blob: a14a295f25bf460ebd2cf496a14f38b53c9fd97d [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 Srbecky09c2a6b2016-03-11 17:11:44 +000049#include "debug/elf_debug_writer.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000050#include "debug/method_debug_info.h"
Mathieu Chartier5bdab122015-01-26 18:30:19 -080051#include "dex/pass_manager.h"
Ian Rogerse63db272014-07-15 15:36:11 -070052#include "dex/quick/dex_file_to_method_inliner_map.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000053#include "dex/quick_compiler_callbacks.h"
54#include "dex/verification_results.h"
55#include "dex_file-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070056#include "driver/compiler_driver.h"
Brian Carlstrom6449c622014-02-10 23:48:36 -080057#include "driver/compiler_options.h"
Andreas Gampe88ec7f42014-11-05 10:18:32 -080058#include "elf_file.h"
Tong Shen62d1ca32014-09-03 17:24:56 -070059#include "elf_writer.h"
Vladimir Marko10c13562015-11-25 14:33:36 +000060#include "elf_writer_quick.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070061#include "gc/space/image_space.h"
62#include "gc/space/space-inl.h"
63#include "image_writer.h"
Andreas Gampe2969bcd2015-03-09 12:57:41 -070064#include "interpreter/unstarted_runtime.h"
Calin Juravle998c2162015-12-21 15:39:33 +020065#include "jit/offline_profiling_info.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070066#include "leb128.h"
Vladimir Marko944da602016-02-19 12:27:55 +000067#include "linker/multi_oat_relative_patcher.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070068#include "mirror/class-inl.h"
69#include "mirror/class_loader.h"
70#include "mirror/object-inl.h"
71#include "mirror/object_array-inl.h"
72#include "oat_writer.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070073#include "os.h"
74#include "runtime.h"
Vladimir Marko49b0f452015-12-10 13:49:19 +000075#include "runtime_options.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070076#include "ScopedLocalRef.h"
77#include "scoped_thread_state_change.h"
Alex Light53cb16b2014-06-12 11:26:29 -070078#include "utils.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070079#include "well_known_classes.h"
80#include "zip_archive.h"
81
82namespace art {
83
Brian Carlstrom6449c622014-02-10 23:48:36 -080084static int original_argc;
85static char** original_argv;
86
87static std::string CommandLine() {
88 std::vector<std::string> command;
89 for (int i = 0; i < original_argc; ++i) {
90 command.push_back(original_argv[i]);
91 }
92 return Join(command, ' ');
93}
94
Andreas Gampe046c7062015-05-18 23:22:54 -070095// A stripped version. Remove some less essential parameters. If we see a "--zip-fd=" parameter, be
96// even more aggressive. There won't be much reasonable data here for us in that case anyways (the
97// locations are all staged).
98static std::string StrippedCommandLine() {
99 std::vector<std::string> command;
100
101 // Do a pre-pass to look for zip-fd.
102 bool saw_zip_fd = false;
103 for (int i = 0; i < original_argc; ++i) {
104 if (StartsWith(original_argv[i], "--zip-fd=")) {
105 saw_zip_fd = true;
106 break;
107 }
108 }
109
110 // Now filter out things.
111 for (int i = 0; i < original_argc; ++i) {
112 // All runtime-arg parameters are dropped.
113 if (strcmp(original_argv[i], "--runtime-arg") == 0) {
114 i++; // Drop the next part, too.
115 continue;
116 }
117
118 // Any instruction-setXXX is dropped.
119 if (StartsWith(original_argv[i], "--instruction-set")) {
120 continue;
121 }
122
123 // The boot image is dropped.
124 if (StartsWith(original_argv[i], "--boot-image=")) {
125 continue;
126 }
127
Mathieu Chartier97590cc2016-02-03 15:50:29 -0800128 // The image format is dropped.
129 if (StartsWith(original_argv[i], "--image-format=")) {
130 continue;
131 }
132
Andreas Gampe046c7062015-05-18 23:22:54 -0700133 // This should leave any dex-file and oat-file options, describing what we compiled.
134
135 // However, we prefer to drop this when we saw --zip-fd.
136 if (saw_zip_fd) {
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700137 // Drop anything --zip-X, --dex-X, --oat-X, --swap-X, or --app-image-X
Andreas Gampe046c7062015-05-18 23:22:54 -0700138 if (StartsWith(original_argv[i], "--zip-") ||
139 StartsWith(original_argv[i], "--dex-") ||
140 StartsWith(original_argv[i], "--oat-") ||
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700141 StartsWith(original_argv[i], "--swap-") ||
142 StartsWith(original_argv[i], "--app-image-")) {
Andreas Gampe046c7062015-05-18 23:22:54 -0700143 continue;
144 }
145 }
146
147 command.push_back(original_argv[i]);
148 }
149
150 // Construct the final output.
151 if (command.size() <= 1U) {
152 // It seems only "/system/bin/dex2oat" is left, or not even that. Use a pretty line.
153 return "Starting dex2oat.";
154 }
155 return Join(command, ' ');
156}
157
Brian Carlstrom7940e442013-07-12 13:46:57 -0700158static void UsageErrorV(const char* fmt, va_list ap) {
159 std::string error;
160 StringAppendV(&error, fmt, ap);
161 LOG(ERROR) << error;
162}
163
164static void UsageError(const char* fmt, ...) {
165 va_list ap;
166 va_start(ap, fmt);
167 UsageErrorV(fmt, ap);
168 va_end(ap);
169}
170
Andreas Gampe794ad762015-02-23 08:12:24 -0800171NO_RETURN static void Usage(const char* fmt, ...) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700172 va_list ap;
173 va_start(ap, fmt);
174 UsageErrorV(fmt, ap);
175 va_end(ap);
176
Brian Carlstrom6449c622014-02-10 23:48:36 -0800177 UsageError("Command: %s", CommandLine().c_str());
178
Brian Carlstrom7940e442013-07-12 13:46:57 -0700179 UsageError("Usage: dex2oat [options]...");
180 UsageError("");
Jean-Philippe Halimi3d329d72015-03-23 14:09:48 +0100181 UsageError(" -j<number>: specifies the number of threads used for compilation.");
182 UsageError(" Default is the number of detected hardware threads available on the");
183 UsageError(" host system.");
184 UsageError(" Example: -j12");
185 UsageError("");
Richard Uhlere934df22015-03-17 11:26:16 -0700186 UsageError(" --dex-file=<dex-file>: specifies a .dex, .jar, or .apk file to compile.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700187 UsageError(" Example: --dex-file=/system/framework/core.jar");
188 UsageError("");
Richard Uhlere934df22015-03-17 11:26:16 -0700189 UsageError(" --dex-location=<dex-location>: specifies an alternative dex location to");
190 UsageError(" encode in the oat file for the corresponding --dex-file argument.");
191 UsageError(" Example: --dex-file=/home/build/out/system/framework/core.jar");
192 UsageError(" --dex-location=/system/framework/core.jar");
193 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700194 UsageError(" --zip-fd=<file-descriptor>: specifies a file descriptor of a zip file");
195 UsageError(" containing a classes.dex file to compile.");
196 UsageError(" Example: --zip-fd=5");
197 UsageError("");
Brian Carlstrom45602482013-07-21 22:07:55 -0700198 UsageError(" --zip-location=<zip-location>: specifies a symbolic name for the file");
199 UsageError(" corresponding to the file descriptor specified by --zip-fd.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700200 UsageError(" Example: --zip-location=/system/app/Calculator.apk");
201 UsageError("");
Jeff Haodcdc85b2015-12-04 14:06:18 -0800202 UsageError(" --oat-file=<file.oat>: specifies an oat output destination via a filename.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700203 UsageError(" Example: --oat-file=/system/framework/boot.oat");
204 UsageError("");
205 UsageError(" --oat-fd=<number>: specifies the oat output destination via a file descriptor.");
Wonil Kim9cb554a2014-04-28 11:26:55 +0900206 UsageError(" Example: --oat-fd=6");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700207 UsageError("");
208 UsageError(" --oat-location=<oat-name>: specifies a symbolic name for the file corresponding");
209 UsageError(" to the file descriptor specified by --oat-fd.");
210 UsageError(" Example: --oat-location=/data/dalvik-cache/system@app@Calculator.apk.oat");
211 UsageError("");
Jeff Haodcdc85b2015-12-04 14:06:18 -0800212 UsageError(" --oat-symbols=<file.oat>: specifies an oat output destination with full symbols.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700213 UsageError(" Example: --oat-symbols=/symbols/system/framework/boot.oat");
214 UsageError("");
Jeff Haodcdc85b2015-12-04 14:06:18 -0800215 UsageError(" --image=<file.art>: specifies an output image filename.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700216 UsageError(" Example: --image=/system/framework/boot.art");
217 UsageError("");
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800218 UsageError(" --image-format=(uncompressed|lz4|lz4hc):");
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800219 UsageError(" Which format to store the image.");
220 UsageError(" Example: --image-format=lz4");
221 UsageError(" Default: uncompressed");
222 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700223 UsageError(" --image-classes=<classname-file>: specifies classes to include in an image.");
224 UsageError(" Example: --image=frameworks/base/preloaded-classes");
225 UsageError("");
226 UsageError(" --base=<hex-address>: specifies the base address when creating a boot image.");
227 UsageError(" Example: --base=0x50000000");
228 UsageError("");
229 UsageError(" --boot-image=<file.art>: provide the image file for the boot class path.");
Kevin Brodsky64fff412015-11-24 14:24:34 +0000230 UsageError(" Do not include the arch as part of the name, it is added automatically.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700231 UsageError(" Example: --boot-image=/system/framework/boot.art");
Kevin Brodsky64fff412015-11-24 14:24:34 +0000232 UsageError(" (specifies /system/framework/<arch>/boot.art as the image file)");
Nicolas Geoffray9583fbc2014-02-28 15:21:07 +0000233 UsageError(" Default: $ANDROID_ROOT/system/framework/boot.art");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700234 UsageError("");
235 UsageError(" --android-root=<path>: used to locate libraries for portable linking.");
236 UsageError(" Example: --android-root=out/host/linux-x86");
237 UsageError(" Default: $ANDROID_ROOT");
238 UsageError("");
Andreas Gampe57b34292015-01-14 15:45:59 -0800239 UsageError(" --instruction-set=(arm|arm64|mips|mips64|x86|x86_64): compile for a particular");
Alex Light53cb16b2014-06-12 11:26:29 -0700240 UsageError(" instruction set.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700241 UsageError(" Example: --instruction-set=x86");
242 UsageError(" Default: arm");
243 UsageError("");
Dave Allison70202782013-10-22 17:52:19 -0700244 UsageError(" --instruction-set-features=...,: Specify instruction set features");
245 UsageError(" Example: --instruction-set-features=div");
246 UsageError(" Default: default");
247 UsageError("");
Igor Murashkin46774762014-10-22 11:37:02 -0700248 UsageError(" --compile-pic: Force indirect use of code, methods, and classes");
249 UsageError(" Default: disabled");
250 UsageError("");
Elliott Hughes956af0f2014-12-11 14:34:28 -0800251 UsageError(" --compiler-backend=(Quick|Optimizing): select compiler backend");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700252 UsageError(" set.");
Elliott Hughes956af0f2014-12-11 14:34:28 -0800253 UsageError(" Example: --compiler-backend=Optimizing");
Nicolas Geoffray409e8092015-10-01 10:32:19 +0100254 UsageError(" Default: Optimizing");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700255 UsageError("");
Nicolas Geoffray88157ef2014-09-12 10:29:53 +0100256 UsageError(" --compiler-filter="
257 "(verify-none"
258 "|interpret-only"
259 "|space"
260 "|balanced"
261 "|speed"
262 "|everything"
263 "|time):");
Jeff Hao4a200f52014-04-01 14:58:49 -0700264 UsageError(" select compiler filter.");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800265 UsageError(" Example: --compiler-filter=everything");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800266 UsageError(" Default: speed");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800267 UsageError("");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800268 UsageError(" --huge-method-max=<method-instruction-count>: threshold size for a huge");
269 UsageError(" method for compiler filter tuning.");
270 UsageError(" Example: --huge-method-max=%d", CompilerOptions::kDefaultHugeMethodThreshold);
271 UsageError(" Default: %d", CompilerOptions::kDefaultHugeMethodThreshold);
272 UsageError("");
273 UsageError(" --large-method-max=<method-instruction-count>: threshold size for a large");
274 UsageError(" method for compiler filter tuning.");
275 UsageError(" Example: --large-method-max=%d", CompilerOptions::kDefaultLargeMethodThreshold);
276 UsageError(" Default: %d", CompilerOptions::kDefaultLargeMethodThreshold);
277 UsageError("");
278 UsageError(" --small-method-max=<method-instruction-count>: threshold size for a small");
279 UsageError(" method for compiler filter tuning.");
280 UsageError(" Example: --small-method-max=%d", CompilerOptions::kDefaultSmallMethodThreshold);
281 UsageError(" Default: %d", CompilerOptions::kDefaultSmallMethodThreshold);
282 UsageError("");
283 UsageError(" --tiny-method-max=<method-instruction-count>: threshold size for a tiny");
284 UsageError(" method for compiler filter tuning.");
285 UsageError(" Example: --tiny-method-max=%d", CompilerOptions::kDefaultTinyMethodThreshold);
286 UsageError(" Default: %d", CompilerOptions::kDefaultTinyMethodThreshold);
287 UsageError("");
288 UsageError(" --num-dex-methods=<method-count>: threshold size for a small dex file for");
289 UsageError(" compiler filter tuning. If the input has fewer than this many methods");
Jeff Hao4a200f52014-04-01 14:58:49 -0700290 UsageError(" and the filter is not interpret-only or verify-none, overrides the");
291 UsageError(" filter to use speed");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800292 UsageError(" Example: --num-dex-method=%d", CompilerOptions::kDefaultNumDexMethodsThreshold);
293 UsageError(" Default: %d", CompilerOptions::kDefaultNumDexMethodsThreshold);
294 UsageError("");
Calin Juravleec748352015-07-29 13:52:12 +0100295 UsageError(" --inline-depth-limit=<depth-limit>: the depth limit of inlining for fine tuning");
296 UsageError(" the compiler. A zero value will disable inlining. Honored only by Optimizing.");
Roland Levillaina215b952015-08-07 11:38:32 +0100297 UsageError(" Has priority over the --compiler-filter option. Intended for ");
298 UsageError(" development/experimental use.");
Calin Juravleec748352015-07-29 13:52:12 +0100299 UsageError(" Example: --inline-depth-limit=%d", CompilerOptions::kDefaultInlineDepthLimit);
300 UsageError(" Default: %d", CompilerOptions::kDefaultInlineDepthLimit);
301 UsageError("");
302 UsageError(" --inline-max-code-units=<code-units-count>: the maximum code units that a method");
303 UsageError(" can have to be considered for inlining. A zero value will disable inlining.");
Roland Levillaina215b952015-08-07 11:38:32 +0100304 UsageError(" Honored only by Optimizing. Has priority over the --compiler-filter option.");
305 UsageError(" Intended for development/experimental use.");
Calin Juravleec748352015-07-29 13:52:12 +0100306 UsageError(" Example: --inline-max-code-units=%d",
307 CompilerOptions::kDefaultInlineMaxCodeUnits);
308 UsageError(" Default: %d", CompilerOptions::kDefaultInlineMaxCodeUnits);
309 UsageError("");
Ian Rogers46398602013-08-20 07:50:36 -0700310 UsageError(" --dump-timing: display a breakdown of where time was spent");
311 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700312 UsageError(" --include-patch-information: Include patching information so the generated code");
313 UsageError(" can have its base address moved without full recompilation.");
314 UsageError("");
315 UsageError(" --no-include-patch-information: Do not include patching information.");
316 UsageError("");
David Srbecky8363c772015-05-28 16:12:43 +0100317 UsageError(" -g");
318 UsageError(" --generate-debug-info: Generate debug information for native debugging,");
319 UsageError(" such as stack unwinding information, ELF symbols and DWARF sections.");
David Srbecky3e09eeb2016-01-12 14:54:03 +0000320 UsageError(" If used without --native-debuggable, it will be best-effort only.");
321 UsageError(" This option does not affect the generated code. (disabled by default)");
Alex Light78382fa2014-06-06 15:45:32 -0700322 UsageError("");
David Srbecky8363c772015-05-28 16:12:43 +0100323 UsageError(" --no-generate-debug-info: Do not generate debug information for native debugging.");
David Srbecky8dc73242015-04-12 11:40:39 +0100324 UsageError("");
David Srbecky5b1c2ca2016-01-25 17:32:41 +0000325 UsageError(" --generate-mini-debug-info: Generate minimal amount of LZMA-compressed");
326 UsageError(" debug information necessary to print backtraces. (disabled by default)");
327 UsageError("");
328 UsageError(" --no-generate-mini-debug-info: Do do generated backtrace info.");
329 UsageError("");
David Srbecky3e09eeb2016-01-12 14:54:03 +0000330 UsageError(" --debuggable: Produce code debuggable with Java debugger.");
David Srbecky0cf44932015-12-09 14:09:59 +0000331 UsageError("");
332 UsageError(" --native-debuggable: Produce code debuggable with native debugger (like LLDB).");
333 UsageError(" Implies --debuggable.");
334 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700335 UsageError(" --runtime-arg <argument>: used to specify various arguments for the runtime,");
336 UsageError(" such as initial heap size, maximum heap size, and verbose output.");
337 UsageError(" Use a separate --runtime-arg switch for each argument.");
338 UsageError(" Example: --runtime-arg -Xms256m");
Jeff Hao4a200f52014-04-01 14:58:49 -0700339 UsageError("");
Dave Allisond6ed6422014-04-09 23:36:15 +0000340 UsageError(" --profile-file=<filename>: specify profiler output file to use for compilation.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700341 UsageError("");
Calin Juravle877fd962016-01-05 14:29:29 +0000342 UsageError(" --profile-file-fd=<number>: same as --profile-file but accepts a file descriptor.");
343 UsageError(" Cannot be used together with --profile-file.");
344 UsageError("");
Chao-ying Fucd8ce662014-03-11 14:57:19 -0700345 UsageError(" --print-pass-names: print a list of pass names");
346 UsageError("");
347 UsageError(" --disable-passes=<pass-names>: disable one or more passes separated by comma.");
348 UsageError(" Example: --disable-passes=UseCount,BBOptimizations");
349 UsageError("");
Razvan A Lupusorubd25d4b2014-07-02 18:16:51 -0700350 UsageError(" --print-pass-options: print a list of passes that have configurable options along "
351 "with the setting.");
352 UsageError(" Will print default if no overridden setting exists.");
353 UsageError("");
354 UsageError(" --pass-options=Pass1Name:Pass1OptionName:Pass1Option#,"
355 "Pass2Name:Pass2OptionName:Pass2Option#");
356 UsageError(" Used to specify a pass specific option. The setting itself must be integer.");
357 UsageError(" Separator used between options is a comma.");
358 UsageError("");
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800359 UsageError(" --swap-file=<file-name>: specifies a file to use for swap.");
360 UsageError(" Example: --swap-file=/data/tmp/swap.001");
361 UsageError("");
362 UsageError(" --swap-fd=<file-descriptor>: specifies a file to use for swap (by descriptor).");
363 UsageError(" Example: --swap-fd=10");
364 UsageError("");
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700365 UsageError(" --app-image-fd=<file-descriptor>: specify output file descriptor for app image.");
366 UsageError(" Example: --app-image-fd=10");
367 UsageError("");
368 UsageError(" --app-image-file=<file-name>: specify a file name for app image.");
369 UsageError(" Example: --app-image-file=/data/dalvik-cache/system@app@Calculator.apk.art");
370 UsageError("");
Jeff Haodcdc85b2015-12-04 14:06:18 -0800371 UsageError(" --multi-image: specify that separate oat and image files be generated for each "
372 "input dex file.");
373 UsageError("");
Roland Levillaineb2c7412016-01-28 14:37:01 +0000374 UsageError(" --force-determinism: force the compiler to emit a deterministic output.");
375 UsageError(" This option is incompatible with read barriers (e.g., if dex2oat has been");
376 UsageError(" built with the environment variable `ART_USE_READ_BARRIER` set to `true`).");
377 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700378 std::cerr << "See log for usage error information\n";
379 exit(EXIT_FAILURE);
380}
381
Brian Carlstrom7940e442013-07-12 13:46:57 -0700382// The primary goal of the watchdog is to prevent stuck build servers
383// during development when fatal aborts lead to a cascade of failures
384// that result in a deadlock.
385class WatchDog {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800386// WatchDog defines its own CHECK_PTHREAD_CALL to avoid using LOG which uses locks
Brian Carlstrom7940e442013-07-12 13:46:57 -0700387#undef CHECK_PTHREAD_CALL
388#define CHECK_WATCH_DOG_PTHREAD_CALL(call, args, what) \
389 do { \
390 int rc = call args; \
391 if (rc != 0) { \
392 errno = rc; \
393 std::string message(# call); \
394 message += " failed for "; \
395 message += reason; \
396 Fatal(message); \
397 } \
398 } while (false)
399
400 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -0700401 explicit WatchDog(bool is_watch_dog_enabled) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700402 is_watch_dog_enabled_ = is_watch_dog_enabled;
403 if (!is_watch_dog_enabled_) {
404 return;
405 }
406 shutting_down_ = false;
407 const char* reason = "dex2oat watch dog thread startup";
Kenny Root51316382014-05-13 14:59:37 -0700408 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_init, (&mutex_, nullptr), reason);
409 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_init, (&cond_, nullptr), reason);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700410 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_init, (&attr_), reason);
411 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_create, (&pthread_, &attr_, &CallBack, this), reason);
412 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_destroy, (&attr_), reason);
413 }
414 ~WatchDog() {
415 if (!is_watch_dog_enabled_) {
416 return;
417 }
418 const char* reason = "dex2oat watch dog thread shutdown";
419 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
420 shutting_down_ = true;
421 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_signal, (&cond_), reason);
422 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
423
Kenny Root51316382014-05-13 14:59:37 -0700424 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_join, (pthread_, nullptr), reason);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700425
426 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_destroy, (&cond_), reason);
427 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_destroy, (&mutex_), reason);
428 }
429
430 private:
431 static void* CallBack(void* arg) {
432 WatchDog* self = reinterpret_cast<WatchDog*>(arg);
433 ::art::SetThreadName("dex2oat watch dog");
434 self->Wait();
Kenny Root51316382014-05-13 14:59:37 -0700435 return nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700436 }
437
Andreas Gampe794ad762015-02-23 08:12:24 -0800438 NO_RETURN static void Fatal(const std::string& message) {
Andreas Gamped687e372015-04-28 23:16:03 -0700439 // TODO: When we can guarantee it won't prevent shutdown in error cases, move to LOG. However,
440 // it's rather easy to hang in unwinding.
441 // LogLine also avoids ART logging lock issues, as it's really only a wrapper around
442 // logcat logging or stderr output.
443 LogMessage::LogLine(__FILE__, __LINE__, LogSeverity::FATAL, message.c_str());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700444 exit(1);
445 }
446
447 void Wait() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700448 // TODO: tune the multiplier for GC verification, the following is just to make the timeout
449 // large.
Andreas Gamped687e372015-04-28 23:16:03 -0700450 constexpr int64_t multiplier = kVerifyObjectSupport > kVerifyObjectModeFast ? 100 : 1;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700451 timespec timeout_ts;
452 InitTimeSpec(true, CLOCK_REALTIME, multiplier * kWatchDogTimeoutSeconds * 1000, 0, &timeout_ts);
453 const char* reason = "dex2oat watch dog thread waiting";
454 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
455 while (!shutting_down_) {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800456 int rc = TEMP_FAILURE_RETRY(pthread_cond_timedwait(&cond_, &mutex_, &timeout_ts));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700457 if (rc == ETIMEDOUT) {
Andreas Gamped687e372015-04-28 23:16:03 -0700458 Fatal(StringPrintf("dex2oat did not finish after %" PRId64 " seconds",
459 kWatchDogTimeoutSeconds));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700460 } else if (rc != 0) {
461 std::string message(StringPrintf("pthread_cond_timedwait failed: %s",
462 strerror(errno)));
463 Fatal(message.c_str());
464 }
465 }
466 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
467 }
468
469 // When setting timeouts, keep in mind that the build server may not be as fast as your desktop.
Mathieu Chartier13b9f432014-09-09 17:26:58 -0700470 // Debug builds are slower so they have larger timeouts.
Andreas Gamped687e372015-04-28 23:16:03 -0700471 static constexpr int64_t kSlowdownFactor = kIsDebugBuild ? 5U : 1U;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800472
Andreas Gampe540138a2015-09-14 15:34:38 -0700473 // 9.5 minutes scaled by kSlowdownFactor. This is slightly smaller than the Package Manager
474 // watchdog (PackageManagerService.WATCHDOG_TIMEOUT, 10 minutes), so that dex2oat will abort
475 // itself before that watchdog would take down the system server.
476 static constexpr int64_t kWatchDogTimeoutSeconds = kSlowdownFactor * (9 * 60 + 30);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700477
478 bool is_watch_dog_enabled_;
479 bool shutting_down_;
480 // TODO: Switch to Mutex when we can guarantee it won't prevent shutdown in error cases.
481 pthread_mutex_t mutex_;
482 pthread_cond_t cond_;
483 pthread_attr_t attr_;
484 pthread_t pthread_;
485};
Brian Carlstrom7940e442013-07-12 13:46:57 -0700486
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800487static constexpr size_t kMinDexFilesForSwap = 2;
488static constexpr size_t kMinDexFileCumulativeSizeForSwap = 20 * MB;
489
490static bool UseSwap(bool is_image, std::vector<const DexFile*>& dex_files) {
491 if (is_image) {
492 // Don't use swap, we know generation should succeed, and we don't want to slow it down.
493 return false;
494 }
495 if (dex_files.size() < kMinDexFilesForSwap) {
496 // If there are less dex files than the threshold, assume it's gonna be fine.
497 return false;
498 }
499 size_t dex_files_size = 0;
500 for (const auto* dex_file : dex_files) {
501 dex_files_size += dex_file->GetHeader().file_size_;
502 }
503 return dex_files_size >= kMinDexFileCumulativeSizeForSwap;
504}
505
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800506class Dex2Oat FINAL {
507 public:
508 explicit Dex2Oat(TimingLogger* timings) :
Nicolas Geoffray409e8092015-10-01 10:32:19 +0100509 compiler_kind_(Compiler::kOptimizing),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800510 instruction_set_(kRuntimeISA),
511 // Take the default set of instruction features from the build.
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000512 image_file_location_oat_checksum_(0),
513 image_file_location_oat_data_begin_(0),
514 image_patch_delta_(0),
515 key_value_store_(nullptr),
Andreas Gampe3f30e122015-09-17 14:03:21 -0700516 verification_results_(nullptr),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800517 method_inliner_map_(),
518 runtime_(nullptr),
519 thread_count_(sysconf(_SC_NPROCESSORS_CONF)),
520 start_ns_(NanoTime()),
521 oat_fd_(-1),
522 zip_fd_(-1),
523 image_base_(0U),
524 image_classes_zip_filename_(nullptr),
525 image_classes_filename_(nullptr),
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800526 image_storage_mode_(ImageHeader::kStorageModeUncompressed),
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800527 compiled_classes_zip_filename_(nullptr),
528 compiled_classes_filename_(nullptr),
Andreas Gampe70bef0d2015-04-15 02:37:28 -0700529 compiled_methods_zip_filename_(nullptr),
530 compiled_methods_filename_(nullptr),
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700531 app_image_(false),
532 boot_image_(false),
Jeff Hao436183f2016-01-12 16:36:50 -0800533 multi_image_(false),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800534 is_host_(false),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000535 class_loader_(nullptr),
536 elf_writers_(),
537 oat_writers_(),
538 rodata_(),
Vladimir Marko10c13562015-11-25 14:33:36 +0000539 image_writer_(nullptr),
Andreas Gampe3f30e122015-09-17 14:03:21 -0700540 driver_(nullptr),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000541 opened_dex_files_maps_(),
542 opened_dex_files_(),
Vladimir Marko47496c22016-01-27 16:15:08 +0000543 no_inline_from_dex_files_(),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800544 dump_stats_(false),
545 dump_passes_(false),
546 dump_timing_(false),
547 dump_slow_timing_(kIsDebugBuild),
Calin Juravle2e2db782016-02-23 12:00:03 +0000548 swap_fd_(kInvalidFd),
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800549 app_image_fd_(kInvalidFd),
Calin Juravle2e2db782016-02-23 12:00:03 +0000550 profile_file_fd_(kInvalidFd),
Andreas Gampeace0dc12016-01-20 13:33:13 -0800551 timings_(timings),
Calin Juravle2e2db782016-02-23 12:00:03 +0000552 force_determinism_(false)
553 {}
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800554
555 ~Dex2Oat() {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800556 // Log completion time before deleting the runtime_, because this accesses
557 // the runtime.
558 LogCompletionTime();
559
Vladimir Marko307dac92015-10-20 11:20:09 +0100560 if (!kIsDebugBuild && !(RUNNING_ON_MEMORY_TOOL && kMemoryToolDetectsLeaks)) {
561 // We want to just exit on non-debug builds, not bringing the runtime down
562 // in an orderly fashion. So release the following fields.
563 driver_.release();
564 image_writer_.release();
565 for (std::unique_ptr<const DexFile>& dex_file : opened_dex_files_) {
566 dex_file.release();
567 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000568 for (std::unique_ptr<MemMap>& map : opened_dex_files_maps_) {
569 map.release();
570 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800571 for (std::unique_ptr<File>& oat_file : oat_files_) {
572 oat_file.release();
573 }
Vladimir Marko307dac92015-10-20 11:20:09 +0100574 runtime_.release();
575 verification_results_.release();
576 key_value_store_.release();
Vladimir Markof94b7812014-06-05 15:48:04 +0100577 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700578 }
579
Roland Levillain9ec5e222015-08-17 20:18:41 +0100580 struct ParserOptions {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800581 std::vector<const char*> oat_symbols;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800582 std::string boot_image_filename;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800583 bool watch_dog_enabled = true;
Nicolas Geoffray1412dfa2015-03-20 14:48:13 +0000584 bool requested_specific_compiler = false;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800585 std::string error_msg;
Roland Levillain9ec5e222015-08-17 20:18:41 +0100586 };
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800587
Roland Levillain9ec5e222015-08-17 20:18:41 +0100588 void ParseZipFd(const StringPiece& option) {
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000589 ParseUintOption(option, "--zip-fd", &zip_fd_, Usage);
Roland Levillain9ec5e222015-08-17 20:18:41 +0100590 }
591
592 void ParseOatFd(const StringPiece& option) {
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000593 ParseUintOption(option, "--oat-fd", &oat_fd_, Usage);
Roland Levillain9ec5e222015-08-17 20:18:41 +0100594 }
595
Calin Juravle877fd962016-01-05 14:29:29 +0000596 void ParseFdForCollection(const StringPiece& option,
597 const char* arg_name,
598 std::vector<uint32_t>* fds) {
599 uint32_t fd;
600 ParseUintOption(option, arg_name, &fd, Usage);
601 fds->push_back(fd);
602 }
603
Roland Levillain9ec5e222015-08-17 20:18:41 +0100604 void ParseJ(const StringPiece& option) {
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000605 ParseUintOption(option, "-j", &thread_count_, Usage, /* is_long_option */ false);
Roland Levillain9ec5e222015-08-17 20:18:41 +0100606 }
607
608 void ParseBase(const StringPiece& option) {
609 DCHECK(option.starts_with("--base="));
610 const char* image_base_str = option.substr(strlen("--base=")).data();
611 char* end;
612 image_base_ = strtoul(image_base_str, &end, 16);
613 if (end == image_base_str || *end != '\0') {
614 Usage("Failed to parse hexadecimal value for option %s", option.data());
615 }
616 }
617
618 void ParseInstructionSet(const StringPiece& option) {
619 DCHECK(option.starts_with("--instruction-set="));
620 StringPiece instruction_set_str = option.substr(strlen("--instruction-set=")).data();
621 // StringPiece is not necessarily zero-terminated, so need to make a copy and ensure it.
622 std::unique_ptr<char[]> buf(new char[instruction_set_str.length() + 1]);
623 strncpy(buf.get(), instruction_set_str.data(), instruction_set_str.length());
624 buf.get()[instruction_set_str.length()] = 0;
625 instruction_set_ = GetInstructionSetFromString(buf.get());
626 // arm actually means thumb2.
627 if (instruction_set_ == InstructionSet::kArm) {
628 instruction_set_ = InstructionSet::kThumb2;
629 }
630 }
631
632 void ParseInstructionSetVariant(const StringPiece& option, ParserOptions* parser_options) {
633 DCHECK(option.starts_with("--instruction-set-variant="));
634 StringPiece str = option.substr(strlen("--instruction-set-variant=")).data();
635 instruction_set_features_.reset(
636 InstructionSetFeatures::FromVariant(
637 instruction_set_, str.as_string(), &parser_options->error_msg));
638 if (instruction_set_features_.get() == nullptr) {
639 Usage("%s", parser_options->error_msg.c_str());
640 }
641 }
642
643 void ParseInstructionSetFeatures(const StringPiece& option, ParserOptions* parser_options) {
644 DCHECK(option.starts_with("--instruction-set-features="));
645 StringPiece str = option.substr(strlen("--instruction-set-features=")).data();
646 if (instruction_set_features_.get() == nullptr) {
647 instruction_set_features_.reset(
648 InstructionSetFeatures::FromVariant(
649 instruction_set_, "default", &parser_options->error_msg));
650 if (instruction_set_features_.get() == nullptr) {
651 Usage("Problem initializing default instruction set features variant: %s",
652 parser_options->error_msg.c_str());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700653 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800654 }
Roland Levillain9ec5e222015-08-17 20:18:41 +0100655 instruction_set_features_.reset(
656 instruction_set_features_->AddFeaturesFromString(str.as_string(),
657 &parser_options->error_msg));
658 if (instruction_set_features_.get() == nullptr) {
659 Usage("Error parsing '%s': %s", option.data(), parser_options->error_msg.c_str());
660 }
661 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800662
Roland Levillain9ec5e222015-08-17 20:18:41 +0100663 void ParseCompilerBackend(const StringPiece& option, ParserOptions* parser_options) {
664 DCHECK(option.starts_with("--compiler-backend="));
665 parser_options->requested_specific_compiler = true;
666 StringPiece backend_str = option.substr(strlen("--compiler-backend=")).data();
667 if (backend_str == "Quick") {
668 compiler_kind_ = Compiler::kQuick;
669 } else if (backend_str == "Optimizing") {
670 compiler_kind_ = Compiler::kOptimizing;
671 } else {
672 Usage("Unknown compiler backend: %s", backend_str.data());
673 }
674 }
675
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800676 void ParseImageFormat(const StringPiece& option) {
677 const StringPiece substr("--image-format=");
678 DCHECK(option.starts_with(substr));
679 const StringPiece format_str = option.substr(substr.length());
680 if (format_str == "lz4") {
681 image_storage_mode_ = ImageHeader::kStorageModeLZ4;
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800682 } else if (format_str == "lz4hc") {
683 image_storage_mode_ = ImageHeader::kStorageModeLZ4HC;
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800684 } else if (format_str == "uncompressed") {
685 image_storage_mode_ = ImageHeader::kStorageModeUncompressed;
686 } else {
687 Usage("Unknown image format: %s", format_str.data());
688 }
689 }
690
Jeff Hao436183f2016-01-12 16:36:50 -0800691 void ProcessOptions(ParserOptions* parser_options) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800692 boot_image_ = !image_filenames_.empty();
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700693 app_image_ = app_image_fd_ != -1 || !app_image_file_name_.empty();
694
695 if (IsAppImage() && IsBootImage()) {
696 Usage("Can't have both --image and (--app-image-fd or --app-image-file)");
697 }
698
Nicolas Geoffray0c6e3342016-03-04 11:38:14 +0000699 if (IsBootImage()) {
700 // We need the boot image to always be debuggable.
701 // TODO: Remove this once we better deal with full frame deoptimization.
702 compiler_options_->debuggable_ = true;
703 }
704
Jeff Haodcdc85b2015-12-04 14:06:18 -0800705 if (oat_filenames_.empty() && oat_fd_ == -1) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800706 Usage("Output must be supplied with either --oat-file or --oat-fd");
707 }
708
Jeff Haodcdc85b2015-12-04 14:06:18 -0800709 if (!oat_filenames_.empty() && oat_fd_ != -1) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800710 Usage("--oat-file should not be used with --oat-fd");
711 }
712
Roland Levillain9ec5e222015-08-17 20:18:41 +0100713 if (!parser_options->oat_symbols.empty() && oat_fd_ != -1) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800714 Usage("--oat-symbols should not be used with --oat-fd");
715 }
716
Roland Levillain9ec5e222015-08-17 20:18:41 +0100717 if (!parser_options->oat_symbols.empty() && is_host_) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800718 Usage("--oat-symbols should not be used with --host");
719 }
720
Jeff Haodcdc85b2015-12-04 14:06:18 -0800721 if (oat_fd_ != -1 && !image_filenames_.empty()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800722 Usage("--oat-fd should not be used with --image");
723 }
724
Jeff Haodcdc85b2015-12-04 14:06:18 -0800725 if (!parser_options->oat_symbols.empty() &&
726 parser_options->oat_symbols.size() != oat_filenames_.size()) {
727 Usage("--oat-file arguments do not match --oat-symbols arguments");
728 }
729
730 if (!image_filenames_.empty() && image_filenames_.size() != oat_filenames_.size()) {
731 Usage("--oat-file arguments do not match --image arguments");
732 }
733
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800734 if (android_root_.empty()) {
735 const char* android_root_env_var = getenv("ANDROID_ROOT");
736 if (android_root_env_var == nullptr) {
737 Usage("--android-root unspecified and ANDROID_ROOT not set");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700738 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800739 android_root_ += android_root_env_var;
740 }
741
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700742 if (!boot_image_ && parser_options->boot_image_filename.empty()) {
Roland Levillain9ec5e222015-08-17 20:18:41 +0100743 parser_options->boot_image_filename += android_root_;
744 parser_options->boot_image_filename += "/framework/boot.art";
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800745 }
Roland Levillain9ec5e222015-08-17 20:18:41 +0100746 if (!parser_options->boot_image_filename.empty()) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000747 boot_image_filename_ = parser_options->boot_image_filename;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800748 }
749
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700750 if (image_classes_filename_ != nullptr && !IsBootImage()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800751 Usage("--image-classes should only be used with --image");
752 }
753
Vladimir Marko49b0f452015-12-10 13:49:19 +0000754 if (image_classes_filename_ != nullptr && !boot_image_filename_.empty()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800755 Usage("--image-classes should not be used with --boot-image");
756 }
757
758 if (image_classes_zip_filename_ != nullptr && image_classes_filename_ == nullptr) {
759 Usage("--image-classes-zip should be used with --image-classes");
760 }
761
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700762 if (compiled_classes_filename_ != nullptr && !IsBootImage()) {
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800763 Usage("--compiled-classes should only be used with --image");
764 }
765
Vladimir Marko49b0f452015-12-10 13:49:19 +0000766 if (compiled_classes_filename_ != nullptr && !boot_image_filename_.empty()) {
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800767 Usage("--compiled-classes should not be used with --boot-image");
768 }
769
770 if (compiled_classes_zip_filename_ != nullptr && compiled_classes_filename_ == nullptr) {
771 Usage("--compiled-classes-zip should be used with --compiled-classes");
772 }
773
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800774 if (dex_filenames_.empty() && zip_fd_ == -1) {
775 Usage("Input must be supplied with either --dex-file or --zip-fd");
776 }
777
778 if (!dex_filenames_.empty() && zip_fd_ != -1) {
779 Usage("--dex-file should not be used with --zip-fd");
780 }
781
782 if (!dex_filenames_.empty() && !zip_location_.empty()) {
783 Usage("--dex-file should not be used with --zip-location");
784 }
785
786 if (dex_locations_.empty()) {
787 for (const char* dex_file_name : dex_filenames_) {
788 dex_locations_.push_back(dex_file_name);
789 }
790 } else if (dex_locations_.size() != dex_filenames_.size()) {
791 Usage("--dex-location arguments do not match --dex-file arguments");
792 }
793
Jeff Haodcdc85b2015-12-04 14:06:18 -0800794 if (!dex_filenames_.empty() && !oat_filenames_.empty()) {
795 if (oat_filenames_.size() != 1 && oat_filenames_.size() != dex_filenames_.size()) {
796 Usage("--oat-file arguments must be singular or match --dex-file arguments");
797 }
798 }
799
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800800 if (zip_fd_ != -1 && zip_location_.empty()) {
801 Usage("--zip-location should be supplied with --zip-fd");
802 }
803
Vladimir Marko49b0f452015-12-10 13:49:19 +0000804 if (boot_image_filename_.empty()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800805 if (image_base_ == 0) {
806 Usage("Non-zero --base not specified");
807 }
808 }
809
Calin Juravle2e2db782016-02-23 12:00:03 +0000810 if (!profile_file_.empty() && (profile_file_fd_ != kInvalidFd)) {
811 Usage("Profile file should not be specified with both --profile-file-fd and --profile-file");
Calin Juravle998c2162015-12-21 15:39:33 +0200812 }
813
Roland Levillain9ec5e222015-08-17 20:18:41 +0100814 if (!parser_options->oat_symbols.empty()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800815 oat_unstripped_ = std::move(parser_options->oat_symbols);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800816 }
817
818 // If no instruction set feature was given, use the default one for the target
819 // instruction set.
820 if (instruction_set_features_.get() == nullptr) {
821 instruction_set_features_.reset(
Roland Levillain9ec5e222015-08-17 20:18:41 +0100822 InstructionSetFeatures::FromVariant(
823 instruction_set_, "default", &parser_options->error_msg));
Ian Rogersd582fa42014-11-05 23:46:43 -0800824 if (instruction_set_features_.get() == nullptr) {
825 Usage("Problem initializing default instruction set features variant: %s",
Roland Levillain9ec5e222015-08-17 20:18:41 +0100826 parser_options->error_msg.c_str());
Ian Rogersd582fa42014-11-05 23:46:43 -0800827 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800828 }
829
830 if (instruction_set_ == kRuntimeISA) {
831 std::unique_ptr<const InstructionSetFeatures> runtime_features(
832 InstructionSetFeatures::FromCppDefines());
833 if (!instruction_set_features_->Equals(runtime_features.get())) {
834 LOG(WARNING) << "Mismatch between dex2oat instruction set features ("
835 << *instruction_set_features_ << ") and those of dex2oat executable ("
836 << *runtime_features <<") for the command line:\n"
837 << CommandLine();
838 }
839 }
840
Roland Levillaina215b952015-08-07 11:38:32 +0100841 // It they are not set, use default values for inlining settings.
842 // TODO: We should rethink the compiler filter. We mostly save
843 // time here, which is orthogonal to space.
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000844 if (compiler_options_->inline_depth_limit_ == CompilerOptions::kUnsetInlineDepthLimit) {
845 compiler_options_->inline_depth_limit_ =
846 (compiler_options_->compiler_filter_ == CompilerOptions::kSpace)
Roland Levillaina215b952015-08-07 11:38:32 +0100847 // Implementation of the space filter: limit inlining depth.
848 ? CompilerOptions::kSpaceFilterInlineDepthLimit
849 : CompilerOptions::kDefaultInlineDepthLimit;
850 }
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000851 if (compiler_options_->inline_max_code_units_ == CompilerOptions::kUnsetInlineMaxCodeUnits) {
852 compiler_options_->inline_max_code_units_ =
853 (compiler_options_->compiler_filter_ == CompilerOptions::kSpace)
Roland Levillaina215b952015-08-07 11:38:32 +0100854 // Implementation of the space filter: limit inlining max code units.
855 ? CompilerOptions::kSpaceFilterInlineMaxCodeUnits
856 : CompilerOptions::kDefaultInlineMaxCodeUnits;
857 }
858
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800859 // Checks are all explicit until we know the architecture.
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800860 // Set the compilation target's implicit checks options.
861 switch (instruction_set_) {
862 case kArm:
863 case kThumb2:
864 case kArm64:
865 case kX86:
866 case kX86_64:
Douglas Leung22bb5a22015-07-02 16:42:08 -0700867 case kMips:
868 case kMips64:
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000869 compiler_options_->implicit_null_checks_ = true;
870 compiler_options_->implicit_so_checks_ = true;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800871 break;
872
873 default:
874 // Defaults are correct.
875 break;
876 }
877
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000878 compiler_options_->verbose_methods_ = verbose_methods_.empty() ? nullptr : &verbose_methods_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800879
Jeff Hao436183f2016-01-12 16:36:50 -0800880 if (!IsBootImage() && multi_image_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800881 Usage("--multi-image can only be used when creating boot images");
882 }
Jeff Hao436183f2016-01-12 16:36:50 -0800883 if (IsBootImage() && multi_image_ && image_filenames_.size() > 1) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800884 Usage("--multi-image cannot be used with multiple image names");
885 }
886
887 // For now, if we're on the host and compile the boot image, *always* use multiple image files.
888 if (!kIsTargetBuild && IsBootImage()) {
889 if (image_filenames_.size() == 1) {
Jeff Hao436183f2016-01-12 16:36:50 -0800890 multi_image_ = true;
Jeff Haodcdc85b2015-12-04 14:06:18 -0800891 }
892 }
893
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800894 // Done with usage checks, enable watchdog if requested
Roland Levillain9ec5e222015-08-17 20:18:41 +0100895 if (parser_options->watch_dog_enabled) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800896 watchdog_.reset(new WatchDog(true));
897 }
898
899 // Fill some values into the key-value store for the oat header.
900 key_value_store_.reset(new SafeMap<std::string, std::string>());
Andreas Gampeace0dc12016-01-20 13:33:13 -0800901
Hiroshi Yamauchi6af53482016-01-29 15:38:58 -0800902 // Automatically force determinism for the boot image in a host build if the default GC is CMS
903 // or MS and read barriers are not enabled, as the former switches the GC to a non-concurrent
904 // one by passing the option `-Xgc:nonconcurrent` (see below).
905 if (!kIsTargetBuild && IsBootImage()) {
906 if (SupportsDeterministicCompilation()) {
907 force_determinism_ = true;
908 } else {
909 LOG(WARNING) << "Deterministic compilation is disabled.";
910 }
Andreas Gampeace0dc12016-01-20 13:33:13 -0800911 }
912 compiler_options_->force_determinism_ = force_determinism_;
Roland Levillain9ec5e222015-08-17 20:18:41 +0100913 }
914
Hiroshi Yamauchi6af53482016-01-29 15:38:58 -0800915 static bool SupportsDeterministicCompilation() {
916 return (gc::kCollectorTypeDefault == gc::kCollectorTypeCMS ||
917 gc::kCollectorTypeDefault == gc::kCollectorTypeMS) &&
918 !kEmitCompilerReadBarrier;
919 }
920
Jeff Hao436183f2016-01-12 16:36:50 -0800921 void ExpandOatAndImageFilenames() {
922 std::string base_oat = oat_filenames_[0];
923 size_t last_oat_slash = base_oat.rfind('/');
924 if (last_oat_slash == std::string::npos) {
925 Usage("--multi-image used with unusable oat filename %s", base_oat.c_str());
926 }
927 // We also need to honor path components that were encoded through '@'. Otherwise the loading
928 // code won't be able to find the images.
929 if (base_oat.find('@', last_oat_slash) != std::string::npos) {
930 last_oat_slash = base_oat.rfind('@');
931 }
932 base_oat = base_oat.substr(0, last_oat_slash + 1);
933
934 std::string base_img = image_filenames_[0];
935 size_t last_img_slash = base_img.rfind('/');
936 if (last_img_slash == std::string::npos) {
937 Usage("--multi-image used with unusable image filename %s", base_img.c_str());
938 }
939 // We also need to honor path components that were encoded through '@'. Otherwise the loading
940 // code won't be able to find the images.
941 if (base_img.find('@', last_img_slash) != std::string::npos) {
942 last_img_slash = base_img.rfind('@');
943 }
944
945 // Get the prefix, which is the primary image name (without path components). Strip the
946 // extension.
947 std::string prefix = base_img.substr(last_img_slash + 1);
948 if (prefix.rfind('.') != std::string::npos) {
949 prefix = prefix.substr(0, prefix.rfind('.'));
950 }
951 if (!prefix.empty()) {
952 prefix = prefix + "-";
953 }
954
955 base_img = base_img.substr(0, last_img_slash + 1);
956
957 // Note: we have some special case here for our testing. We have to inject the differentiating
958 // parts for the different core images.
959 std::string infix; // Empty infix by default.
960 {
961 // Check the first name.
962 std::string dex_file = oat_filenames_[0];
963 size_t last_dex_slash = dex_file.rfind('/');
964 if (last_dex_slash != std::string::npos) {
965 dex_file = dex_file.substr(last_dex_slash + 1);
966 }
967 size_t last_dex_dot = dex_file.rfind('.');
968 if (last_dex_dot != std::string::npos) {
969 dex_file = dex_file.substr(0, last_dex_dot);
970 }
971 if (StartsWith(dex_file, "core-")) {
972 infix = dex_file.substr(strlen("core"));
973 }
974 }
975
976 // Now create the other names. Use a counted loop to skip the first one.
977 for (size_t i = 1; i < dex_locations_.size(); ++i) {
978 // TODO: Make everything properly std::string.
979 std::string image_name = CreateMultiImageName(dex_locations_[i], prefix, infix, ".art");
980 char_backing_storage_.push_back(base_img + image_name);
981 image_filenames_.push_back((char_backing_storage_.end() - 1)->c_str());
982
983 std::string oat_name = CreateMultiImageName(dex_locations_[i], prefix, infix, ".oat");
984 char_backing_storage_.push_back(base_oat + oat_name);
985 oat_filenames_.push_back((char_backing_storage_.end() - 1)->c_str());
986 }
987 }
988
Andreas Gampe8994a042015-12-30 19:03:17 +0000989 // Modify the input string in the following way:
990 // 0) Assume input is /a/b/c.d
991 // 1) Strip the path -> c.d
992 // 2) Inject prefix p -> pc.d
993 // 3) Inject infix i -> pci.d
994 // 4) Replace suffix with s if it's "jar" -> d == "jar" -> pci.s
Jeff Haodcdc85b2015-12-04 14:06:18 -0800995 static std::string CreateMultiImageName(std::string in,
Andreas Gampe8994a042015-12-30 19:03:17 +0000996 const std::string& prefix,
Jeff Haodcdc85b2015-12-04 14:06:18 -0800997 const std::string& infix,
Andreas Gampe8994a042015-12-30 19:03:17 +0000998 const char* replace_suffix) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800999 size_t last_dex_slash = in.rfind('/');
1000 if (last_dex_slash != std::string::npos) {
1001 in = in.substr(last_dex_slash + 1);
1002 }
Andreas Gampe8994a042015-12-30 19:03:17 +00001003 if (!prefix.empty()) {
1004 in = prefix + in;
1005 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001006 if (!infix.empty()) {
1007 // Inject infix.
1008 size_t last_dot = in.rfind('.');
1009 if (last_dot != std::string::npos) {
1010 in.insert(last_dot, infix);
1011 }
1012 }
1013 if (EndsWith(in, ".jar")) {
Andreas Gampe8994a042015-12-30 19:03:17 +00001014 in = in.substr(0, in.length() - strlen(".jar")) +
1015 (replace_suffix != nullptr ? replace_suffix : "");
Jeff Haodcdc85b2015-12-04 14:06:18 -08001016 }
1017 return in;
1018 }
1019
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001020 void InsertCompileOptions(int argc, char** argv) {
Roland Levillain9ec5e222015-08-17 20:18:41 +01001021 std::ostringstream oss;
1022 for (int i = 0; i < argc; ++i) {
1023 if (i > 0) {
1024 oss << ' ';
1025 }
1026 oss << argv[i];
1027 }
1028 key_value_store_->Put(OatHeader::kDex2OatCmdLineKey, oss.str());
1029 oss.str(""); // Reset.
1030 oss << kRuntimeISA;
1031 key_value_store_->Put(OatHeader::kDex2OatHostKey, oss.str());
1032 key_value_store_->Put(
1033 OatHeader::kPicKey,
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001034 compiler_options_->compile_pic_ ? OatHeader::kTrueValue : OatHeader::kFalseValue);
Roland Levillain9ec5e222015-08-17 20:18:41 +01001035 key_value_store_->Put(
1036 OatHeader::kDebuggableKey,
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001037 compiler_options_->debuggable_ ? OatHeader::kTrueValue : OatHeader::kFalseValue);
Calin Juravleb077e152016-02-18 18:47:37 +00001038 if (compiler_options_->IsExtractOnly()) {
1039 key_value_store_->Put(OatHeader::kCompilationType, OatHeader::kExtractOnlyValue);
1040 } else if (UseProfileGuidedCompilation()) {
1041 key_value_store_->Put(OatHeader::kCompilationType, OatHeader::kProfileGuideCompiledValue);
1042 }
Roland Levillain9ec5e222015-08-17 20:18:41 +01001043 }
1044
1045 // Parse the arguments from the command line. In case of an unrecognized option or impossible
1046 // values/combinations, a usage error will be displayed and exit() is called. Thus, if the method
1047 // returns, arguments have been successfully parsed.
1048 void ParseArgs(int argc, char** argv) {
1049 original_argc = argc;
1050 original_argv = argv;
1051
1052 InitLogging(argv);
1053
1054 // Skip over argv[0].
1055 argv++;
1056 argc--;
1057
1058 if (argc == 0) {
1059 Usage("No arguments specified");
1060 }
1061
1062 std::unique_ptr<ParserOptions> parser_options(new ParserOptions());
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001063 compiler_options_.reset(new CompilerOptions());
Roland Levillain9ec5e222015-08-17 20:18:41 +01001064
1065 for (int i = 0; i < argc; i++) {
1066 const StringPiece option(argv[i]);
1067 const bool log_options = false;
1068 if (log_options) {
1069 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
1070 }
1071 if (option.starts_with("--dex-file=")) {
1072 dex_filenames_.push_back(option.substr(strlen("--dex-file=")).data());
1073 } else if (option.starts_with("--dex-location=")) {
1074 dex_locations_.push_back(option.substr(strlen("--dex-location=")).data());
1075 } else if (option.starts_with("--zip-fd=")) {
1076 ParseZipFd(option);
1077 } else if (option.starts_with("--zip-location=")) {
1078 zip_location_ = option.substr(strlen("--zip-location=")).data();
1079 } else if (option.starts_with("--oat-file=")) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001080 oat_filenames_.push_back(option.substr(strlen("--oat-file=")).data());
Roland Levillain9ec5e222015-08-17 20:18:41 +01001081 } else if (option.starts_with("--oat-symbols=")) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001082 parser_options->oat_symbols.push_back(option.substr(strlen("--oat-symbols=")).data());
Roland Levillain9ec5e222015-08-17 20:18:41 +01001083 } else if (option.starts_with("--oat-fd=")) {
1084 ParseOatFd(option);
1085 } else if (option == "--watch-dog") {
1086 parser_options->watch_dog_enabled = true;
1087 } else if (option == "--no-watch-dog") {
1088 parser_options->watch_dog_enabled = false;
1089 } else if (option.starts_with("-j")) {
1090 ParseJ(option);
1091 } else if (option.starts_with("--oat-location=")) {
1092 oat_location_ = option.substr(strlen("--oat-location=")).data();
1093 } else if (option.starts_with("--image=")) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001094 image_filenames_.push_back(option.substr(strlen("--image=")).data());
Roland Levillain9ec5e222015-08-17 20:18:41 +01001095 } else if (option.starts_with("--image-classes=")) {
1096 image_classes_filename_ = option.substr(strlen("--image-classes=")).data();
1097 } else if (option.starts_with("--image-classes-zip=")) {
1098 image_classes_zip_filename_ = option.substr(strlen("--image-classes-zip=")).data();
Mathieu Chartierceb07b32015-12-10 09:33:21 -08001099 } else if (option.starts_with("--image-format=")) {
1100 ParseImageFormat(option);
Roland Levillain9ec5e222015-08-17 20:18:41 +01001101 } else if (option.starts_with("--compiled-classes=")) {
1102 compiled_classes_filename_ = option.substr(strlen("--compiled-classes=")).data();
1103 } else if (option.starts_with("--compiled-classes-zip=")) {
1104 compiled_classes_zip_filename_ = option.substr(strlen("--compiled-classes-zip=")).data();
1105 } else if (option.starts_with("--compiled-methods=")) {
1106 compiled_methods_filename_ = option.substr(strlen("--compiled-methods=")).data();
1107 } else if (option.starts_with("--compiled-methods-zip=")) {
1108 compiled_methods_zip_filename_ = option.substr(strlen("--compiled-methods-zip=")).data();
1109 } else if (option.starts_with("--base=")) {
1110 ParseBase(option);
1111 } else if (option.starts_with("--boot-image=")) {
1112 parser_options->boot_image_filename = option.substr(strlen("--boot-image=")).data();
1113 } else if (option.starts_with("--android-root=")) {
1114 android_root_ = option.substr(strlen("--android-root=")).data();
1115 } else if (option.starts_with("--instruction-set=")) {
1116 ParseInstructionSet(option);
1117 } else if (option.starts_with("--instruction-set-variant=")) {
1118 ParseInstructionSetVariant(option, parser_options.get());
1119 } else if (option.starts_with("--instruction-set-features=")) {
1120 ParseInstructionSetFeatures(option, parser_options.get());
1121 } else if (option.starts_with("--compiler-backend=")) {
1122 ParseCompilerBackend(option, parser_options.get());
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001123 } else if (option.starts_with("--profile-file=")) {
Calin Juravle2e2db782016-02-23 12:00:03 +00001124 profile_file_ = option.substr(strlen("--profile-file=")).ToString();
Calin Juravle877fd962016-01-05 14:29:29 +00001125 } else if (option.starts_with("--profile-file-fd=")) {
Calin Juravle2e2db782016-02-23 12:00:03 +00001126 ParseUintOption(option, "--profile-file-fd", &profile_file_fd_, Usage);
Roland Levillain9ec5e222015-08-17 20:18:41 +01001127 } else if (option == "--host") {
1128 is_host_ = true;
1129 } else if (option == "--runtime-arg") {
1130 if (++i >= argc) {
1131 Usage("Missing required argument for --runtime-arg");
1132 }
1133 if (log_options) {
1134 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
1135 }
1136 runtime_args_.push_back(argv[i]);
1137 } else if (option == "--dump-timing") {
1138 dump_timing_ = true;
1139 } else if (option == "--dump-passes") {
1140 dump_passes_ = true;
Roland Levillain9ec5e222015-08-17 20:18:41 +01001141 } else if (option == "--dump-stats") {
1142 dump_stats_ = true;
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001143 } else if (option.starts_with("--swap-file=")) {
1144 swap_file_name_ = option.substr(strlen("--swap-file=")).data();
1145 } else if (option.starts_with("--swap-fd=")) {
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001146 ParseUintOption(option, "--swap-fd", &swap_fd_, Usage);
1147 } else if (option.starts_with("--app-image-file=")) {
1148 app_image_file_name_ = option.substr(strlen("--app-image-file=")).data();
1149 } else if (option.starts_with("--app-image-fd=")) {
1150 ParseUintOption(option, "--app-image-fd", &app_image_fd_, Usage);
Roland Levillain9ec5e222015-08-17 20:18:41 +01001151 } else if (option.starts_with("--verbose-methods=")) {
1152 // TODO: rather than switch off compiler logging, make all VLOG(compiler) messages
1153 // conditional on having verbost methods.
1154 gLogVerbosity.compiler = false;
1155 Split(option.substr(strlen("--verbose-methods=")).ToString(), ',', &verbose_methods_);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001156 } else if (option == "--multi-image") {
Jeff Hao436183f2016-01-12 16:36:50 -08001157 multi_image_ = true;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001158 } else if (option.starts_with("--no-inline-from=")) {
1159 no_inline_from_string_ = option.substr(strlen("--no-inline-from=")).data();
Andreas Gampeace0dc12016-01-20 13:33:13 -08001160 } else if (option == "--force-determinism") {
Hiroshi Yamauchi6af53482016-01-29 15:38:58 -08001161 if (!SupportsDeterministicCompilation()) {
1162 Usage("Cannot use --force-determinism with read barriers or non-CMS garbage collector");
Roland Levillaineb2c7412016-01-28 14:37:01 +00001163 }
Andreas Gampeace0dc12016-01-20 13:33:13 -08001164 force_determinism_ = true;
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001165 } else if (!compiler_options_->ParseCompilerOption(option, Usage)) {
Roland Levillain9ec5e222015-08-17 20:18:41 +01001166 Usage("Unknown argument %s", option.data());
1167 }
1168 }
1169
Jeff Hao436183f2016-01-12 16:36:50 -08001170 ProcessOptions(parser_options.get());
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001171
1172 // Insert some compiler things.
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001173 InsertCompileOptions(argc, argv);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001174 }
1175
Jeff Haodcdc85b2015-12-04 14:06:18 -08001176 // Check whether the oat output files are writable, and open them for later. Also open a swap
1177 // file, if a name is given.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001178 bool OpenFile() {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001179 // Prune non-existent dex files now so that we don't create empty oat files for multi-image.
1180 PruneNonExistentDexFiles();
1181
Jeff Hao436183f2016-01-12 16:36:50 -08001182 // Expand oat and image filenames for multi image.
1183 if (IsBootImage() && multi_image_) {
1184 ExpandOatAndImageFilenames();
1185 }
1186
Jeff Haodcdc85b2015-12-04 14:06:18 -08001187 bool create_file = oat_fd_ == -1; // as opposed to using open file descriptor
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001188 if (create_file) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001189 for (const char* oat_filename : oat_filenames_) {
1190 std::unique_ptr<File> oat_file(OS::CreateEmptyFile(oat_filename));
1191 if (oat_file.get() == nullptr) {
1192 PLOG(ERROR) << "Failed to create oat file: " << oat_filename;
1193 return false;
1194 }
1195 if (create_file && fchmod(oat_file->Fd(), 0644) != 0) {
1196 PLOG(ERROR) << "Failed to make oat file world readable: " << oat_filename;
1197 oat_file->Erase();
1198 return false;
1199 }
1200 oat_files_.push_back(std::move(oat_file));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001201 }
1202 } else {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001203 std::unique_ptr<File> oat_file(new File(oat_fd_, oat_location_, true));
1204 oat_file->DisableAutoClose();
1205 if (oat_file->SetLength(0) != 0) {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001206 PLOG(WARNING) << "Truncating oat file " << oat_location_ << " failed.";
1207 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001208 if (oat_file.get() == nullptr) {
1209 PLOG(ERROR) << "Failed to create oat file: " << oat_location_;
1210 return false;
1211 }
1212 if (create_file && fchmod(oat_file->Fd(), 0644) != 0) {
1213 PLOG(ERROR) << "Failed to make oat file world readable: " << oat_location_;
1214 oat_file->Erase();
1215 return false;
1216 }
1217 oat_filenames_.push_back(oat_location_.c_str());
1218 oat_files_.push_back(std::move(oat_file));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001219 }
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001220
1221 // Swap file handling.
1222 //
1223 // If the swap fd is not -1, we assume this is the file descriptor of an open but unlinked file
1224 // that we can use for swap.
1225 //
1226 // If the swap fd is -1 and we have a swap-file string, open the given file as a swap file. We
1227 // will immediately unlink to satisfy the swap fd assumption.
1228 if (swap_fd_ == -1 && !swap_file_name_.empty()) {
1229 std::unique_ptr<File> swap_file(OS::CreateEmptyFile(swap_file_name_.c_str()));
1230 if (swap_file.get() == nullptr) {
1231 PLOG(ERROR) << "Failed to create swap file: " << swap_file_name_;
1232 return false;
1233 }
1234 swap_fd_ = swap_file->Fd();
1235 swap_file->MarkUnchecked(); // We don't we to track this, it will be unlinked immediately.
1236 swap_file->DisableAutoClose(); // We'll handle it ourselves, the File object will be
1237 // released immediately.
1238 unlink(swap_file_name_.c_str());
1239 }
Jeff Hao436183f2016-01-12 16:36:50 -08001240
1241 // If we use a swap file, ensure we are above the threshold to make it necessary.
1242 if (swap_fd_ != -1) {
1243 if (!UseSwap(IsBootImage(), dex_files_)) {
1244 close(swap_fd_);
1245 swap_fd_ = -1;
1246 VLOG(compiler) << "Decided to run without swap.";
1247 } else {
1248 LOG(INFO) << "Large app, accepted running with swap.";
1249 }
1250 }
1251 // Note that dex2oat won't close the swap_fd_. The compiler driver's swap space will do that.
1252
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001253 return true;
1254 }
1255
Jeff Haodcdc85b2015-12-04 14:06:18 -08001256 void EraseOatFiles() {
1257 for (size_t i = 0; i < oat_files_.size(); ++i) {
1258 DCHECK(oat_files_[i].get() != nullptr);
1259 oat_files_[i]->Erase();
1260 oat_files_[i].reset();
1261 }
Andreas Gampea650e702014-12-03 14:28:02 -08001262 }
1263
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001264 void Shutdown() {
1265 ScopedObjectAccess soa(Thread::Current());
1266 for (jobject dex_cache : dex_caches_) {
1267 soa.Env()->DeleteLocalRef(dex_cache);
1268 }
1269 dex_caches_.clear();
1270 }
1271
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08001272 void LoadClassProfileDescriptors() {
1273 if (profile_compilation_info_ != nullptr && app_image_) {
1274 Runtime* runtime = Runtime::Current();
1275 CHECK(runtime != nullptr);
1276 std::set<DexCacheResolvedClasses> resolved_classes(
1277 profile_compilation_info_->GetResolvedClasses());
1278 image_classes_.reset(new std::unordered_set<std::string>(
1279 runtime->GetClassLinker()->GetClassDescriptorsForProfileKeys(resolved_classes)));
1280 VLOG(compiler) << "Loaded " << image_classes_->size()
1281 << " image class descriptors from profile";
1282 if (VLOG_IS_ON(compiler)) {
1283 for (const std::string& s : *image_classes_) {
1284 LOG(INFO) << "Image class " << s;
1285 }
1286 }
1287 }
1288 }
1289
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001290 // Set up the environment for compilation. Includes starting the runtime and loading/opening the
1291 // boot class path.
1292 bool Setup() {
1293 TimingLogger::ScopedTiming t("dex2oat Setup", timings_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001294 art::MemMap::Init(); // For ZipEntry::ExtractToMemMap.
Vladimir Marko49b0f452015-12-10 13:49:19 +00001295
1296 if (!PrepareImageClasses() || !PrepareCompiledClasses() || !PrepareCompiledMethods()) {
1297 return false;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001298 }
Brian Carlstromd76e0832013-08-29 15:17:42 -07001299
Vladimir Marko307dac92015-10-20 11:20:09 +01001300 verification_results_.reset(new VerificationResults(compiler_options_.get()));
Andreas Gampe4585f872015-03-27 23:45:15 -07001301 callbacks_.reset(new QuickCompilerCallbacks(
Vladimir Marko307dac92015-10-20 11:20:09 +01001302 verification_results_.get(),
Andreas Gampe4585f872015-03-27 23:45:15 -07001303 &method_inliner_map_,
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001304 IsBootImage() ?
Andreas Gampe4585f872015-03-27 23:45:15 -07001305 CompilerCallbacks::CallbackMode::kCompileBootImage :
1306 CompilerCallbacks::CallbackMode::kCompileApp));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001307
Vladimir Marko49b0f452015-12-10 13:49:19 +00001308 RuntimeArgumentMap runtime_options;
1309 if (!PrepareRuntimeOptions(&runtime_options)) {
1310 return false;
Andreas Gampe1d00add2015-02-27 19:35:46 -08001311 }
1312
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001313 CreateOatWriters();
1314 if (!AddDexFileSources()) {
1315 return false;
1316 }
1317
1318 if (IsBootImage() && image_filenames_.size() > 1) {
1319 // If we're compiling the boot image, store the boot classpath into the Key-Value store.
1320 // We need this for the multi-image case.
1321 key_value_store_->Put(OatHeader::kBootClassPath, GetMultiImageBootClassPath());
1322 }
1323
1324 if (!IsBootImage()) {
1325 // When compiling an app, create the runtime early to retrieve
1326 // the image location key needed for the oat header.
1327 if (!CreateRuntime(std::move(runtime_options))) {
1328 return false;
1329 }
1330
David Brazdilce4b0ba2016-01-28 15:05:49 +00001331 if (compiler_options_->IsExtractOnly()) {
1332 // ExtractOnly oat files only contain non-quickened DEX code and are
1333 // therefore independent of the image file.
1334 image_file_location_oat_checksum_ = 0u;
1335 image_file_location_oat_data_begin_ = 0u;
1336 image_patch_delta_ = 0;
1337 } else {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001338 TimingLogger::ScopedTiming t3("Loading image checksum", timings_);
1339 std::vector<gc::space::ImageSpace*> image_spaces =
1340 Runtime::Current()->GetHeap()->GetBootImageSpaces();
1341 image_file_location_oat_checksum_ = image_spaces[0]->GetImageHeader().GetOatChecksum();
1342 image_file_location_oat_data_begin_ =
1343 reinterpret_cast<uintptr_t>(image_spaces[0]->GetImageHeader().GetOatDataBegin());
1344 image_patch_delta_ = image_spaces[0]->GetImageHeader().GetPatchDelta();
1345 // Store the boot image filename(s).
1346 std::vector<std::string> image_filenames;
1347 for (const gc::space::ImageSpace* image_space : image_spaces) {
1348 image_filenames.push_back(image_space->GetImageFilename());
1349 }
1350 std::string image_file_location = Join(image_filenames, ':');
1351 if (!image_file_location.empty()) {
1352 key_value_store_->Put(OatHeader::kImageLocationKey, image_file_location);
1353 }
1354 }
1355
1356 // Open dex files for class path.
1357 const std::vector<std::string> class_path_locations =
1358 GetClassPathLocations(runtime_->GetClassPathString());
1359 OpenClassPathFiles(class_path_locations, &class_path_files_);
1360
1361 // Store the classpath we have right now.
1362 std::vector<const DexFile*> class_path_files = MakeNonOwningPointerVector(class_path_files_);
1363 key_value_store_->Put(OatHeader::kClassPathKey,
1364 OatFile::EncodeDexFileDependencies(class_path_files));
1365 }
1366
1367 // Now that we have finalized key_value_store_, start writing the oat file.
Andreas Gampec7ae55d2015-09-15 20:04:54 -07001368 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001369 TimingLogger::ScopedTiming t_dex("Writing and opening dex files", timings_);
1370 rodata_.reserve(oat_writers_.size());
1371 for (size_t i = 0, size = oat_writers_.size(); i != size; ++i) {
1372 rodata_.push_back(elf_writers_[i]->StartRoData());
1373 // Unzip or copy dex files straight to the oat file.
1374 std::unique_ptr<MemMap> opened_dex_files_map;
1375 std::vector<std::unique_ptr<const DexFile>> opened_dex_files;
1376 if (!oat_writers_[i]->WriteAndOpenDexFiles(rodata_.back(),
1377 oat_files_[i].get(),
1378 instruction_set_,
1379 instruction_set_features_.get(),
1380 key_value_store_.get(),
Andreas Gampe3a2bd292016-01-26 17:23:47 -08001381 /* verify */ true,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001382 &opened_dex_files_map,
1383 &opened_dex_files)) {
1384 return false;
1385 }
1386 dex_files_per_oat_file_.push_back(MakeNonOwningPointerVector(opened_dex_files));
1387 if (opened_dex_files_map != nullptr) {
1388 opened_dex_files_maps_.push_back(std::move(opened_dex_files_map));
1389 for (std::unique_ptr<const DexFile>& dex_file : opened_dex_files) {
Vladimir Marko944da602016-02-19 12:27:55 +00001390 dex_file_oat_index_map_.emplace(dex_file.get(), i);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001391 opened_dex_files_.push_back(std::move(dex_file));
1392 }
1393 } else {
1394 DCHECK(opened_dex_files.empty());
1395 }
1396 }
1397 }
1398
1399 dex_files_ = MakeNonOwningPointerVector(opened_dex_files_);
1400 if (IsBootImage()) {
1401 // For boot image, pass opened dex files to the Runtime::Create().
1402 // Note: Runtime acquires ownership of these dex files.
1403 runtime_options.Set(RuntimeArgumentMap::BootClassPathDexList, &opened_dex_files_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001404 if (!CreateRuntime(std::move(runtime_options))) {
Andreas Gampec7ae55d2015-09-15 20:04:54 -07001405 return false;
1406 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001407 }
1408
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001409 // If we're doing the image, override the compiler filter to force full compilation. Must be
1410 // done ahead of WellKnownClasses::Init that causes verification. Note: doesn't force
1411 // compilation of class initializers.
1412 // Whilst we're in native take the opportunity to initialize well known classes.
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001413 Thread* self = Thread::Current();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001414 WellKnownClasses::Init(self->GetJniEnv());
1415
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001416 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001417 if (!IsBootImage()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001418 constexpr bool kSaveDexInput = false;
1419 if (kSaveDexInput) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001420 SaveDexInput();
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001421 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001422
1423 // Handle and ClassLoader creation needs to come after Runtime::Create.
1424 ScopedObjectAccess soa(self);
1425
1426 // Classpath: first the class-path given.
1427 std::vector<const DexFile*> class_path_files = MakeNonOwningPointerVector(class_path_files_);
1428
1429 // Then the dex files we'll compile. Thus we'll resolve the class-path first.
1430 class_path_files.insert(class_path_files.end(), dex_files_.begin(), dex_files_.end());
1431
1432 class_loader_ = class_linker->CreatePathClassLoader(self, class_path_files);
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001433 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001434
1435 // Ensure opened dex files are writable for dex-to-dex transformations.
1436 for (const std::unique_ptr<MemMap>& map : opened_dex_files_maps_) {
1437 if (!map->Protect(PROT_READ | PROT_WRITE)) {
1438 PLOG(ERROR) << "Failed to make .dex files writeable.";
1439 return false;
Vladimir Marko919f5532016-01-20 19:13:01 +00001440 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001441 }
1442
1443 // Ensure that the dex caches stay live since we don't want class unloading
1444 // to occur during compilation.
1445 for (const auto& dex_file : dex_files_) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001446 ScopedObjectAccess soa(self);
1447 dex_caches_.push_back(soa.AddLocalReference<jobject>(
Mathieu Chartierd57d4542015-10-14 10:55:30 -07001448 class_linker->RegisterDexFile(*dex_file, Runtime::Current()->GetLinearAlloc())));
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001449 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001450
1451 /*
1452 * If we're not in interpret-only or verify-none mode, go ahead and compile small applications.
1453 * Don't bother to check if we're doing the image.
1454 */
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001455 if (!IsBootImage() &&
Brian Carlstrom95b033b2014-12-03 22:29:37 -08001456 compiler_options_->IsCompilationEnabled() &&
1457 compiler_kind_ == Compiler::kQuick) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001458 size_t num_methods = 0;
1459 for (size_t i = 0; i != dex_files_.size(); ++i) {
1460 const DexFile* dex_file = dex_files_[i];
1461 CHECK(dex_file != nullptr);
1462 num_methods += dex_file->NumMethodIds();
1463 }
1464 if (num_methods <= compiler_options_->GetNumDexMethodsThreshold()) {
1465 compiler_options_->SetCompilerFilter(CompilerOptions::kSpeed);
1466 VLOG(compiler) << "Below method threshold, compiling anyways";
1467 }
1468 }
1469
1470 return true;
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001471 }
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001472
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001473 // If we need to keep the oat file open for the image writer.
1474 bool ShouldKeepOatFileOpen() const {
1475 return IsImage() && oat_fd_ != kInvalidFd;
1476 }
1477
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001478 // Create and invoke the compiler driver. This will compile all the dex files.
1479 void Compile() {
1480 TimingLogger::ScopedTiming t("dex2oat Compile", timings_);
1481 compiler_phases_timings_.reset(new CumulativeLogger("compilation times"));
Vladimir Markof4da6752014-08-01 19:04:18 +01001482
Vladimir Marko47496c22016-01-27 16:15:08 +00001483 // Find the dex files we should not inline from.
1484
1485 std::vector<std::string> no_inline_filters;
1486 Split(no_inline_from_string_, ',', &no_inline_filters);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001487
1488 // For now, on the host always have core-oj removed.
Vladimir Marko47496c22016-01-27 16:15:08 +00001489 const std::string core_oj = "core-oj";
1490 if (!kIsTargetBuild && !ContainsElement(no_inline_filters, core_oj)) {
1491 no_inline_filters.push_back(core_oj);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001492 }
1493
Vladimir Marko47496c22016-01-27 16:15:08 +00001494 if (!no_inline_filters.empty()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001495 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1496 std::vector<const DexFile*> class_path_files = MakeNonOwningPointerVector(class_path_files_);
1497 std::vector<const std::vector<const DexFile*>*> dex_file_vectors = {
1498 &class_linker->GetBootClassPath(),
1499 &class_path_files,
1500 &dex_files_
1501 };
1502 for (const std::vector<const DexFile*>* dex_file_vector : dex_file_vectors) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001503 for (const DexFile* dex_file : *dex_file_vector) {
Vladimir Marko47496c22016-01-27 16:15:08 +00001504 for (const std::string& filter : no_inline_filters) {
1505 // Use dex_file->GetLocation() rather than dex_file->GetBaseLocation(). This
1506 // allows tests to specify <test-dexfile>:classes2.dex if needed but if the
1507 // base location passes the StartsWith() test, so do all extra locations.
1508 std::string dex_location = dex_file->GetLocation();
1509 if (filter.find('/') == std::string::npos) {
1510 // The filter does not contain the path. Remove the path from dex_location as well.
1511 size_t last_slash = dex_file->GetLocation().rfind('/');
1512 if (last_slash != std::string::npos) {
1513 dex_location = dex_location.substr(last_slash + 1);
1514 }
1515 }
1516
1517 if (StartsWith(dex_location, filter.c_str())) {
1518 VLOG(compiler) << "Disabling inlining from " << dex_file->GetLocation();
1519 no_inline_from_dex_files_.push_back(dex_file);
1520 break;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001521 }
1522 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001523 }
Vladimir Marko47496c22016-01-27 16:15:08 +00001524 }
1525 if (!no_inline_from_dex_files_.empty()) {
1526 compiler_options_->no_inline_from_ = &no_inline_from_dex_files_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001527 }
1528 }
1529
Vladimir Marko307dac92015-10-20 11:20:09 +01001530 driver_.reset(new CompilerDriver(compiler_options_.get(),
1531 verification_results_.get(),
1532 &method_inliner_map_,
1533 compiler_kind_,
1534 instruction_set_,
1535 instruction_set_features_.get(),
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001536 IsBootImage(),
Vladimir Marko307dac92015-10-20 11:20:09 +01001537 image_classes_.release(),
1538 compiled_classes_.release(),
Vladimir Marko944da602016-02-19 12:27:55 +00001539 /* compiled_methods */ nullptr,
Vladimir Marko307dac92015-10-20 11:20:09 +01001540 thread_count_,
1541 dump_stats_,
1542 dump_passes_,
Vladimir Marko307dac92015-10-20 11:20:09 +01001543 compiler_phases_timings_.get(),
1544 swap_fd_,
Calin Juravle998c2162015-12-21 15:39:33 +02001545 profile_compilation_info_.get()));
Vladimir Markod1eaf0d2015-10-29 12:18:29 +00001546 driver_->SetDexFilesForOatFile(dex_files_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001547 driver_->CompileAll(class_loader_, dex_files_, timings_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001548 }
1549
Jeff Hao436183f2016-01-12 16:36:50 -08001550 // Notes on the interleaving of creating the images and oat files to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001551 // ensure the references between the two are correct.
1552 //
1553 // Currently we have a memory layout that looks something like this:
1554 //
1555 // +--------------+
Jeff Hao436183f2016-01-12 16:36:50 -08001556 // | images |
Brian Carlstrom7940e442013-07-12 13:46:57 -07001557 // +--------------+
Jeff Hao436183f2016-01-12 16:36:50 -08001558 // | oat files |
Brian Carlstrom7940e442013-07-12 13:46:57 -07001559 // +--------------+
1560 // | alloc spaces |
1561 // +--------------+
1562 //
Jeff Hao436183f2016-01-12 16:36:50 -08001563 // There are several constraints on the loading of the images and oat files.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001564 //
Jeff Hao436183f2016-01-12 16:36:50 -08001565 // 1. The images are expected to be loaded at an absolute address and
1566 // contain Objects with absolute pointers within the images.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001567 //
Jeff Hao436183f2016-01-12 16:36:50 -08001568 // 2. There are absolute pointers from Methods in the images to their
1569 // code in the oat files.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001570 //
Jeff Hao436183f2016-01-12 16:36:50 -08001571 // 3. There are absolute pointers from the code in the oat files to Methods
1572 // in the images.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001573 //
Jeff Hao436183f2016-01-12 16:36:50 -08001574 // 4. There are absolute pointers from code in the oat files to other code
1575 // in the oat files.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001576 //
1577 // To get this all correct, we go through several steps.
1578 //
Jeff Hao436183f2016-01-12 16:36:50 -08001579 // 1. We prepare offsets for all data in the oat files and calculate
Vladimir Markof4da6752014-08-01 19:04:18 +01001580 // the oat data size and code size. During this stage, we also set
1581 // oat code offsets in methods for use by the image writer.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001582 //
Jeff Hao436183f2016-01-12 16:36:50 -08001583 // 2. We prepare offsets for the objects in the images and calculate
1584 // the image sizes.
Vladimir Markof4da6752014-08-01 19:04:18 +01001585 //
Jeff Hao436183f2016-01-12 16:36:50 -08001586 // 3. We create the oat files. Originally this was just our own proprietary
Vladimir Markof4da6752014-08-01 19:04:18 +01001587 // file but now it is contained within an ELF dynamic object (aka an .so
Jeff Hao436183f2016-01-12 16:36:50 -08001588 // file). Since we know the image sizes and oat data sizes and code sizes we
Vladimir Markof4da6752014-08-01 19:04:18 +01001589 // can prepare the ELF headers and we then know the ELF memory segment
1590 // layout and we can now resolve all references. The compiler provides
1591 // LinkerPatch information in each CompiledMethod and we resolve these,
1592 // using the layout information and image object locations provided by
1593 // image writer, as we're writing the method code.
1594 //
Jeff Hao436183f2016-01-12 16:36:50 -08001595 // 4. We create the image files. They need to know where the oat files
1596 // will be loaded after itself. Originally oat files were simply
1597 // memory mapped so we could predict where their contents were based
1598 // on the file size. Now that they are ELF files, we need to inspect
1599 // the ELF files to understand the in memory segment layout including
Vladimir Markof4da6752014-08-01 19:04:18 +01001600 // where the oat header is located within.
1601 // TODO: We could just remember this information from step 3.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001602 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001603 // 5. We fixup the ELF program headers so that dlopen will try to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001604 // load the .so at the desired location at runtime by offsetting the
1605 // Elf32_Phdr.p_vaddr values by the desired base address.
Vladimir Markof4da6752014-08-01 19:04:18 +01001606 // TODO: Do this in step 3. We already know the layout there.
1607 //
1608 // Steps 1.-3. are done by the CreateOatFile() above, steps 4.-5.
1609 // are done by the CreateImageFile() below.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001610
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001611 // Write out the generated code part. Calls the OatWriter and ElfBuilder. Also prepares the
1612 // ImageWriter, if necessary.
Andreas Gampe10e477d2014-11-19 12:57:42 -08001613 // Note: Flushing (and closing) the file is the caller's responsibility, except for the failure
1614 // case (when the file will be explicitly erased).
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001615 bool WriteOatFiles() {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001616 TimingLogger::ScopedTiming t("dex2oat Oat", timings_);
1617
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001618 // Sync the data to the file, in case we did dex2dex transformations.
1619 for (const std::unique_ptr<MemMap>& map : opened_dex_files_maps_) {
1620 if (!map->Sync()) {
1621 PLOG(ERROR) << "Failed to Sync() dex2dex output. Map: " << map->GetName();
1622 return false;
1623 }
1624 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001625
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001626 if (IsImage()) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001627 if (app_image_ && image_base_ == 0) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001628 gc::Heap* const heap = Runtime::Current()->GetHeap();
1629 for (gc::space::ImageSpace* image_space : heap->GetBootImageSpaces()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001630 image_base_ = std::max(image_base_, RoundUp(
1631 reinterpret_cast<uintptr_t>(image_space->GetImageHeader().GetOatFileEnd()),
1632 kPageSize));
1633 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001634 // The non moving space is right after the oat file. Put the preferred app image location
1635 // right after the non moving space so that we ideally get a continuous immune region for
1636 // the GC.
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08001637 // Use the default non moving space capacity since dex2oat does not have a separate non-
1638 // moving space. This means the runtime's non moving space space size will be as large
1639 // as the growth limit for dex2oat, but smaller in the zygote.
1640 const size_t non_moving_space_capacity = gc::Heap::kDefaultNonMovingSpaceCapacity;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001641 image_base_ += non_moving_space_capacity;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001642 VLOG(compiler) << "App image base=" << reinterpret_cast<void*>(image_base_);
1643 }
1644
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001645 image_writer_.reset(new ImageWriter(*driver_,
1646 image_base_,
1647 compiler_options_->GetCompilePic(),
1648 IsAppImage(),
1649 image_storage_mode_,
1650 oat_filenames_,
Vladimir Marko944da602016-02-19 12:27:55 +00001651 dex_file_oat_index_map_));
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001652
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001653 // We need to prepare method offsets in the image address space for direct method patching.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001654 TimingLogger::ScopedTiming t2("dex2oat Prepare image address space", timings_);
1655 if (!image_writer_->PrepareImageAddressSpace()) {
1656 LOG(ERROR) << "Failed to prepare image address space.";
1657 return false;
1658 }
1659 }
1660
Vladimir Marko944da602016-02-19 12:27:55 +00001661 linker::MultiOatRelativePatcher patcher(instruction_set_, instruction_set_features_.get());
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001662 {
1663 TimingLogger::ScopedTiming t2("dex2oat Write ELF", timings_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001664 for (size_t i = 0, size = oat_files_.size(); i != size; ++i) {
Vladimir Marko944da602016-02-19 12:27:55 +00001665 std::unique_ptr<ElfWriter>& elf_writer = elf_writers_[i];
1666 std::unique_ptr<OatWriter>& oat_writer = oat_writers_[i];
1667
1668 std::vector<const DexFile*>& dex_files = dex_files_per_oat_file_[i];
1669 oat_writer->PrepareLayout(driver_.get(), image_writer_.get(), dex_files, &patcher);
1670
1671 size_t rodata_size = oat_writer->GetOatHeader().GetExecutableOffset();
1672 size_t text_size = oat_writer->GetSize() - rodata_size;
1673 elf_writer->SetLoadedSectionSizes(rodata_size, text_size, oat_writer->GetBssSize());
1674
1675 if (IsImage()) {
1676 // Update oat layout.
1677 DCHECK(image_writer_ != nullptr);
1678 DCHECK_LT(i, oat_filenames_.size());
1679 image_writer_->UpdateOatFileLayout(i,
1680 elf_writer->GetLoadedSize(),
1681 oat_writer->GetOatDataOffset(),
1682 oat_writer->GetSize());
1683 }
1684 }
1685
1686 for (size_t i = 0, size = oat_files_.size(); i != size; ++i) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001687 std::unique_ptr<File>& oat_file = oat_files_[i];
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001688 std::unique_ptr<ElfWriter>& elf_writer = elf_writers_[i];
1689 std::unique_ptr<OatWriter>& oat_writer = oat_writers_[i];
Vladimir Marko10c13562015-11-25 14:33:36 +00001690
David Srbecky09c2a6b2016-03-11 17:11:44 +00001691 oat_writer->AddMethodDebugInfos(debug::MakeTrampolineInfos(oat_writer->GetOatHeader()));
1692
David Srbecky0c4572e2016-01-22 19:19:25 +00001693 // We need to mirror the layout of the ELF file in the compressed debug-info.
Vladimir Marko944da602016-02-19 12:27:55 +00001694 // Therefore PrepareDebugInfo() relies on the SetLoadedSectionSizes() call further above.
1695 elf_writer->PrepareDebugInfo(oat_writer->GetMethodDebugInfo());
David Srbecky0c4572e2016-01-22 19:19:25 +00001696
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001697 OutputStream*& rodata = rodata_[i];
1698 DCHECK(rodata != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001699 if (!oat_writer->WriteRodata(rodata)) {
1700 LOG(ERROR) << "Failed to write .rodata section to the ELF file " << oat_file->GetPath();
1701 return false;
1702 }
1703 elf_writer->EndRoData(rodata);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001704 rodata = nullptr;
Vladimir Marko10c13562015-11-25 14:33:36 +00001705
Jeff Haodcdc85b2015-12-04 14:06:18 -08001706 OutputStream* text = elf_writer->StartText();
1707 if (!oat_writer->WriteCode(text)) {
1708 LOG(ERROR) << "Failed to write .text section to the ELF file " << oat_file->GetPath();
1709 return false;
1710 }
1711 elf_writer->EndText(text);
Vladimir Marko10c13562015-11-25 14:33:36 +00001712
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001713 if (!oat_writer->WriteHeader(elf_writer->GetStream(),
1714 image_file_location_oat_checksum_,
1715 image_file_location_oat_data_begin_,
1716 image_patch_delta_)) {
1717 LOG(ERROR) << "Failed to write oat header to the ELF file " << oat_file->GetPath();
1718 return false;
1719 }
1720
Vladimir Marko944da602016-02-19 12:27:55 +00001721 if (IsImage()) {
1722 // Update oat header information.
1723 DCHECK(image_writer_ != nullptr);
1724 DCHECK_LT(i, oat_filenames_.size());
1725 image_writer_->UpdateOatFileHeader(i, oat_writer->GetOatHeader());
1726 }
1727
Jeff Haodcdc85b2015-12-04 14:06:18 -08001728 elf_writer->WriteDynamicSection();
1729 elf_writer->WriteDebugInfo(oat_writer->GetMethodDebugInfo());
1730 elf_writer->WritePatchLocations(oat_writer->GetAbsolutePatchLocations());
Vladimir Marko10c13562015-11-25 14:33:36 +00001731
Jeff Haodcdc85b2015-12-04 14:06:18 -08001732 if (!elf_writer->End()) {
1733 LOG(ERROR) << "Failed to write ELF file " << oat_file->GetPath();
1734 return false;
1735 }
1736
1737 // Flush the oat file.
1738 if (oat_files_[i] != nullptr) {
1739 if (oat_files_[i]->Flush() != 0) {
1740 PLOG(ERROR) << "Failed to flush oat file: " << oat_filenames_[i];
Jeff Haodcdc85b2015-12-04 14:06:18 -08001741 return false;
1742 }
1743 }
1744
Jeff Haodcdc85b2015-12-04 14:06:18 -08001745 VLOG(compiler) << "Oat file written successfully: " << oat_filenames_[i];
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001746
1747 oat_writer.reset();
1748 elf_writer.reset();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001749 }
1750 }
1751
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001752 return true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001753 }
1754
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001755 // If we are compiling an image, invoke the image creation routine. Else just skip.
1756 bool HandleImage() {
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001757 if (IsImage()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001758 TimingLogger::ScopedTiming t("dex2oat ImageWriter", timings_);
1759 if (!CreateImageFile()) {
1760 return false;
1761 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001762 VLOG(compiler) << "Images written successfully";
Brian Carlstrom45602482013-07-21 22:07:55 -07001763 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001764 return true;
1765 }
1766
Jeff Haodcdc85b2015-12-04 14:06:18 -08001767 // Create a copy from stripped to unstripped.
1768 bool CopyStrippedToUnstripped() {
1769 for (size_t i = 0; i < oat_unstripped_.size(); ++i) {
1770 // If we don't want to strip in place, copy from stripped location to unstripped location.
1771 // We need to strip after image creation because FixupElf needs to use .strtab.
1772 if (strcmp(oat_unstripped_[i], oat_filenames_[i]) != 0) {
1773 // If the oat file is still open, flush it.
1774 if (oat_files_[i].get() != nullptr && oat_files_[i]->IsOpened()) {
1775 if (!FlushCloseOatFile(i)) {
1776 return false;
1777 }
1778 }
1779
1780 TimingLogger::ScopedTiming t("dex2oat OatFile copy", timings_);
1781 std::unique_ptr<File> in(OS::OpenFileForReading(oat_filenames_[i]));
1782 std::unique_ptr<File> out(OS::CreateEmptyFile(oat_unstripped_[i]));
1783 size_t buffer_size = 8192;
1784 std::unique_ptr<uint8_t[]> buffer(new uint8_t[buffer_size]);
1785 while (true) {
1786 int bytes_read = TEMP_FAILURE_RETRY(read(in->Fd(), buffer.get(), buffer_size));
1787 if (bytes_read <= 0) {
1788 break;
1789 }
1790 bool write_ok = out->WriteFully(buffer.get(), bytes_read);
1791 CHECK(write_ok);
1792 }
1793 if (out->FlushCloseOrErase() != 0) {
1794 PLOG(ERROR) << "Failed to flush and close copied oat file: " << oat_unstripped_[i];
1795 return false;
1796 }
1797 VLOG(compiler) << "Oat file copied successfully (unstripped): " << oat_unstripped_[i];
1798 }
1799 }
1800 return true;
1801 }
1802
1803 bool FlushOatFiles() {
1804 TimingLogger::ScopedTiming t2("dex2oat Flush ELF", timings_);
1805 for (size_t i = 0; i < oat_files_.size(); ++i) {
1806 if (oat_files_[i].get() != nullptr) {
1807 if (oat_files_[i]->Flush() != 0) {
1808 PLOG(ERROR) << "Failed to flush oat file: " << oat_filenames_[i];
1809 oat_files_[i]->Erase();
Andreas Gampe10e477d2014-11-19 12:57:42 -08001810 return false;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001811 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001812 }
Nicolas Geoffrayea3fa0b2014-02-10 11:59:41 +00001813 }
Andreas Gampe10e477d2014-11-19 12:57:42 -08001814 return true;
1815 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001816
Jeff Haodcdc85b2015-12-04 14:06:18 -08001817 bool FlushCloseOatFile(size_t i) {
1818 if (oat_files_[i].get() != nullptr) {
1819 std::unique_ptr<File> tmp(oat_files_[i].release());
Andreas Gampe10e477d2014-11-19 12:57:42 -08001820 if (tmp->FlushCloseOrErase() != 0) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001821 PLOG(ERROR) << "Failed to flush and close oat file: " << oat_filenames_[i];
Andreas Gampe10e477d2014-11-19 12:57:42 -08001822 return false;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001823 }
1824 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001825 return true;
1826 }
1827
Jeff Haodcdc85b2015-12-04 14:06:18 -08001828 bool FlushCloseOatFiles() {
1829 bool result = true;
1830 for (size_t i = 0; i < oat_files_.size(); ++i) {
1831 result &= FlushCloseOatFile(i);
1832 }
1833 return result;
1834 }
1835
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001836 void DumpTiming() {
1837 if (dump_timing_ || (dump_slow_timing_ && timings_->GetTotalNs() > MsToNs(1000))) {
1838 LOG(INFO) << Dumpable<TimingLogger>(*timings_);
1839 }
1840 if (dump_passes_) {
1841 LOG(INFO) << Dumpable<CumulativeLogger>(*driver_->GetTimingsLogger());
1842 }
1843 }
1844
1845 CompilerOptions* GetCompilerOptions() const {
1846 return compiler_options_.get();
1847 }
1848
Andreas Gampe10e477d2014-11-19 12:57:42 -08001849 bool IsImage() const {
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001850 return IsAppImage() || IsBootImage();
1851 }
1852
1853 bool IsAppImage() const {
1854 return app_image_;
1855 }
1856
1857 bool IsBootImage() const {
1858 return boot_image_;
Andreas Gampe10e477d2014-11-19 12:57:42 -08001859 }
1860
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001861 bool IsHost() const {
1862 return is_host_;
1863 }
1864
Calin Juravle998c2162015-12-21 15:39:33 +02001865 bool UseProfileGuidedCompilation() const {
Calin Juravle2e2db782016-02-23 12:00:03 +00001866 return !profile_file_.empty() || (profile_file_fd_ != kInvalidFd);
Calin Juravle998c2162015-12-21 15:39:33 +02001867 }
1868
Calin Juravle2e2db782016-02-23 12:00:03 +00001869 bool LoadProfile() {
Calin Juravle998c2162015-12-21 15:39:33 +02001870 DCHECK(UseProfileGuidedCompilation());
Calin Juravle2e2db782016-02-23 12:00:03 +00001871
1872 profile_compilation_info_.reset(new ProfileCompilationInfo());
1873 ScopedFlock flock;
1874 bool success = false;
1875 std::string error;
1876 if (profile_file_fd_ != -1) {
1877 // The file doesn't need to be flushed so don't check the usage.
1878 // Pass a bogus path so that we can easily attribute any reported error.
1879 File file(profile_file_fd_, "profile", /*check_usage*/ false, /*read_only_mode*/ true);
1880 if (flock.Init(&file, &error)) {
1881 success = profile_compilation_info_->Load(profile_file_fd_);
1882 }
Calin Juravle877fd962016-01-05 14:29:29 +00001883 } else {
Calin Juravle2e2db782016-02-23 12:00:03 +00001884 if (flock.Init(profile_file_.c_str(), O_RDONLY, /* block */ true, &error)) {
1885 success = profile_compilation_info_->Load(flock.GetFile()->Fd());
1886 }
1887 }
1888 if (!error.empty()) {
1889 LOG(WARNING) << "Cannot lock profiles: " << error;
Calin Juravle998c2162015-12-21 15:39:33 +02001890 }
Calin Juravle877fd962016-01-05 14:29:29 +00001891
Calin Juravle2e2db782016-02-23 12:00:03 +00001892 if (!success) {
1893 profile_compilation_info_.reset(nullptr);
1894 }
Calin Juravle877fd962016-01-05 14:29:29 +00001895
Calin Juravle2e2db782016-02-23 12:00:03 +00001896 return success;
Calin Juravle998c2162015-12-21 15:39:33 +02001897 }
1898
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001899 private:
Vladimir Marko49b0f452015-12-10 13:49:19 +00001900 template <typename T>
1901 static std::vector<T*> MakeNonOwningPointerVector(const std::vector<std::unique_ptr<T>>& src) {
1902 std::vector<T*> result;
1903 result.reserve(src.size());
1904 for (const std::unique_ptr<T>& t : src) {
1905 result.push_back(t.get());
1906 }
1907 return result;
1908 }
1909
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001910 std::string GetMultiImageBootClassPath() {
1911 DCHECK(IsBootImage());
1912 DCHECK_GT(oat_filenames_.size(), 1u);
1913 // If the image filename was adapted (e.g., for our tests), we need to change this here,
1914 // too, but need to strip all path components (they will be re-established when loading).
1915 std::ostringstream bootcp_oss;
1916 bool first_bootcp = true;
1917 for (size_t i = 0; i < dex_locations_.size(); ++i) {
1918 if (!first_bootcp) {
1919 bootcp_oss << ":";
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001920 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001921
1922 std::string dex_loc = dex_locations_[i];
1923 std::string image_filename = image_filenames_[i];
1924
1925 // Use the dex_loc path, but the image_filename name (without path elements).
1926 size_t dex_last_slash = dex_loc.rfind('/');
1927
1928 // npos is max(size_t). That makes this a bit ugly.
1929 size_t image_last_slash = image_filename.rfind('/');
1930 size_t image_last_at = image_filename.rfind('@');
1931 size_t image_last_sep = (image_last_slash == std::string::npos)
1932 ? image_last_at
1933 : (image_last_at == std::string::npos)
1934 ? std::string::npos
1935 : std::max(image_last_slash, image_last_at);
1936 // Note: whenever image_last_sep == npos, +1 overflow means using the full string.
1937
1938 if (dex_last_slash == std::string::npos) {
1939 dex_loc = image_filename.substr(image_last_sep + 1);
1940 } else {
1941 dex_loc = dex_loc.substr(0, dex_last_slash + 1) +
1942 image_filename.substr(image_last_sep + 1);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001943 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001944
1945 // Image filenames already end with .art, no need to replace.
1946
1947 bootcp_oss << dex_loc;
1948 first_bootcp = false;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001949 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001950 return bootcp_oss.str();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001951 }
1952
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001953 std::vector<std::string> GetClassPathLocations(const std::string& class_path) {
1954 // This function is used only for apps and for an app we have exactly one oat file.
1955 DCHECK(!IsBootImage());
1956 DCHECK_EQ(oat_writers_.size(), 1u);
1957 std::vector<std::string> dex_files_canonical_locations;
1958 for (const char* location : oat_writers_[0]->GetSourceLocations()) {
1959 dex_files_canonical_locations.push_back(DexFile::GetDexCanonicalLocation(location));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001960 }
Vladimir Marko625a64a2015-11-26 14:44:16 +00001961
Vladimir Marko919f5532016-01-20 19:13:01 +00001962 std::vector<std::string> parsed;
1963 Split(class_path, ':', &parsed);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001964 auto kept_it = std::remove_if(parsed.begin(),
1965 parsed.end(),
1966 [dex_files_canonical_locations](const std::string& location) {
1967 return ContainsElement(dex_files_canonical_locations,
1968 DexFile::GetDexCanonicalLocation(location.c_str()));
1969 });
1970 parsed.erase(kept_it, parsed.end());
1971 return parsed;
1972 }
1973
1974 // Opens requested class path files and appends them to opened_dex_files.
1975 static void OpenClassPathFiles(const std::vector<std::string>& class_path_locations,
1976 std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
1977 DCHECK(opened_dex_files != nullptr) << "OpenClassPathFiles out-param is nullptr";
1978 for (const std::string& location : class_path_locations) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001979 std::string error_msg;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001980 if (!DexFile::Open(location.c_str(), location.c_str(), &error_msg, opened_dex_files)) {
1981 LOG(WARNING) << "Failed to open dex file '" << location << "': " << error_msg;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001982 }
1983 }
1984 }
1985
Vladimir Marko49b0f452015-12-10 13:49:19 +00001986 bool PrepareImageClasses() {
1987 // If --image-classes was specified, calculate the full list of classes to include in the image.
1988 if (image_classes_filename_ != nullptr) {
1989 image_classes_ =
1990 ReadClasses(image_classes_zip_filename_, image_classes_filename_, "image");
1991 if (image_classes_ == nullptr) {
1992 return false;
1993 }
1994 } else if (IsBootImage()) {
1995 image_classes_.reset(new std::unordered_set<std::string>);
1996 }
1997 return true;
1998 }
1999
2000 bool PrepareCompiledClasses() {
2001 // If --compiled-classes was specified, calculate the full list of classes to compile in the
2002 // image.
2003 if (compiled_classes_filename_ != nullptr) {
2004 compiled_classes_ =
2005 ReadClasses(compiled_classes_zip_filename_, compiled_classes_filename_, "compiled");
2006 if (compiled_classes_ == nullptr) {
2007 return false;
2008 }
2009 } else {
2010 compiled_classes_.reset(nullptr); // By default compile everything.
2011 }
2012 return true;
2013 }
2014
2015 static std::unique_ptr<std::unordered_set<std::string>> ReadClasses(const char* zip_filename,
2016 const char* classes_filename,
2017 const char* tag) {
2018 std::unique_ptr<std::unordered_set<std::string>> classes;
2019 std::string error_msg;
2020 if (zip_filename != nullptr) {
2021 classes.reset(ReadImageClassesFromZip(zip_filename, classes_filename, &error_msg));
2022 } else {
2023 classes.reset(ReadImageClassesFromFile(classes_filename));
2024 }
2025 if (classes == nullptr) {
2026 LOG(ERROR) << "Failed to create list of " << tag << " classes from '"
2027 << classes_filename << "': " << error_msg;
2028 }
2029 return classes;
2030 }
2031
2032 bool PrepareCompiledMethods() {
2033 // If --compiled-methods was specified, read the methods to compile from the given file(s).
2034 if (compiled_methods_filename_ != nullptr) {
2035 std::string error_msg;
2036 if (compiled_methods_zip_filename_ != nullptr) {
2037 compiled_methods_.reset(ReadCommentedInputFromZip(compiled_methods_zip_filename_,
2038 compiled_methods_filename_,
2039 nullptr, // No post-processing.
2040 &error_msg));
2041 } else {
2042 compiled_methods_.reset(ReadCommentedInputFromFile(compiled_methods_filename_,
2043 nullptr)); // No post-processing.
2044 }
2045 if (compiled_methods_.get() == nullptr) {
2046 LOG(ERROR) << "Failed to create list of compiled methods from '"
2047 << compiled_methods_filename_ << "': " << error_msg;
2048 return false;
2049 }
2050 } else {
2051 compiled_methods_.reset(nullptr); // By default compile everything.
2052 }
2053 return true;
2054 }
2055
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002056 void PruneNonExistentDexFiles() {
2057 DCHECK_EQ(dex_filenames_.size(), dex_locations_.size());
2058 size_t kept = 0u;
2059 for (size_t i = 0, size = dex_filenames_.size(); i != size; ++i) {
2060 if (!OS::FileExists(dex_filenames_[i])) {
2061 LOG(WARNING) << "Skipping non-existent dex file '" << dex_filenames_[i] << "'";
2062 } else {
2063 dex_filenames_[kept] = dex_filenames_[i];
2064 dex_locations_[kept] = dex_locations_[i];
2065 ++kept;
2066 }
2067 }
2068 dex_filenames_.resize(kept);
2069 dex_locations_.resize(kept);
2070 }
2071
2072 bool AddDexFileSources() {
2073 TimingLogger::ScopedTiming t2("AddDexFileSources", timings_);
2074 if (zip_fd_ != -1) {
2075 DCHECK_EQ(oat_writers_.size(), 1u);
2076 if (!oat_writers_[0]->AddZippedDexFilesSource(ScopedFd(zip_fd_), zip_location_.c_str())) {
2077 return false;
2078 }
2079 } else if (oat_writers_.size() > 1u) {
2080 // Multi-image.
2081 DCHECK_EQ(oat_writers_.size(), dex_filenames_.size());
2082 DCHECK_EQ(oat_writers_.size(), dex_locations_.size());
2083 for (size_t i = 0, size = oat_writers_.size(); i != size; ++i) {
2084 if (!oat_writers_[i]->AddDexFileSource(dex_filenames_[i], dex_locations_[i])) {
2085 return false;
2086 }
2087 }
2088 } else {
2089 DCHECK_EQ(oat_writers_.size(), 1u);
2090 DCHECK_EQ(dex_filenames_.size(), dex_locations_.size());
2091 DCHECK_NE(dex_filenames_.size(), 0u);
2092 for (size_t i = 0; i != dex_filenames_.size(); ++i) {
2093 if (!oat_writers_[0]->AddDexFileSource(dex_filenames_[i], dex_locations_[i])) {
2094 return false;
2095 }
2096 }
2097 }
2098 return true;
2099 }
2100
2101 void CreateOatWriters() {
2102 TimingLogger::ScopedTiming t2("CreateOatWriters", timings_);
2103 elf_writers_.reserve(oat_files_.size());
2104 oat_writers_.reserve(oat_files_.size());
2105 for (const std::unique_ptr<File>& oat_file : oat_files_) {
David Srbecky5d811202016-03-08 13:21:22 +00002106 elf_writers_.emplace_back(CreateElfWriterQuick(instruction_set_,
2107 instruction_set_features_.get(),
2108 compiler_options_.get(),
2109 oat_file.get()));
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002110 elf_writers_.back()->Start();
2111 oat_writers_.emplace_back(new OatWriter(IsBootImage(), timings_));
2112 }
2113 }
2114
Vladimir Marko49b0f452015-12-10 13:49:19 +00002115 void SaveDexInput() {
2116 for (size_t i = 0; i < dex_files_.size(); ++i) {
2117 const DexFile* dex_file = dex_files_[i];
2118 std::string tmp_file_name(StringPrintf("/data/local/tmp/dex2oat.%d.%zd.dex",
2119 getpid(), i));
2120 std::unique_ptr<File> tmp_file(OS::CreateEmptyFile(tmp_file_name.c_str()));
2121 if (tmp_file.get() == nullptr) {
2122 PLOG(ERROR) << "Failed to open file " << tmp_file_name
2123 << ". Try: adb shell chmod 777 /data/local/tmp";
2124 continue;
2125 }
2126 // This is just dumping files for debugging. Ignore errors, and leave remnants.
2127 UNUSED(tmp_file->WriteFully(dex_file->Begin(), dex_file->Size()));
2128 UNUSED(tmp_file->Flush());
2129 UNUSED(tmp_file->Close());
2130 LOG(INFO) << "Wrote input to " << tmp_file_name;
2131 }
2132 }
2133
2134 bool PrepareRuntimeOptions(RuntimeArgumentMap* runtime_options) {
2135 RuntimeOptions raw_options;
2136 if (boot_image_filename_.empty()) {
2137 std::string boot_class_path = "-Xbootclasspath:";
2138 boot_class_path += Join(dex_filenames_, ':');
2139 raw_options.push_back(std::make_pair(boot_class_path, nullptr));
2140 std::string boot_class_path_locations = "-Xbootclasspath-locations:";
2141 boot_class_path_locations += Join(dex_locations_, ':');
2142 raw_options.push_back(std::make_pair(boot_class_path_locations, nullptr));
2143 } else {
2144 std::string boot_image_option = "-Ximage:";
2145 boot_image_option += boot_image_filename_;
2146 raw_options.push_back(std::make_pair(boot_image_option, nullptr));
2147 }
2148 for (size_t i = 0; i < runtime_args_.size(); i++) {
2149 raw_options.push_back(std::make_pair(runtime_args_[i], nullptr));
2150 }
2151
2152 raw_options.push_back(std::make_pair("compilercallbacks", callbacks_.get()));
2153 raw_options.push_back(
2154 std::make_pair("imageinstructionset", GetInstructionSetString(instruction_set_)));
2155
2156 // Only allow no boot image for the runtime if we're compiling one. When we compile an app,
2157 // we don't want fallback mode, it will abort as we do not push a boot classpath (it might
2158 // have been stripped in preopting, anyways).
2159 if (!IsBootImage()) {
2160 raw_options.push_back(std::make_pair("-Xno-dex-file-fallback", nullptr));
2161 }
2162 // Disable libsigchain. We don't don't need it during compilation and it prevents us
2163 // from getting a statically linked version of dex2oat (because of dlsym and RTLD_NEXT).
2164 raw_options.push_back(std::make_pair("-Xno-sig-chain", nullptr));
Lin Zang97f3f7d2016-01-13 10:25:00 +08002165 // Disable Hspace compaction to save heap size virtual space.
2166 // Only need disable Hspace for OOM becasue background collector is equal to
2167 // foreground collector by default for dex2oat.
2168 raw_options.push_back(std::make_pair("-XX:DisableHSpaceCompactForOOM", nullptr));
Vladimir Marko49b0f452015-12-10 13:49:19 +00002169
Andreas Gampeace0dc12016-01-20 13:33:13 -08002170 // If we're asked to be deterministic, ensure non-concurrent GC for determinism. Also
2171 // force the free-list implementation for large objects.
2172 if (compiler_options_->IsForceDeterminism()) {
2173 raw_options.push_back(std::make_pair("-Xgc:nonconcurrent", nullptr));
2174 raw_options.push_back(std::make_pair("-XX:LargeObjectSpace=freelist", nullptr));
2175
2176 // We also need to turn off the nonmoving space. For that, we need to disable HSpace
2177 // compaction (done above) and ensure that neither foreground nor background collectors
2178 // are concurrent.
2179 raw_options.push_back(std::make_pair("-XX:BackgroundGC=nonconcurrent", nullptr));
2180
2181 // To make identity hashcode deterministic, set a known seed.
2182 mirror::Object::SetHashCodeSeed(987654321U);
2183 }
2184
Vladimir Marko49b0f452015-12-10 13:49:19 +00002185 if (!Runtime::ParseOptions(raw_options, false, runtime_options)) {
2186 LOG(ERROR) << "Failed to parse runtime options";
2187 return false;
2188 }
2189 return true;
2190 }
2191
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002192 // Create a runtime necessary for compilation.
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002193 bool CreateRuntime(RuntimeArgumentMap&& runtime_options) {
2194 TimingLogger::ScopedTiming t_runtime("Create runtime", timings_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002195 if (!Runtime::Create(std::move(runtime_options))) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002196 LOG(ERROR) << "Failed to create runtime";
2197 return false;
2198 }
Vladimir Marko307dac92015-10-20 11:20:09 +01002199 runtime_.reset(Runtime::Current());
2200 runtime_->SetInstructionSet(instruction_set_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002201 for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
2202 Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i);
Vladimir Marko307dac92015-10-20 11:20:09 +01002203 if (!runtime_->HasCalleeSaveMethod(type)) {
2204 runtime_->SetCalleeSaveMethod(runtime_->CreateCalleeSaveMethod(), type);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002205 }
2206 }
Vladimir Marko307dac92015-10-20 11:20:09 +01002207 runtime_->GetClassLinker()->FixupDexCaches(runtime_->GetResolutionMethod());
Andreas Gampe2969bcd2015-03-09 12:57:41 -07002208
2209 // Initialize maps for unstarted runtime. This needs to be here, as running clinits needs this
2210 // set up.
Andreas Gampe799681b2015-05-15 19:24:12 -07002211 interpreter::UnstartedRuntime::Initialize();
Andreas Gampe2969bcd2015-03-09 12:57:41 -07002212
Vladimir Marko307dac92015-10-20 11:20:09 +01002213 runtime_->GetClassLinker()->RunRootClinits();
Andreas Gampe2969bcd2015-03-09 12:57:41 -07002214
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002215 // Runtime::Create acquired the mutator_lock_ that is normally given away when we
2216 // Runtime::Start, give it away now so that we don't starve GC.
2217 Thread* self = Thread::Current();
2218 self->TransitionFromRunnableToSuspended(kNative);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002219
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002220 return true;
Vladimir Marko919f5532016-01-20 19:13:01 +00002221 }
2222
Jeff Haodcdc85b2015-12-04 14:06:18 -08002223 // 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 -08002224 bool CreateImageFile()
Mathieu Chartier90443472015-07-16 20:32:27 -07002225 REQUIRES(!Locks::mutator_lock_) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002226 CHECK(image_writer_ != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002227 if (!IsBootImage()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002228 CHECK(image_filenames_.empty());
Jeff Haodcdc85b2015-12-04 14:06:18 -08002229 image_filenames_.push_back(app_image_file_name_.c_str());
2230 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002231 if (!image_writer_->Write(app_image_fd_,
2232 image_filenames_,
Vladimir Marko944da602016-02-19 12:27:55 +00002233 oat_filenames_)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002234 LOG(ERROR) << "Failure during image file creation";
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002235 return false;
2236 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002237
Jeff Haodcdc85b2015-12-04 14:06:18 -08002238 // We need the OatDataBegin entries.
Vladimir Marko944da602016-02-19 12:27:55 +00002239 dchecked_vector<uintptr_t> oat_data_begins;
2240 for (size_t i = 0, size = oat_filenames_.size(); i != size; ++i) {
2241 oat_data_begins.push_back(image_writer_->GetOatDataBegin(i));
Jeff Haodcdc85b2015-12-04 14:06:18 -08002242 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002243 // Destroy ImageWriter before doing FixupElf.
2244 image_writer_.reset();
2245
Vladimir Marko944da602016-02-19 12:27:55 +00002246 for (size_t i = 0, size = oat_filenames_.size(); i != size; ++i) {
2247 const char* oat_filename = oat_filenames_[i];
Jeff Haodcdc85b2015-12-04 14:06:18 -08002248 // Do not fix up the ELF file if we are --compile-pic or compiling the app image
2249 if (!compiler_options_->GetCompilePic() && IsBootImage()) {
2250 std::unique_ptr<File> oat_file(OS::OpenFileReadWrite(oat_filename));
2251 if (oat_file.get() == nullptr) {
2252 PLOG(ERROR) << "Failed to open ELF file: " << oat_filename;
2253 return false;
2254 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08002255
Vladimir Marko944da602016-02-19 12:27:55 +00002256 if (!ElfWriter::Fixup(oat_file.get(), oat_data_begins[i])) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002257 oat_file->Erase();
2258 LOG(ERROR) << "Failed to fixup ELF file " << oat_file->GetPath();
2259 return false;
2260 }
2261
2262 if (oat_file->FlushCloseOrErase()) {
2263 PLOG(ERROR) << "Failed to flush and close fixed ELF file " << oat_file->GetPath();
2264 return false;
2265 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08002266 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002267 }
2268
2269 return true;
2270 }
2271
2272 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
Andreas Gampeb1fcead2015-04-20 18:53:51 -07002273 static std::unordered_set<std::string>* ReadImageClassesFromFile(
2274 const char* image_classes_filename) {
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002275 std::function<std::string(const char*)> process = DotToDescriptor;
2276 return ReadCommentedInputFromFile(image_classes_filename, &process);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002277 }
2278
2279 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
Andreas Gampeb1fcead2015-04-20 18:53:51 -07002280 static std::unordered_set<std::string>* ReadImageClassesFromZip(
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002281 const char* zip_filename,
2282 const char* image_classes_filename,
2283 std::string* error_msg) {
2284 std::function<std::string(const char*)> process = DotToDescriptor;
2285 return ReadCommentedInputFromZip(zip_filename, image_classes_filename, &process, error_msg);
2286 }
2287
2288 // Read lines from the given file, dropping comments and empty lines. Post-process each line with
2289 // the given function.
2290 static std::unordered_set<std::string>* ReadCommentedInputFromFile(
2291 const char* input_filename, std::function<std::string(const char*)>* process) {
2292 std::unique_ptr<std::ifstream> input_file(new std::ifstream(input_filename, std::ifstream::in));
2293 if (input_file.get() == nullptr) {
2294 LOG(ERROR) << "Failed to open input file " << input_filename;
2295 return nullptr;
2296 }
2297 std::unique_ptr<std::unordered_set<std::string>> result(
2298 ReadCommentedInputStream(*input_file, process));
2299 input_file->close();
2300 return result.release();
2301 }
2302
2303 // Read lines from the given file from the given zip file, dropping comments and empty lines.
2304 // Post-process each line with the given function.
2305 static std::unordered_set<std::string>* ReadCommentedInputFromZip(
Andreas Gampeb1fcead2015-04-20 18:53:51 -07002306 const char* zip_filename,
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002307 const char* input_filename,
2308 std::function<std::string(const char*)>* process,
Andreas Gampeb1fcead2015-04-20 18:53:51 -07002309 std::string* error_msg) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002310 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::Open(zip_filename, error_msg));
2311 if (zip_archive.get() == nullptr) {
2312 return nullptr;
2313 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002314 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(input_filename, error_msg));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002315 if (zip_entry.get() == nullptr) {
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002316 *error_msg = StringPrintf("Failed to find '%s' within '%s': %s", input_filename,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002317 zip_filename, error_msg->c_str());
2318 return nullptr;
2319 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002320 std::unique_ptr<MemMap> input_file(zip_entry->ExtractToMemMap(zip_filename,
2321 input_filename,
2322 error_msg));
2323 if (input_file.get() == nullptr) {
2324 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", input_filename,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002325 zip_filename, error_msg->c_str());
2326 return nullptr;
2327 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002328 const std::string input_string(reinterpret_cast<char*>(input_file->Begin()),
2329 input_file->Size());
2330 std::istringstream input_stream(input_string);
2331 return ReadCommentedInputStream(input_stream, process);
2332 }
2333
2334 // Read lines from the given stream, dropping comments and empty lines. Post-process each line
2335 // with the given function.
2336 static std::unordered_set<std::string>* ReadCommentedInputStream(
2337 std::istream& in_stream,
2338 std::function<std::string(const char*)>* process) {
2339 std::unique_ptr<std::unordered_set<std::string>> image_classes(
2340 new std::unordered_set<std::string>);
2341 while (in_stream.good()) {
2342 std::string dot;
2343 std::getline(in_stream, dot);
2344 if (StartsWith(dot, "#") || dot.empty()) {
2345 continue;
2346 }
2347 if (process != nullptr) {
2348 std::string descriptor((*process)(dot.c_str()));
2349 image_classes->insert(descriptor);
2350 } else {
2351 image_classes->insert(dot);
2352 }
2353 }
2354 return image_classes.release();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002355 }
2356
Mathieu Chartier49285c52014-12-02 15:43:48 -08002357 void LogCompletionTime() {
Andreas Gampe1d00add2015-02-27 19:35:46 -08002358 // Note: when creation of a runtime fails, e.g., when trying to compile an app but when there
2359 // is no image, there won't be a Runtime::Current().
Brian Carlstroma11a34c2015-03-06 08:44:45 -08002360 // Note: driver creation can fail when loading an invalid dex file.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002361 LOG(INFO) << "dex2oat took " << PrettyDuration(NanoTime() - start_ns_)
Mathieu Chartierab972ef2014-12-03 17:38:22 -08002362 << " (threads: " << thread_count_ << ") "
Andreas Gampe3f30e122015-09-17 14:03:21 -07002363 << ((Runtime::Current() != nullptr && driver_ != nullptr) ?
Andreas Gampe1d00add2015-02-27 19:35:46 -08002364 driver_->GetMemoryUsageString(kIsDebugBuild || VLOG_IS_ON(compiler)) :
2365 "");
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002366 }
2367
Jeff Haodcdc85b2015-12-04 14:06:18 -08002368 std::string StripIsaFrom(const char* image_filename, InstructionSet isa) {
2369 std::string res(image_filename);
2370 size_t last_slash = res.rfind('/');
2371 if (last_slash == std::string::npos || last_slash == 0) {
2372 return res;
2373 }
2374 size_t penultimate_slash = res.rfind('/', last_slash - 1);
2375 if (penultimate_slash == std::string::npos) {
2376 return res;
2377 }
2378 // Check that the string in-between is the expected one.
2379 if (res.substr(penultimate_slash + 1, last_slash - penultimate_slash - 1) !=
2380 GetInstructionSetString(isa)) {
2381 LOG(WARNING) << "Unexpected string when trying to strip isa: " << res;
2382 return res;
2383 }
2384 return res.substr(0, penultimate_slash) + res.substr(last_slash);
2385 }
2386
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002387 std::unique_ptr<CompilerOptions> compiler_options_;
2388 Compiler::Kind compiler_kind_;
2389
2390 InstructionSet instruction_set_;
2391 std::unique_ptr<const InstructionSetFeatures> instruction_set_features_;
2392
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002393 uint32_t image_file_location_oat_checksum_;
2394 uintptr_t image_file_location_oat_data_begin_;
2395 int32_t image_patch_delta_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002396 std::unique_ptr<SafeMap<std::string, std::string> > key_value_store_;
2397
Vladimir Marko307dac92015-10-20 11:20:09 +01002398 std::unique_ptr<VerificationResults> verification_results_;
Andreas Gampe3f30e122015-09-17 14:03:21 -07002399
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002400 DexFileToMethodInlinerMap method_inliner_map_;
2401 std::unique_ptr<QuickCompilerCallbacks> callbacks_;
2402
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002403 std::unique_ptr<Runtime> runtime_;
2404
Richard Uhlerfbef44d2014-12-23 09:48:51 -08002405 // Ownership for the class path files.
2406 std::vector<std::unique_ptr<const DexFile>> class_path_files_;
2407
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002408 size_t thread_count_;
2409 uint64_t start_ns_;
2410 std::unique_ptr<WatchDog> watchdog_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002411 std::vector<std::unique_ptr<File>> oat_files_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002412 std::string oat_location_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002413 std::vector<const char*> oat_filenames_;
2414 std::vector<const char*> oat_unstripped_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002415 int oat_fd_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002416 std::vector<const char*> dex_filenames_;
2417 std::vector<const char*> dex_locations_;
2418 int zip_fd_;
2419 std::string zip_location_;
Vladimir Marko49b0f452015-12-10 13:49:19 +00002420 std::string boot_image_filename_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002421 std::vector<const char*> runtime_args_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002422 std::vector<const char*> image_filenames_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002423 uintptr_t image_base_;
2424 const char* image_classes_zip_filename_;
2425 const char* image_classes_filename_;
Mathieu Chartierceb07b32015-12-10 09:33:21 -08002426 ImageHeader::StorageMode image_storage_mode_;
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08002427 const char* compiled_classes_zip_filename_;
2428 const char* compiled_classes_filename_;
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002429 const char* compiled_methods_zip_filename_;
2430 const char* compiled_methods_filename_;
Andreas Gampeb1fcead2015-04-20 18:53:51 -07002431 std::unique_ptr<std::unordered_set<std::string>> image_classes_;
2432 std::unique_ptr<std::unordered_set<std::string>> compiled_classes_;
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002433 std::unique_ptr<std::unordered_set<std::string>> compiled_methods_;
Mathieu Chartiera90c7722015-10-29 15:41:36 -07002434 bool app_image_;
2435 bool boot_image_;
Jeff Hao436183f2016-01-12 16:36:50 -08002436 bool multi_image_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002437 bool is_host_;
2438 std::string android_root_;
2439 std::vector<const DexFile*> dex_files_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002440 std::string no_inline_from_string_;
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002441 std::vector<jobject> dex_caches_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002442 jobject class_loader_;
Andreas Gampe3f30e122015-09-17 14:03:21 -07002443
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002444 std::vector<std::unique_ptr<ElfWriter>> elf_writers_;
2445 std::vector<std::unique_ptr<OatWriter>> oat_writers_;
2446 std::vector<OutputStream*> rodata_;
Vladimir Marko307dac92015-10-20 11:20:09 +01002447 std::unique_ptr<ImageWriter> image_writer_;
2448 std::unique_ptr<CompilerDriver> driver_;
Andreas Gampe3f30e122015-09-17 14:03:21 -07002449
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002450 std::vector<std::unique_ptr<MemMap>> opened_dex_files_maps_;
2451 std::vector<std::unique_ptr<const DexFile>> opened_dex_files_;
2452
Vladimir Marko47496c22016-01-27 16:15:08 +00002453 std::vector<const DexFile*> no_inline_from_dex_files_;
2454
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002455 std::vector<std::string> verbose_methods_;
2456 bool dump_stats_;
2457 bool dump_passes_;
2458 bool dump_timing_;
2459 bool dump_slow_timing_;
Andreas Gampee21dc3d2014-12-08 16:59:43 -08002460 std::string swap_file_name_;
2461 int swap_fd_;
Mathieu Chartiera90c7722015-10-29 15:41:36 -07002462 std::string app_image_file_name_;
2463 int app_image_fd_;
Calin Juravle2e2db782016-02-23 12:00:03 +00002464 std::string profile_file_;
2465 int profile_file_fd_;
Calin Juravle998c2162015-12-21 15:39:33 +02002466 std::unique_ptr<ProfileCompilationInfo> profile_compilation_info_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002467 TimingLogger* timings_;
2468 std::unique_ptr<CumulativeLogger> compiler_phases_timings_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002469 std::vector<std::vector<const DexFile*>> dex_files_per_oat_file_;
Vladimir Marko944da602016-02-19 12:27:55 +00002470 std::unordered_map<const DexFile*, size_t> dex_file_oat_index_map_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002471
2472 // Backing storage.
2473 std::vector<std::string> char_backing_storage_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002474
Andreas Gampeace0dc12016-01-20 13:33:13 -08002475 // See CompilerOptions.force_determinism_.
2476 bool force_determinism_;
2477
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002478 DISALLOW_IMPLICIT_CONSTRUCTORS(Dex2Oat);
2479};
2480
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002481static void b13564922() {
2482#if defined(__linux__) && defined(__arm__)
2483 int major, minor;
2484 struct utsname uts;
2485 if (uname(&uts) != -1 &&
2486 sscanf(uts.release, "%d.%d", &major, &minor) == 2 &&
2487 ((major < 3) || ((major == 3) && (minor < 4)))) {
2488 // Kernels before 3.4 don't handle the ASLR well and we can run out of address
2489 // space (http://b/13564922). Work around the issue by inhibiting further mmap() randomization.
2490 int old_personality = personality(0xffffffff);
2491 if ((old_personality & ADDR_NO_RANDOMIZE) == 0) {
2492 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
2493 if (new_personality == -1) {
2494 LOG(WARNING) << "personality(. | ADDR_NO_RANDOMIZE) failed.";
2495 }
2496 }
2497 }
2498#endif
2499}
2500
Andreas Gampe10e477d2014-11-19 12:57:42 -08002501static int CompileImage(Dex2Oat& dex2oat) {
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08002502 dex2oat.LoadClassProfileDescriptors();
Andreas Gampe10e477d2014-11-19 12:57:42 -08002503 dex2oat.Compile();
2504
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002505 if (!dex2oat.WriteOatFiles()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002506 dex2oat.EraseOatFiles();
Andreas Gampe10e477d2014-11-19 12:57:42 -08002507 return EXIT_FAILURE;
2508 }
2509
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002510 // Flush boot.oat. We always expect the output file by name, and it will be re-opened from the
2511 // unstripped name. Do not close the file if we are compiling the image with an oat fd since the
2512 // image writer will require this fd to generate the image.
2513 if (dex2oat.ShouldKeepOatFileOpen()) {
2514 if (!dex2oat.FlushOatFiles()) {
2515 return EXIT_FAILURE;
2516 }
2517 } else if (!dex2oat.FlushCloseOatFiles()) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08002518 return EXIT_FAILURE;
2519 }
2520
Jeff Haodcdc85b2015-12-04 14:06:18 -08002521 // Creates the boot.art and patches the oat files.
Andreas Gampe10e477d2014-11-19 12:57:42 -08002522 if (!dex2oat.HandleImage()) {
2523 return EXIT_FAILURE;
2524 }
2525
2526 // When given --host, finish early without stripping.
2527 if (dex2oat.IsHost()) {
2528 dex2oat.DumpTiming();
2529 return EXIT_SUCCESS;
2530 }
2531
Jeff Haodcdc85b2015-12-04 14:06:18 -08002532 // Copy stripped to unstripped location, if necessary.
2533 if (!dex2oat.CopyStrippedToUnstripped()) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08002534 return EXIT_FAILURE;
2535 }
2536
Jeff Haodcdc85b2015-12-04 14:06:18 -08002537 // FlushClose again, as stripping might have re-opened the oat files.
2538 if (!dex2oat.FlushCloseOatFiles()) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08002539 return EXIT_FAILURE;
2540 }
2541
2542 dex2oat.DumpTiming();
2543 return EXIT_SUCCESS;
2544}
2545
2546static int CompileApp(Dex2Oat& dex2oat) {
2547 dex2oat.Compile();
2548
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002549 if (!dex2oat.WriteOatFiles()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002550 dex2oat.EraseOatFiles();
Andreas Gampe10e477d2014-11-19 12:57:42 -08002551 return EXIT_FAILURE;
2552 }
2553
Jeff Haodcdc85b2015-12-04 14:06:18 -08002554 // Do not close the oat files here. We might have gotten the output file by file descriptor,
Andreas Gampe10e477d2014-11-19 12:57:42 -08002555 // which we would lose.
Andreas Gampe10e477d2014-11-19 12:57:42 -08002556
2557 // When given --host, finish early without stripping.
2558 if (dex2oat.IsHost()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002559 if (!dex2oat.FlushCloseOatFiles()) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08002560 return EXIT_FAILURE;
2561 }
2562
2563 dex2oat.DumpTiming();
2564 return EXIT_SUCCESS;
2565 }
2566
Jeff Haodcdc85b2015-12-04 14:06:18 -08002567 // Copy stripped to unstripped location, if necessary. This will implicitly flush & close the
2568 // stripped versions. If this is given, we expect to be able to open writable files by name.
2569 if (!dex2oat.CopyStrippedToUnstripped()) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08002570 return EXIT_FAILURE;
2571 }
2572
Jeff Haodcdc85b2015-12-04 14:06:18 -08002573 // Flush and close the files.
2574 if (!dex2oat.FlushCloseOatFiles()) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08002575 return EXIT_FAILURE;
2576 }
2577
2578 dex2oat.DumpTiming();
2579 return EXIT_SUCCESS;
2580}
2581
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002582static int dex2oat(int argc, char** argv) {
2583 b13564922();
2584
2585 TimingLogger timings("compiler", false, false);
2586
Roland Levillain5c7e2602016-02-23 18:08:53 +00002587 // Allocate `dex2oat` on the heap instead of on the stack, as Clang
2588 // might produce a stack frame too large for this function or for
2589 // functions inlining it (such as main), that would not fit the
2590 // requirements of the `-Wframe-larger-than` option.
2591 std::unique_ptr<Dex2Oat> dex2oat = MakeUnique<Dex2Oat>(&timings);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002592
2593 // Parse arguments. Argument mistakes will lead to exit(EXIT_FAILURE) in UsageError.
Roland Levillain5c7e2602016-02-23 18:08:53 +00002594 dex2oat->ParseArgs(argc, argv);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002595
Calin Juravleb077e152016-02-18 18:47:37 +00002596 // If needed, process profile information for profile guided compilation.
Calin Juravle998c2162015-12-21 15:39:33 +02002597 // This operation involves I/O.
Roland Levillain5c7e2602016-02-23 18:08:53 +00002598 if (dex2oat->UseProfileGuidedCompilation()) {
Calin Juravleb077e152016-02-18 18:47:37 +00002599 if (!dex2oat->LoadProfile()) {
2600 LOG(ERROR) << "Failed to process profile file";
Calin Juravle998c2162015-12-21 15:39:33 +02002601 return EXIT_FAILURE;
2602 }
2603 }
2604
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002605 // Check early that the result of compilation can be written
Roland Levillain5c7e2602016-02-23 18:08:53 +00002606 if (!dex2oat->OpenFile()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002607 return EXIT_FAILURE;
2608 }
2609
Andreas Gampe046c7062015-05-18 23:22:54 -07002610 // Print the complete line when any of the following is true:
2611 // 1) Debug build
2612 // 2) Compiling an image
2613 // 3) Compiling with --host
2614 // 4) Compiling on the host (not a target build)
2615 // Otherwise, print a stripped command line.
Roland Levillain5c7e2602016-02-23 18:08:53 +00002616 if (kIsDebugBuild || dex2oat->IsBootImage() || dex2oat->IsHost() || !kIsTargetBuild) {
Andreas Gampe046c7062015-05-18 23:22:54 -07002617 LOG(INFO) << CommandLine();
2618 } else {
2619 LOG(INFO) << StrippedCommandLine();
2620 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002621
Roland Levillain5c7e2602016-02-23 18:08:53 +00002622 if (!dex2oat->Setup()) {
2623 dex2oat->EraseOatFiles();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002624 return EXIT_FAILURE;
2625 }
2626
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002627 bool result;
Roland Levillain5c7e2602016-02-23 18:08:53 +00002628 if (dex2oat->IsImage()) {
2629 result = CompileImage(*dex2oat);
Andreas Gampe10e477d2014-11-19 12:57:42 -08002630 } else {
Roland Levillain5c7e2602016-02-23 18:08:53 +00002631 result = CompileApp(*dex2oat);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002632 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002633
Roland Levillain5c7e2602016-02-23 18:08:53 +00002634 dex2oat->Shutdown();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002635 return result;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002636}
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002637} // namespace art
Brian Carlstrom7940e442013-07-12 13:46:57 -07002638
2639int main(int argc, char** argv) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002640 int result = art::dex2oat(argc, argv);
2641 // Everything was done, do an explicit exit here to avoid running Runtime destructors that take
2642 // time (bug 10645725) unless we're a debug build or running on valgrind. Note: The Dex2Oat class
2643 // should not destruct the runtime in this case.
Evgenii Stepanov1e133742015-05-20 12:30:59 -07002644 if (!art::kIsDebugBuild && (RUNNING_ON_MEMORY_TOOL == 0)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002645 exit(result);
2646 }
2647 return result;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002648}