blob: 53331284cb1f77945b28eaac4e82fbb9e34fee7d [file] [log] [blame]
Brian Carlstrom7940e442013-07-12 13:46:57 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Andreas Gamped687e372015-04-28 23:16:03 -070017#include <inttypes.h>
Brian Carlstrom7940e442013-07-12 13:46:57 -070018#include <stdio.h>
19#include <stdlib.h>
20#include <sys/stat.h>
Evgenii Stepanov1e133742015-05-20 12:30:59 -070021#include "base/memory_tool.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070022
23#include <fstream>
24#include <iostream>
25#include <sstream>
26#include <string>
Andreas Gampeb1fcead2015-04-20 18:53:51 -070027#include <unordered_set>
Brian Carlstrom7940e442013-07-12 13:46:57 -070028#include <vector>
29
Vladimir Markof94b7812014-06-05 15:48:04 +010030#if defined(__linux__) && defined(__arm__)
31#include <sys/personality.h>
32#include <sys/utsname.h>
33#endif
34
Ian Rogerscf7f1912014-10-22 22:06:39 -070035#define ATRACE_TAG ATRACE_TAG_DALVIK
Ian Rogersd582fa42014-11-05 23:46:43 -080036#include <cutils/trace.h>
Ian Rogerscf7f1912014-10-22 22:06:39 -070037
Ian Rogersd582fa42014-11-05 23:46:43 -080038#include "arch/instruction_set_features.h"
Andreas Gampec5a3ea72015-01-13 16:41:53 -080039#include "arch/mips/instruction_set_features_mips.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000040#include "art_method-inl.h"
Ian Rogersc7dd2952014-10-21 23:31:19 -070041#include "base/dumpable.h"
Andreas Gampe794ad762015-02-23 08:12:24 -080042#include "base/macros.h"
Calin Juravle2e2db782016-02-23 12:00:03 +000043#include "base/scoped_flock.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070044#include "base/stl_util.h"
45#include "base/stringpiece.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010046#include "base/time_utils.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070047#include "base/timing_logger.h"
48#include "base/unix_file/fd_file.h"
49#include "class_linker.h"
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +000050#include "compiler.h"
Vladimir Marko2b5eaa22013-12-13 13:59:30 +000051#include "compiler_callbacks.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000052#include "debug/method_debug_info.h"
Mathieu Chartier5bdab122015-01-26 18:30:19 -080053#include "dex/pass_manager.h"
Ian Rogerse63db272014-07-15 15:36:11 -070054#include "dex/quick/dex_file_to_method_inliner_map.h"
David Srbecky4fda4eb2016-02-05 13:34:46 +000055#include "dex/quick_compiler_callbacks.h"
56#include "dex/verification_results.h"
57#include "dex_file-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070058#include "driver/compiler_driver.h"
Brian Carlstrom6449c622014-02-10 23:48:36 -080059#include "driver/compiler_options.h"
Andreas Gampe88ec7f42014-11-05 10:18:32 -080060#include "elf_file.h"
Tong Shen62d1ca32014-09-03 17:24:56 -070061#include "elf_writer.h"
Vladimir Marko10c13562015-11-25 14:33:36 +000062#include "elf_writer_quick.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070063#include "gc/space/image_space.h"
64#include "gc/space/space-inl.h"
65#include "image_writer.h"
Andreas Gampe2969bcd2015-03-09 12:57:41 -070066#include "interpreter/unstarted_runtime.h"
Calin Juravle998c2162015-12-21 15:39:33 +020067#include "jit/offline_profiling_info.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070068#include "leb128.h"
Vladimir Marko944da602016-02-19 12:27:55 +000069#include "linker/multi_oat_relative_patcher.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070070#include "mirror/class-inl.h"
71#include "mirror/class_loader.h"
72#include "mirror/object-inl.h"
73#include "mirror/object_array-inl.h"
74#include "oat_writer.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070075#include "os.h"
76#include "runtime.h"
Vladimir Marko49b0f452015-12-10 13:49:19 +000077#include "runtime_options.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070078#include "ScopedLocalRef.h"
79#include "scoped_thread_state_change.h"
Alex Light53cb16b2014-06-12 11:26:29 -070080#include "utils.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070081#include "well_known_classes.h"
82#include "zip_archive.h"
83
84namespace art {
85
Brian Carlstrom6449c622014-02-10 23:48:36 -080086static int original_argc;
87static char** original_argv;
88
89static std::string CommandLine() {
90 std::vector<std::string> command;
91 for (int i = 0; i < original_argc; ++i) {
92 command.push_back(original_argv[i]);
93 }
94 return Join(command, ' ');
95}
96
Andreas Gampe046c7062015-05-18 23:22:54 -070097// A stripped version. Remove some less essential parameters. If we see a "--zip-fd=" parameter, be
98// even more aggressive. There won't be much reasonable data here for us in that case anyways (the
99// locations are all staged).
100static std::string StrippedCommandLine() {
101 std::vector<std::string> command;
102
103 // Do a pre-pass to look for zip-fd.
104 bool saw_zip_fd = false;
105 for (int i = 0; i < original_argc; ++i) {
106 if (StartsWith(original_argv[i], "--zip-fd=")) {
107 saw_zip_fd = true;
108 break;
109 }
110 }
111
112 // Now filter out things.
113 for (int i = 0; i < original_argc; ++i) {
114 // All runtime-arg parameters are dropped.
115 if (strcmp(original_argv[i], "--runtime-arg") == 0) {
116 i++; // Drop the next part, too.
117 continue;
118 }
119
120 // Any instruction-setXXX is dropped.
121 if (StartsWith(original_argv[i], "--instruction-set")) {
122 continue;
123 }
124
125 // The boot image is dropped.
126 if (StartsWith(original_argv[i], "--boot-image=")) {
127 continue;
128 }
129
Mathieu Chartier97590cc2016-02-03 15:50:29 -0800130 // The image format is dropped.
131 if (StartsWith(original_argv[i], "--image-format=")) {
132 continue;
133 }
134
Andreas Gampe046c7062015-05-18 23:22:54 -0700135 // This should leave any dex-file and oat-file options, describing what we compiled.
136
137 // However, we prefer to drop this when we saw --zip-fd.
138 if (saw_zip_fd) {
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700139 // Drop anything --zip-X, --dex-X, --oat-X, --swap-X, or --app-image-X
Andreas Gampe046c7062015-05-18 23:22:54 -0700140 if (StartsWith(original_argv[i], "--zip-") ||
141 StartsWith(original_argv[i], "--dex-") ||
142 StartsWith(original_argv[i], "--oat-") ||
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700143 StartsWith(original_argv[i], "--swap-") ||
144 StartsWith(original_argv[i], "--app-image-")) {
Andreas Gampe046c7062015-05-18 23:22:54 -0700145 continue;
146 }
147 }
148
149 command.push_back(original_argv[i]);
150 }
151
152 // Construct the final output.
153 if (command.size() <= 1U) {
154 // It seems only "/system/bin/dex2oat" is left, or not even that. Use a pretty line.
155 return "Starting dex2oat.";
156 }
157 return Join(command, ' ');
158}
159
Brian Carlstrom7940e442013-07-12 13:46:57 -0700160static void UsageErrorV(const char* fmt, va_list ap) {
161 std::string error;
162 StringAppendV(&error, fmt, ap);
163 LOG(ERROR) << error;
164}
165
166static void UsageError(const char* fmt, ...) {
167 va_list ap;
168 va_start(ap, fmt);
169 UsageErrorV(fmt, ap);
170 va_end(ap);
171}
172
Andreas Gampe794ad762015-02-23 08:12:24 -0800173NO_RETURN static void Usage(const char* fmt, ...) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700174 va_list ap;
175 va_start(ap, fmt);
176 UsageErrorV(fmt, ap);
177 va_end(ap);
178
Brian Carlstrom6449c622014-02-10 23:48:36 -0800179 UsageError("Command: %s", CommandLine().c_str());
180
Brian Carlstrom7940e442013-07-12 13:46:57 -0700181 UsageError("Usage: dex2oat [options]...");
182 UsageError("");
Jean-Philippe Halimi3d329d72015-03-23 14:09:48 +0100183 UsageError(" -j<number>: specifies the number of threads used for compilation.");
184 UsageError(" Default is the number of detected hardware threads available on the");
185 UsageError(" host system.");
186 UsageError(" Example: -j12");
187 UsageError("");
Richard Uhlere934df22015-03-17 11:26:16 -0700188 UsageError(" --dex-file=<dex-file>: specifies a .dex, .jar, or .apk file to compile.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700189 UsageError(" Example: --dex-file=/system/framework/core.jar");
190 UsageError("");
Richard Uhlere934df22015-03-17 11:26:16 -0700191 UsageError(" --dex-location=<dex-location>: specifies an alternative dex location to");
192 UsageError(" encode in the oat file for the corresponding --dex-file argument.");
193 UsageError(" Example: --dex-file=/home/build/out/system/framework/core.jar");
194 UsageError(" --dex-location=/system/framework/core.jar");
195 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700196 UsageError(" --zip-fd=<file-descriptor>: specifies a file descriptor of a zip file");
197 UsageError(" containing a classes.dex file to compile.");
198 UsageError(" Example: --zip-fd=5");
199 UsageError("");
Brian Carlstrom45602482013-07-21 22:07:55 -0700200 UsageError(" --zip-location=<zip-location>: specifies a symbolic name for the file");
201 UsageError(" corresponding to the file descriptor specified by --zip-fd.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700202 UsageError(" Example: --zip-location=/system/app/Calculator.apk");
203 UsageError("");
Jeff Haodcdc85b2015-12-04 14:06:18 -0800204 UsageError(" --oat-file=<file.oat>: specifies an oat output destination via a filename.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700205 UsageError(" Example: --oat-file=/system/framework/boot.oat");
206 UsageError("");
207 UsageError(" --oat-fd=<number>: specifies the oat output destination via a file descriptor.");
Wonil Kim9cb554a2014-04-28 11:26:55 +0900208 UsageError(" Example: --oat-fd=6");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700209 UsageError("");
210 UsageError(" --oat-location=<oat-name>: specifies a symbolic name for the file corresponding");
211 UsageError(" to the file descriptor specified by --oat-fd.");
212 UsageError(" Example: --oat-location=/data/dalvik-cache/system@app@Calculator.apk.oat");
213 UsageError("");
Jeff Haodcdc85b2015-12-04 14:06:18 -0800214 UsageError(" --oat-symbols=<file.oat>: specifies an oat output destination with full symbols.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700215 UsageError(" Example: --oat-symbols=/symbols/system/framework/boot.oat");
216 UsageError("");
Jeff Haodcdc85b2015-12-04 14:06:18 -0800217 UsageError(" --image=<file.art>: specifies an output image filename.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700218 UsageError(" Example: --image=/system/framework/boot.art");
219 UsageError("");
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800220 UsageError(" --image-format=(uncompressed|lz4):");
221 UsageError(" Which format to store the image.");
222 UsageError(" Example: --image-format=lz4");
223 UsageError(" Default: uncompressed");
224 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700225 UsageError(" --image-classes=<classname-file>: specifies classes to include in an image.");
226 UsageError(" Example: --image=frameworks/base/preloaded-classes");
227 UsageError("");
228 UsageError(" --base=<hex-address>: specifies the base address when creating a boot image.");
229 UsageError(" Example: --base=0x50000000");
230 UsageError("");
231 UsageError(" --boot-image=<file.art>: provide the image file for the boot class path.");
Kevin Brodsky64fff412015-11-24 14:24:34 +0000232 UsageError(" Do not include the arch as part of the name, it is added automatically.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700233 UsageError(" Example: --boot-image=/system/framework/boot.art");
Kevin Brodsky64fff412015-11-24 14:24:34 +0000234 UsageError(" (specifies /system/framework/<arch>/boot.art as the image file)");
Nicolas Geoffray9583fbc2014-02-28 15:21:07 +0000235 UsageError(" Default: $ANDROID_ROOT/system/framework/boot.art");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700236 UsageError("");
237 UsageError(" --android-root=<path>: used to locate libraries for portable linking.");
238 UsageError(" Example: --android-root=out/host/linux-x86");
239 UsageError(" Default: $ANDROID_ROOT");
240 UsageError("");
Andreas Gampe57b34292015-01-14 15:45:59 -0800241 UsageError(" --instruction-set=(arm|arm64|mips|mips64|x86|x86_64): compile for a particular");
Alex Light53cb16b2014-06-12 11:26:29 -0700242 UsageError(" instruction set.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700243 UsageError(" Example: --instruction-set=x86");
244 UsageError(" Default: arm");
245 UsageError("");
Dave Allison70202782013-10-22 17:52:19 -0700246 UsageError(" --instruction-set-features=...,: Specify instruction set features");
247 UsageError(" Example: --instruction-set-features=div");
248 UsageError(" Default: default");
249 UsageError("");
Igor Murashkin46774762014-10-22 11:37:02 -0700250 UsageError(" --compile-pic: Force indirect use of code, methods, and classes");
251 UsageError(" Default: disabled");
252 UsageError("");
Elliott Hughes956af0f2014-12-11 14:34:28 -0800253 UsageError(" --compiler-backend=(Quick|Optimizing): select compiler backend");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700254 UsageError(" set.");
Elliott Hughes956af0f2014-12-11 14:34:28 -0800255 UsageError(" Example: --compiler-backend=Optimizing");
Nicolas Geoffray409e8092015-10-01 10:32:19 +0100256 UsageError(" Default: Optimizing");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700257 UsageError("");
Nicolas Geoffray88157ef2014-09-12 10:29:53 +0100258 UsageError(" --compiler-filter="
259 "(verify-none"
260 "|interpret-only"
261 "|space"
262 "|balanced"
263 "|speed"
264 "|everything"
265 "|time):");
Jeff Hao4a200f52014-04-01 14:58:49 -0700266 UsageError(" select compiler filter.");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800267 UsageError(" Example: --compiler-filter=everything");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800268 UsageError(" Default: speed");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800269 UsageError("");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800270 UsageError(" --huge-method-max=<method-instruction-count>: threshold size for a huge");
271 UsageError(" method for compiler filter tuning.");
272 UsageError(" Example: --huge-method-max=%d", CompilerOptions::kDefaultHugeMethodThreshold);
273 UsageError(" Default: %d", CompilerOptions::kDefaultHugeMethodThreshold);
274 UsageError("");
275 UsageError(" --large-method-max=<method-instruction-count>: threshold size for a large");
276 UsageError(" method for compiler filter tuning.");
277 UsageError(" Example: --large-method-max=%d", CompilerOptions::kDefaultLargeMethodThreshold);
278 UsageError(" Default: %d", CompilerOptions::kDefaultLargeMethodThreshold);
279 UsageError("");
280 UsageError(" --small-method-max=<method-instruction-count>: threshold size for a small");
281 UsageError(" method for compiler filter tuning.");
282 UsageError(" Example: --small-method-max=%d", CompilerOptions::kDefaultSmallMethodThreshold);
283 UsageError(" Default: %d", CompilerOptions::kDefaultSmallMethodThreshold);
284 UsageError("");
285 UsageError(" --tiny-method-max=<method-instruction-count>: threshold size for a tiny");
286 UsageError(" method for compiler filter tuning.");
287 UsageError(" Example: --tiny-method-max=%d", CompilerOptions::kDefaultTinyMethodThreshold);
288 UsageError(" Default: %d", CompilerOptions::kDefaultTinyMethodThreshold);
289 UsageError("");
290 UsageError(" --num-dex-methods=<method-count>: threshold size for a small dex file for");
291 UsageError(" compiler filter tuning. If the input has fewer than this many methods");
Jeff Hao4a200f52014-04-01 14:58:49 -0700292 UsageError(" and the filter is not interpret-only or verify-none, overrides the");
293 UsageError(" filter to use speed");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800294 UsageError(" Example: --num-dex-method=%d", CompilerOptions::kDefaultNumDexMethodsThreshold);
295 UsageError(" Default: %d", CompilerOptions::kDefaultNumDexMethodsThreshold);
296 UsageError("");
Calin Juravleec748352015-07-29 13:52:12 +0100297 UsageError(" --inline-depth-limit=<depth-limit>: the depth limit of inlining for fine tuning");
298 UsageError(" the compiler. A zero value will disable inlining. Honored only by Optimizing.");
Roland Levillaina215b952015-08-07 11:38:32 +0100299 UsageError(" Has priority over the --compiler-filter option. Intended for ");
300 UsageError(" development/experimental use.");
Calin Juravleec748352015-07-29 13:52:12 +0100301 UsageError(" Example: --inline-depth-limit=%d", CompilerOptions::kDefaultInlineDepthLimit);
302 UsageError(" Default: %d", CompilerOptions::kDefaultInlineDepthLimit);
303 UsageError("");
304 UsageError(" --inline-max-code-units=<code-units-count>: the maximum code units that a method");
305 UsageError(" can have to be considered for inlining. A zero value will disable inlining.");
Roland Levillaina215b952015-08-07 11:38:32 +0100306 UsageError(" Honored only by Optimizing. Has priority over the --compiler-filter option.");
307 UsageError(" Intended for development/experimental use.");
Calin Juravleec748352015-07-29 13:52:12 +0100308 UsageError(" Example: --inline-max-code-units=%d",
309 CompilerOptions::kDefaultInlineMaxCodeUnits);
310 UsageError(" Default: %d", CompilerOptions::kDefaultInlineMaxCodeUnits);
311 UsageError("");
Ian Rogers46398602013-08-20 07:50:36 -0700312 UsageError(" --dump-timing: display a breakdown of where time was spent");
313 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700314 UsageError(" --include-patch-information: Include patching information so the generated code");
315 UsageError(" can have its base address moved without full recompilation.");
316 UsageError("");
317 UsageError(" --no-include-patch-information: Do not include patching information.");
318 UsageError("");
David Srbecky8363c772015-05-28 16:12:43 +0100319 UsageError(" -g");
320 UsageError(" --generate-debug-info: Generate debug information for native debugging,");
321 UsageError(" such as stack unwinding information, ELF symbols and DWARF sections.");
David Srbecky3e09eeb2016-01-12 14:54:03 +0000322 UsageError(" If used without --native-debuggable, it will be best-effort only.");
323 UsageError(" This option does not affect the generated code. (disabled by default)");
Alex Light78382fa2014-06-06 15:45:32 -0700324 UsageError("");
David Srbecky8363c772015-05-28 16:12:43 +0100325 UsageError(" --no-generate-debug-info: Do not generate debug information for native debugging.");
David Srbecky8dc73242015-04-12 11:40:39 +0100326 UsageError("");
David Srbecky5b1c2ca2016-01-25 17:32:41 +0000327 UsageError(" --generate-mini-debug-info: Generate minimal amount of LZMA-compressed");
328 UsageError(" debug information necessary to print backtraces. (disabled by default)");
329 UsageError("");
330 UsageError(" --no-generate-mini-debug-info: Do do generated backtrace info.");
331 UsageError("");
David Srbecky3e09eeb2016-01-12 14:54:03 +0000332 UsageError(" --debuggable: Produce code debuggable with Java debugger.");
David Srbecky0cf44932015-12-09 14:09:59 +0000333 UsageError("");
334 UsageError(" --native-debuggable: Produce code debuggable with native debugger (like LLDB).");
335 UsageError(" Implies --debuggable.");
336 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700337 UsageError(" --runtime-arg <argument>: used to specify various arguments for the runtime,");
338 UsageError(" such as initial heap size, maximum heap size, and verbose output.");
339 UsageError(" Use a separate --runtime-arg switch for each argument.");
340 UsageError(" Example: --runtime-arg -Xms256m");
Jeff Hao4a200f52014-04-01 14:58:49 -0700341 UsageError("");
Dave Allisond6ed6422014-04-09 23:36:15 +0000342 UsageError(" --profile-file=<filename>: specify profiler output file to use for compilation.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700343 UsageError("");
Calin Juravle877fd962016-01-05 14:29:29 +0000344 UsageError(" --profile-file-fd=<number>: same as --profile-file but accepts a file descriptor.");
345 UsageError(" Cannot be used together with --profile-file.");
346 UsageError("");
Chao-ying Fucd8ce662014-03-11 14:57:19 -0700347 UsageError(" --print-pass-names: print a list of pass names");
348 UsageError("");
349 UsageError(" --disable-passes=<pass-names>: disable one or more passes separated by comma.");
350 UsageError(" Example: --disable-passes=UseCount,BBOptimizations");
351 UsageError("");
Razvan A Lupusorubd25d4b2014-07-02 18:16:51 -0700352 UsageError(" --print-pass-options: print a list of passes that have configurable options along "
353 "with the setting.");
354 UsageError(" Will print default if no overridden setting exists.");
355 UsageError("");
356 UsageError(" --pass-options=Pass1Name:Pass1OptionName:Pass1Option#,"
357 "Pass2Name:Pass2OptionName:Pass2Option#");
358 UsageError(" Used to specify a pass specific option. The setting itself must be integer.");
359 UsageError(" Separator used between options is a comma.");
360 UsageError("");
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800361 UsageError(" --swap-file=<file-name>: specifies a file to use for swap.");
362 UsageError(" Example: --swap-file=/data/tmp/swap.001");
363 UsageError("");
364 UsageError(" --swap-fd=<file-descriptor>: specifies a file to use for swap (by descriptor).");
365 UsageError(" Example: --swap-fd=10");
366 UsageError("");
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700367 UsageError(" --app-image-fd=<file-descriptor>: specify output file descriptor for app image.");
368 UsageError(" Example: --app-image-fd=10");
369 UsageError("");
370 UsageError(" --app-image-file=<file-name>: specify a file name for app image.");
371 UsageError(" Example: --app-image-file=/data/dalvik-cache/system@app@Calculator.apk.art");
372 UsageError("");
Jeff Haodcdc85b2015-12-04 14:06:18 -0800373 UsageError(" --multi-image: specify that separate oat and image files be generated for each "
374 "input dex file.");
375 UsageError("");
Roland Levillaineb2c7412016-01-28 14:37:01 +0000376 UsageError(" --force-determinism: force the compiler to emit a deterministic output.");
377 UsageError(" This option is incompatible with read barriers (e.g., if dex2oat has been");
378 UsageError(" built with the environment variable `ART_USE_READ_BARRIER` set to `true`).");
379 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700380 std::cerr << "See log for usage error information\n";
381 exit(EXIT_FAILURE);
382}
383
Brian Carlstrom7940e442013-07-12 13:46:57 -0700384// The primary goal of the watchdog is to prevent stuck build servers
385// during development when fatal aborts lead to a cascade of failures
386// that result in a deadlock.
387class WatchDog {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800388// WatchDog defines its own CHECK_PTHREAD_CALL to avoid using LOG which uses locks
Brian Carlstrom7940e442013-07-12 13:46:57 -0700389#undef CHECK_PTHREAD_CALL
390#define CHECK_WATCH_DOG_PTHREAD_CALL(call, args, what) \
391 do { \
392 int rc = call args; \
393 if (rc != 0) { \
394 errno = rc; \
395 std::string message(# call); \
396 message += " failed for "; \
397 message += reason; \
398 Fatal(message); \
399 } \
400 } while (false)
401
402 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -0700403 explicit WatchDog(bool is_watch_dog_enabled) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700404 is_watch_dog_enabled_ = is_watch_dog_enabled;
405 if (!is_watch_dog_enabled_) {
406 return;
407 }
408 shutting_down_ = false;
409 const char* reason = "dex2oat watch dog thread startup";
Kenny Root51316382014-05-13 14:59:37 -0700410 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_init, (&mutex_, nullptr), reason);
411 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_init, (&cond_, nullptr), reason);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700412 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_init, (&attr_), reason);
413 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_create, (&pthread_, &attr_, &CallBack, this), reason);
414 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_destroy, (&attr_), reason);
415 }
416 ~WatchDog() {
417 if (!is_watch_dog_enabled_) {
418 return;
419 }
420 const char* reason = "dex2oat watch dog thread shutdown";
421 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
422 shutting_down_ = true;
423 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_signal, (&cond_), reason);
424 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
425
Kenny Root51316382014-05-13 14:59:37 -0700426 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_join, (pthread_, nullptr), reason);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700427
428 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_destroy, (&cond_), reason);
429 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_destroy, (&mutex_), reason);
430 }
431
432 private:
433 static void* CallBack(void* arg) {
434 WatchDog* self = reinterpret_cast<WatchDog*>(arg);
435 ::art::SetThreadName("dex2oat watch dog");
436 self->Wait();
Kenny Root51316382014-05-13 14:59:37 -0700437 return nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700438 }
439
Andreas Gampe794ad762015-02-23 08:12:24 -0800440 NO_RETURN static void Fatal(const std::string& message) {
Andreas Gamped687e372015-04-28 23:16:03 -0700441 // TODO: When we can guarantee it won't prevent shutdown in error cases, move to LOG. However,
442 // it's rather easy to hang in unwinding.
443 // LogLine also avoids ART logging lock issues, as it's really only a wrapper around
444 // logcat logging or stderr output.
445 LogMessage::LogLine(__FILE__, __LINE__, LogSeverity::FATAL, message.c_str());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700446 exit(1);
447 }
448
449 void Wait() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700450 // TODO: tune the multiplier for GC verification, the following is just to make the timeout
451 // large.
Andreas Gamped687e372015-04-28 23:16:03 -0700452 constexpr int64_t multiplier = kVerifyObjectSupport > kVerifyObjectModeFast ? 100 : 1;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700453 timespec timeout_ts;
454 InitTimeSpec(true, CLOCK_REALTIME, multiplier * kWatchDogTimeoutSeconds * 1000, 0, &timeout_ts);
455 const char* reason = "dex2oat watch dog thread waiting";
456 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
457 while (!shutting_down_) {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800458 int rc = TEMP_FAILURE_RETRY(pthread_cond_timedwait(&cond_, &mutex_, &timeout_ts));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700459 if (rc == ETIMEDOUT) {
Andreas Gamped687e372015-04-28 23:16:03 -0700460 Fatal(StringPrintf("dex2oat did not finish after %" PRId64 " seconds",
461 kWatchDogTimeoutSeconds));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700462 } else if (rc != 0) {
463 std::string message(StringPrintf("pthread_cond_timedwait failed: %s",
464 strerror(errno)));
465 Fatal(message.c_str());
466 }
467 }
468 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
469 }
470
471 // 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 -0700472 // Debug builds are slower so they have larger timeouts.
Andreas Gamped687e372015-04-28 23:16:03 -0700473 static constexpr int64_t kSlowdownFactor = kIsDebugBuild ? 5U : 1U;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800474
Andreas Gampe540138a2015-09-14 15:34:38 -0700475 // 9.5 minutes scaled by kSlowdownFactor. This is slightly smaller than the Package Manager
476 // watchdog (PackageManagerService.WATCHDOG_TIMEOUT, 10 minutes), so that dex2oat will abort
477 // itself before that watchdog would take down the system server.
478 static constexpr int64_t kWatchDogTimeoutSeconds = kSlowdownFactor * (9 * 60 + 30);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700479
480 bool is_watch_dog_enabled_;
481 bool shutting_down_;
482 // TODO: Switch to Mutex when we can guarantee it won't prevent shutdown in error cases.
483 pthread_mutex_t mutex_;
484 pthread_cond_t cond_;
485 pthread_attr_t attr_;
486 pthread_t pthread_;
487};
Brian Carlstrom7940e442013-07-12 13:46:57 -0700488
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800489static constexpr size_t kMinDexFilesForSwap = 2;
490static constexpr size_t kMinDexFileCumulativeSizeForSwap = 20 * MB;
491
492static bool UseSwap(bool is_image, std::vector<const DexFile*>& dex_files) {
493 if (is_image) {
494 // Don't use swap, we know generation should succeed, and we don't want to slow it down.
495 return false;
496 }
497 if (dex_files.size() < kMinDexFilesForSwap) {
498 // If there are less dex files than the threshold, assume it's gonna be fine.
499 return false;
500 }
501 size_t dex_files_size = 0;
502 for (const auto* dex_file : dex_files) {
503 dex_files_size += dex_file->GetHeader().file_size_;
504 }
505 return dex_files_size >= kMinDexFileCumulativeSizeForSwap;
506}
507
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800508class Dex2Oat FINAL {
509 public:
510 explicit Dex2Oat(TimingLogger* timings) :
Nicolas Geoffray409e8092015-10-01 10:32:19 +0100511 compiler_kind_(Compiler::kOptimizing),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800512 instruction_set_(kRuntimeISA),
513 // Take the default set of instruction features from the build.
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000514 image_file_location_oat_checksum_(0),
515 image_file_location_oat_data_begin_(0),
516 image_patch_delta_(0),
517 key_value_store_(nullptr),
Andreas Gampe3f30e122015-09-17 14:03:21 -0700518 verification_results_(nullptr),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800519 method_inliner_map_(),
520 runtime_(nullptr),
521 thread_count_(sysconf(_SC_NPROCESSORS_CONF)),
522 start_ns_(NanoTime()),
523 oat_fd_(-1),
524 zip_fd_(-1),
525 image_base_(0U),
526 image_classes_zip_filename_(nullptr),
527 image_classes_filename_(nullptr),
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800528 image_storage_mode_(ImageHeader::kStorageModeUncompressed),
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800529 compiled_classes_zip_filename_(nullptr),
530 compiled_classes_filename_(nullptr),
Andreas Gampe70bef0d2015-04-15 02:37:28 -0700531 compiled_methods_zip_filename_(nullptr),
532 compiled_methods_filename_(nullptr),
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700533 app_image_(false),
534 boot_image_(false),
Jeff Hao436183f2016-01-12 16:36:50 -0800535 multi_image_(false),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800536 is_host_(false),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000537 class_loader_(nullptr),
538 elf_writers_(),
539 oat_writers_(),
540 rodata_(),
Vladimir Marko10c13562015-11-25 14:33:36 +0000541 image_writer_(nullptr),
Andreas Gampe3f30e122015-09-17 14:03:21 -0700542 driver_(nullptr),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000543 opened_dex_files_maps_(),
544 opened_dex_files_(),
Vladimir Marko47496c22016-01-27 16:15:08 +0000545 no_inline_from_dex_files_(),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800546 dump_stats_(false),
547 dump_passes_(false),
548 dump_timing_(false),
549 dump_slow_timing_(kIsDebugBuild),
Calin Juravle2e2db782016-02-23 12:00:03 +0000550 swap_fd_(kInvalidFd),
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800551 app_image_fd_(kInvalidFd),
Calin Juravle2e2db782016-02-23 12:00:03 +0000552 profile_file_fd_(kInvalidFd),
Andreas Gampeace0dc12016-01-20 13:33:13 -0800553 timings_(timings),
Calin Juravle2e2db782016-02-23 12:00:03 +0000554 force_determinism_(false)
555 {}
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800556
557 ~Dex2Oat() {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800558 // Log completion time before deleting the runtime_, because this accesses
559 // the runtime.
560 LogCompletionTime();
561
Vladimir Marko307dac92015-10-20 11:20:09 +0100562 if (!kIsDebugBuild && !(RUNNING_ON_MEMORY_TOOL && kMemoryToolDetectsLeaks)) {
563 // We want to just exit on non-debug builds, not bringing the runtime down
564 // in an orderly fashion. So release the following fields.
565 driver_.release();
566 image_writer_.release();
567 for (std::unique_ptr<const DexFile>& dex_file : opened_dex_files_) {
568 dex_file.release();
569 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000570 for (std::unique_ptr<MemMap>& map : opened_dex_files_maps_) {
571 map.release();
572 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800573 for (std::unique_ptr<File>& oat_file : oat_files_) {
574 oat_file.release();
575 }
Vladimir Marko307dac92015-10-20 11:20:09 +0100576 runtime_.release();
577 verification_results_.release();
578 key_value_store_.release();
Vladimir Markof94b7812014-06-05 15:48:04 +0100579 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700580 }
581
Roland Levillain9ec5e222015-08-17 20:18:41 +0100582 struct ParserOptions {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800583 std::vector<const char*> oat_symbols;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800584 std::string boot_image_filename;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800585 bool watch_dog_enabled = true;
Nicolas Geoffray1412dfa2015-03-20 14:48:13 +0000586 bool requested_specific_compiler = false;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800587 std::string error_msg;
Roland Levillain9ec5e222015-08-17 20:18:41 +0100588 };
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800589
Roland Levillain9ec5e222015-08-17 20:18:41 +0100590 void ParseZipFd(const StringPiece& option) {
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000591 ParseUintOption(option, "--zip-fd", &zip_fd_, Usage);
Roland Levillain9ec5e222015-08-17 20:18:41 +0100592 }
593
594 void ParseOatFd(const StringPiece& option) {
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000595 ParseUintOption(option, "--oat-fd", &oat_fd_, Usage);
Roland Levillain9ec5e222015-08-17 20:18:41 +0100596 }
597
Calin Juravle877fd962016-01-05 14:29:29 +0000598 void ParseFdForCollection(const StringPiece& option,
599 const char* arg_name,
600 std::vector<uint32_t>* fds) {
601 uint32_t fd;
602 ParseUintOption(option, arg_name, &fd, Usage);
603 fds->push_back(fd);
604 }
605
Roland Levillain9ec5e222015-08-17 20:18:41 +0100606 void ParseJ(const StringPiece& option) {
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000607 ParseUintOption(option, "-j", &thread_count_, Usage, /* is_long_option */ false);
Roland Levillain9ec5e222015-08-17 20:18:41 +0100608 }
609
610 void ParseBase(const StringPiece& option) {
611 DCHECK(option.starts_with("--base="));
612 const char* image_base_str = option.substr(strlen("--base=")).data();
613 char* end;
614 image_base_ = strtoul(image_base_str, &end, 16);
615 if (end == image_base_str || *end != '\0') {
616 Usage("Failed to parse hexadecimal value for option %s", option.data());
617 }
618 }
619
620 void ParseInstructionSet(const StringPiece& option) {
621 DCHECK(option.starts_with("--instruction-set="));
622 StringPiece instruction_set_str = option.substr(strlen("--instruction-set=")).data();
623 // StringPiece is not necessarily zero-terminated, so need to make a copy and ensure it.
624 std::unique_ptr<char[]> buf(new char[instruction_set_str.length() + 1]);
625 strncpy(buf.get(), instruction_set_str.data(), instruction_set_str.length());
626 buf.get()[instruction_set_str.length()] = 0;
627 instruction_set_ = GetInstructionSetFromString(buf.get());
628 // arm actually means thumb2.
629 if (instruction_set_ == InstructionSet::kArm) {
630 instruction_set_ = InstructionSet::kThumb2;
631 }
632 }
633
634 void ParseInstructionSetVariant(const StringPiece& option, ParserOptions* parser_options) {
635 DCHECK(option.starts_with("--instruction-set-variant="));
636 StringPiece str = option.substr(strlen("--instruction-set-variant=")).data();
637 instruction_set_features_.reset(
638 InstructionSetFeatures::FromVariant(
639 instruction_set_, str.as_string(), &parser_options->error_msg));
640 if (instruction_set_features_.get() == nullptr) {
641 Usage("%s", parser_options->error_msg.c_str());
642 }
643 }
644
645 void ParseInstructionSetFeatures(const StringPiece& option, ParserOptions* parser_options) {
646 DCHECK(option.starts_with("--instruction-set-features="));
647 StringPiece str = option.substr(strlen("--instruction-set-features=")).data();
648 if (instruction_set_features_.get() == nullptr) {
649 instruction_set_features_.reset(
650 InstructionSetFeatures::FromVariant(
651 instruction_set_, "default", &parser_options->error_msg));
652 if (instruction_set_features_.get() == nullptr) {
653 Usage("Problem initializing default instruction set features variant: %s",
654 parser_options->error_msg.c_str());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700655 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800656 }
Roland Levillain9ec5e222015-08-17 20:18:41 +0100657 instruction_set_features_.reset(
658 instruction_set_features_->AddFeaturesFromString(str.as_string(),
659 &parser_options->error_msg));
660 if (instruction_set_features_.get() == nullptr) {
661 Usage("Error parsing '%s': %s", option.data(), parser_options->error_msg.c_str());
662 }
663 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800664
Roland Levillain9ec5e222015-08-17 20:18:41 +0100665 void ParseCompilerBackend(const StringPiece& option, ParserOptions* parser_options) {
666 DCHECK(option.starts_with("--compiler-backend="));
667 parser_options->requested_specific_compiler = true;
668 StringPiece backend_str = option.substr(strlen("--compiler-backend=")).data();
669 if (backend_str == "Quick") {
670 compiler_kind_ = Compiler::kQuick;
671 } else if (backend_str == "Optimizing") {
672 compiler_kind_ = Compiler::kOptimizing;
673 } else {
674 Usage("Unknown compiler backend: %s", backend_str.data());
675 }
676 }
677
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800678 void ParseImageFormat(const StringPiece& option) {
679 const StringPiece substr("--image-format=");
680 DCHECK(option.starts_with(substr));
681 const StringPiece format_str = option.substr(substr.length());
682 if (format_str == "lz4") {
683 image_storage_mode_ = ImageHeader::kStorageModeLZ4;
684 } 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
Jeff Haodcdc85b2015-12-04 14:06:18 -0800699 if (oat_filenames_.empty() && oat_fd_ == -1) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800700 Usage("Output must be supplied with either --oat-file or --oat-fd");
701 }
702
Jeff Haodcdc85b2015-12-04 14:06:18 -0800703 if (!oat_filenames_.empty() && oat_fd_ != -1) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800704 Usage("--oat-file should not be used with --oat-fd");
705 }
706
Roland Levillain9ec5e222015-08-17 20:18:41 +0100707 if (!parser_options->oat_symbols.empty() && oat_fd_ != -1) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800708 Usage("--oat-symbols should not be used with --oat-fd");
709 }
710
Roland Levillain9ec5e222015-08-17 20:18:41 +0100711 if (!parser_options->oat_symbols.empty() && is_host_) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800712 Usage("--oat-symbols should not be used with --host");
713 }
714
Jeff Haodcdc85b2015-12-04 14:06:18 -0800715 if (oat_fd_ != -1 && !image_filenames_.empty()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800716 Usage("--oat-fd should not be used with --image");
717 }
718
Jeff Haodcdc85b2015-12-04 14:06:18 -0800719 if (!parser_options->oat_symbols.empty() &&
720 parser_options->oat_symbols.size() != oat_filenames_.size()) {
721 Usage("--oat-file arguments do not match --oat-symbols arguments");
722 }
723
724 if (!image_filenames_.empty() && image_filenames_.size() != oat_filenames_.size()) {
725 Usage("--oat-file arguments do not match --image arguments");
726 }
727
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800728 if (android_root_.empty()) {
729 const char* android_root_env_var = getenv("ANDROID_ROOT");
730 if (android_root_env_var == nullptr) {
731 Usage("--android-root unspecified and ANDROID_ROOT not set");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700732 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800733 android_root_ += android_root_env_var;
734 }
735
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700736 if (!boot_image_ && parser_options->boot_image_filename.empty()) {
Roland Levillain9ec5e222015-08-17 20:18:41 +0100737 parser_options->boot_image_filename += android_root_;
738 parser_options->boot_image_filename += "/framework/boot.art";
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800739 }
Roland Levillain9ec5e222015-08-17 20:18:41 +0100740 if (!parser_options->boot_image_filename.empty()) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000741 boot_image_filename_ = parser_options->boot_image_filename;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800742 }
743
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700744 if (image_classes_filename_ != nullptr && !IsBootImage()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800745 Usage("--image-classes should only be used with --image");
746 }
747
Vladimir Marko49b0f452015-12-10 13:49:19 +0000748 if (image_classes_filename_ != nullptr && !boot_image_filename_.empty()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800749 Usage("--image-classes should not be used with --boot-image");
750 }
751
752 if (image_classes_zip_filename_ != nullptr && image_classes_filename_ == nullptr) {
753 Usage("--image-classes-zip should be used with --image-classes");
754 }
755
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700756 if (compiled_classes_filename_ != nullptr && !IsBootImage()) {
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800757 Usage("--compiled-classes should only be used with --image");
758 }
759
Vladimir Marko49b0f452015-12-10 13:49:19 +0000760 if (compiled_classes_filename_ != nullptr && !boot_image_filename_.empty()) {
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800761 Usage("--compiled-classes should not be used with --boot-image");
762 }
763
764 if (compiled_classes_zip_filename_ != nullptr && compiled_classes_filename_ == nullptr) {
765 Usage("--compiled-classes-zip should be used with --compiled-classes");
766 }
767
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800768 if (dex_filenames_.empty() && zip_fd_ == -1) {
769 Usage("Input must be supplied with either --dex-file or --zip-fd");
770 }
771
772 if (!dex_filenames_.empty() && zip_fd_ != -1) {
773 Usage("--dex-file should not be used with --zip-fd");
774 }
775
776 if (!dex_filenames_.empty() && !zip_location_.empty()) {
777 Usage("--dex-file should not be used with --zip-location");
778 }
779
780 if (dex_locations_.empty()) {
781 for (const char* dex_file_name : dex_filenames_) {
782 dex_locations_.push_back(dex_file_name);
783 }
784 } else if (dex_locations_.size() != dex_filenames_.size()) {
785 Usage("--dex-location arguments do not match --dex-file arguments");
786 }
787
Jeff Haodcdc85b2015-12-04 14:06:18 -0800788 if (!dex_filenames_.empty() && !oat_filenames_.empty()) {
789 if (oat_filenames_.size() != 1 && oat_filenames_.size() != dex_filenames_.size()) {
790 Usage("--oat-file arguments must be singular or match --dex-file arguments");
791 }
792 }
793
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800794 if (zip_fd_ != -1 && zip_location_.empty()) {
795 Usage("--zip-location should be supplied with --zip-fd");
796 }
797
Vladimir Marko49b0f452015-12-10 13:49:19 +0000798 if (boot_image_filename_.empty()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800799 if (image_base_ == 0) {
800 Usage("Non-zero --base not specified");
801 }
802 }
803
Calin Juravle2e2db782016-02-23 12:00:03 +0000804 if (!profile_file_.empty() && (profile_file_fd_ != kInvalidFd)) {
805 Usage("Profile file should not be specified with both --profile-file-fd and --profile-file");
Calin Juravle998c2162015-12-21 15:39:33 +0200806 }
807
Roland Levillain9ec5e222015-08-17 20:18:41 +0100808 if (!parser_options->oat_symbols.empty()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800809 oat_unstripped_ = std::move(parser_options->oat_symbols);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800810 }
811
812 // If no instruction set feature was given, use the default one for the target
813 // instruction set.
814 if (instruction_set_features_.get() == nullptr) {
815 instruction_set_features_.reset(
Roland Levillain9ec5e222015-08-17 20:18:41 +0100816 InstructionSetFeatures::FromVariant(
817 instruction_set_, "default", &parser_options->error_msg));
Ian Rogersd582fa42014-11-05 23:46:43 -0800818 if (instruction_set_features_.get() == nullptr) {
819 Usage("Problem initializing default instruction set features variant: %s",
Roland Levillain9ec5e222015-08-17 20:18:41 +0100820 parser_options->error_msg.c_str());
Ian Rogersd582fa42014-11-05 23:46:43 -0800821 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800822 }
823
824 if (instruction_set_ == kRuntimeISA) {
825 std::unique_ptr<const InstructionSetFeatures> runtime_features(
826 InstructionSetFeatures::FromCppDefines());
827 if (!instruction_set_features_->Equals(runtime_features.get())) {
828 LOG(WARNING) << "Mismatch between dex2oat instruction set features ("
829 << *instruction_set_features_ << ") and those of dex2oat executable ("
830 << *runtime_features <<") for the command line:\n"
831 << CommandLine();
832 }
833 }
834
Roland Levillaina215b952015-08-07 11:38:32 +0100835 // It they are not set, use default values for inlining settings.
836 // TODO: We should rethink the compiler filter. We mostly save
837 // time here, which is orthogonal to space.
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000838 if (compiler_options_->inline_depth_limit_ == CompilerOptions::kUnsetInlineDepthLimit) {
839 compiler_options_->inline_depth_limit_ =
840 (compiler_options_->compiler_filter_ == CompilerOptions::kSpace)
Roland Levillaina215b952015-08-07 11:38:32 +0100841 // Implementation of the space filter: limit inlining depth.
842 ? CompilerOptions::kSpaceFilterInlineDepthLimit
843 : CompilerOptions::kDefaultInlineDepthLimit;
844 }
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000845 if (compiler_options_->inline_max_code_units_ == CompilerOptions::kUnsetInlineMaxCodeUnits) {
846 compiler_options_->inline_max_code_units_ =
847 (compiler_options_->compiler_filter_ == CompilerOptions::kSpace)
Roland Levillaina215b952015-08-07 11:38:32 +0100848 // Implementation of the space filter: limit inlining max code units.
849 ? CompilerOptions::kSpaceFilterInlineMaxCodeUnits
850 : CompilerOptions::kDefaultInlineMaxCodeUnits;
851 }
852
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800853 // Checks are all explicit until we know the architecture.
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800854 // Set the compilation target's implicit checks options.
855 switch (instruction_set_) {
856 case kArm:
857 case kThumb2:
858 case kArm64:
859 case kX86:
860 case kX86_64:
Douglas Leung22bb5a22015-07-02 16:42:08 -0700861 case kMips:
862 case kMips64:
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000863 compiler_options_->implicit_null_checks_ = true;
864 compiler_options_->implicit_so_checks_ = true;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800865 break;
866
867 default:
868 // Defaults are correct.
869 break;
870 }
871
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000872 compiler_options_->verbose_methods_ = verbose_methods_.empty() ? nullptr : &verbose_methods_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800873
Jeff Hao436183f2016-01-12 16:36:50 -0800874 if (!IsBootImage() && multi_image_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800875 Usage("--multi-image can only be used when creating boot images");
876 }
Jeff Hao436183f2016-01-12 16:36:50 -0800877 if (IsBootImage() && multi_image_ && image_filenames_.size() > 1) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800878 Usage("--multi-image cannot be used with multiple image names");
879 }
880
881 // For now, if we're on the host and compile the boot image, *always* use multiple image files.
882 if (!kIsTargetBuild && IsBootImage()) {
883 if (image_filenames_.size() == 1) {
Jeff Hao436183f2016-01-12 16:36:50 -0800884 multi_image_ = true;
Jeff Haodcdc85b2015-12-04 14:06:18 -0800885 }
886 }
887
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800888 // Done with usage checks, enable watchdog if requested
Roland Levillain9ec5e222015-08-17 20:18:41 +0100889 if (parser_options->watch_dog_enabled) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800890 watchdog_.reset(new WatchDog(true));
891 }
892
893 // Fill some values into the key-value store for the oat header.
894 key_value_store_.reset(new SafeMap<std::string, std::string>());
Andreas Gampeace0dc12016-01-20 13:33:13 -0800895
Hiroshi Yamauchi6af53482016-01-29 15:38:58 -0800896 // Automatically force determinism for the boot image in a host build if the default GC is CMS
897 // or MS and read barriers are not enabled, as the former switches the GC to a non-concurrent
898 // one by passing the option `-Xgc:nonconcurrent` (see below).
899 if (!kIsTargetBuild && IsBootImage()) {
900 if (SupportsDeterministicCompilation()) {
901 force_determinism_ = true;
902 } else {
903 LOG(WARNING) << "Deterministic compilation is disabled.";
904 }
Andreas Gampeace0dc12016-01-20 13:33:13 -0800905 }
906 compiler_options_->force_determinism_ = force_determinism_;
Roland Levillain9ec5e222015-08-17 20:18:41 +0100907 }
908
Hiroshi Yamauchi6af53482016-01-29 15:38:58 -0800909 static bool SupportsDeterministicCompilation() {
910 return (gc::kCollectorTypeDefault == gc::kCollectorTypeCMS ||
911 gc::kCollectorTypeDefault == gc::kCollectorTypeMS) &&
912 !kEmitCompilerReadBarrier;
913 }
914
Jeff Hao436183f2016-01-12 16:36:50 -0800915 void ExpandOatAndImageFilenames() {
916 std::string base_oat = oat_filenames_[0];
917 size_t last_oat_slash = base_oat.rfind('/');
918 if (last_oat_slash == std::string::npos) {
919 Usage("--multi-image used with unusable oat filename %s", base_oat.c_str());
920 }
921 // We also need to honor path components that were encoded through '@'. Otherwise the loading
922 // code won't be able to find the images.
923 if (base_oat.find('@', last_oat_slash) != std::string::npos) {
924 last_oat_slash = base_oat.rfind('@');
925 }
926 base_oat = base_oat.substr(0, last_oat_slash + 1);
927
928 std::string base_img = image_filenames_[0];
929 size_t last_img_slash = base_img.rfind('/');
930 if (last_img_slash == std::string::npos) {
931 Usage("--multi-image used with unusable image filename %s", base_img.c_str());
932 }
933 // We also need to honor path components that were encoded through '@'. Otherwise the loading
934 // code won't be able to find the images.
935 if (base_img.find('@', last_img_slash) != std::string::npos) {
936 last_img_slash = base_img.rfind('@');
937 }
938
939 // Get the prefix, which is the primary image name (without path components). Strip the
940 // extension.
941 std::string prefix = base_img.substr(last_img_slash + 1);
942 if (prefix.rfind('.') != std::string::npos) {
943 prefix = prefix.substr(0, prefix.rfind('.'));
944 }
945 if (!prefix.empty()) {
946 prefix = prefix + "-";
947 }
948
949 base_img = base_img.substr(0, last_img_slash + 1);
950
951 // Note: we have some special case here for our testing. We have to inject the differentiating
952 // parts for the different core images.
953 std::string infix; // Empty infix by default.
954 {
955 // Check the first name.
956 std::string dex_file = oat_filenames_[0];
957 size_t last_dex_slash = dex_file.rfind('/');
958 if (last_dex_slash != std::string::npos) {
959 dex_file = dex_file.substr(last_dex_slash + 1);
960 }
961 size_t last_dex_dot = dex_file.rfind('.');
962 if (last_dex_dot != std::string::npos) {
963 dex_file = dex_file.substr(0, last_dex_dot);
964 }
965 if (StartsWith(dex_file, "core-")) {
966 infix = dex_file.substr(strlen("core"));
967 }
968 }
969
970 // Now create the other names. Use a counted loop to skip the first one.
971 for (size_t i = 1; i < dex_locations_.size(); ++i) {
972 // TODO: Make everything properly std::string.
973 std::string image_name = CreateMultiImageName(dex_locations_[i], prefix, infix, ".art");
974 char_backing_storage_.push_back(base_img + image_name);
975 image_filenames_.push_back((char_backing_storage_.end() - 1)->c_str());
976
977 std::string oat_name = CreateMultiImageName(dex_locations_[i], prefix, infix, ".oat");
978 char_backing_storage_.push_back(base_oat + oat_name);
979 oat_filenames_.push_back((char_backing_storage_.end() - 1)->c_str());
980 }
981 }
982
Andreas Gampe8994a042015-12-30 19:03:17 +0000983 // Modify the input string in the following way:
984 // 0) Assume input is /a/b/c.d
985 // 1) Strip the path -> c.d
986 // 2) Inject prefix p -> pc.d
987 // 3) Inject infix i -> pci.d
988 // 4) Replace suffix with s if it's "jar" -> d == "jar" -> pci.s
Jeff Haodcdc85b2015-12-04 14:06:18 -0800989 static std::string CreateMultiImageName(std::string in,
Andreas Gampe8994a042015-12-30 19:03:17 +0000990 const std::string& prefix,
Jeff Haodcdc85b2015-12-04 14:06:18 -0800991 const std::string& infix,
Andreas Gampe8994a042015-12-30 19:03:17 +0000992 const char* replace_suffix) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800993 size_t last_dex_slash = in.rfind('/');
994 if (last_dex_slash != std::string::npos) {
995 in = in.substr(last_dex_slash + 1);
996 }
Andreas Gampe8994a042015-12-30 19:03:17 +0000997 if (!prefix.empty()) {
998 in = prefix + in;
999 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001000 if (!infix.empty()) {
1001 // Inject infix.
1002 size_t last_dot = in.rfind('.');
1003 if (last_dot != std::string::npos) {
1004 in.insert(last_dot, infix);
1005 }
1006 }
1007 if (EndsWith(in, ".jar")) {
Andreas Gampe8994a042015-12-30 19:03:17 +00001008 in = in.substr(0, in.length() - strlen(".jar")) +
1009 (replace_suffix != nullptr ? replace_suffix : "");
Jeff Haodcdc85b2015-12-04 14:06:18 -08001010 }
1011 return in;
1012 }
1013
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001014 void InsertCompileOptions(int argc, char** argv) {
Roland Levillain9ec5e222015-08-17 20:18:41 +01001015 std::ostringstream oss;
1016 for (int i = 0; i < argc; ++i) {
1017 if (i > 0) {
1018 oss << ' ';
1019 }
1020 oss << argv[i];
1021 }
1022 key_value_store_->Put(OatHeader::kDex2OatCmdLineKey, oss.str());
1023 oss.str(""); // Reset.
1024 oss << kRuntimeISA;
1025 key_value_store_->Put(OatHeader::kDex2OatHostKey, oss.str());
1026 key_value_store_->Put(
1027 OatHeader::kPicKey,
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001028 compiler_options_->compile_pic_ ? OatHeader::kTrueValue : OatHeader::kFalseValue);
Roland Levillain9ec5e222015-08-17 20:18:41 +01001029 key_value_store_->Put(
1030 OatHeader::kDebuggableKey,
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001031 compiler_options_->debuggable_ ? OatHeader::kTrueValue : OatHeader::kFalseValue);
David Brazdilce4b0ba2016-01-28 15:05:49 +00001032 key_value_store_->Put(
1033 OatHeader::kExtractOnlyKey,
1034 compiler_options_->IsExtractOnly() ? OatHeader::kTrueValue : OatHeader::kFalseValue);
Roland Levillain9ec5e222015-08-17 20:18:41 +01001035 }
1036
1037 // Parse the arguments from the command line. In case of an unrecognized option or impossible
1038 // values/combinations, a usage error will be displayed and exit() is called. Thus, if the method
1039 // returns, arguments have been successfully parsed.
1040 void ParseArgs(int argc, char** argv) {
1041 original_argc = argc;
1042 original_argv = argv;
1043
1044 InitLogging(argv);
1045
1046 // Skip over argv[0].
1047 argv++;
1048 argc--;
1049
1050 if (argc == 0) {
1051 Usage("No arguments specified");
1052 }
1053
1054 std::unique_ptr<ParserOptions> parser_options(new ParserOptions());
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001055 compiler_options_.reset(new CompilerOptions());
Roland Levillain9ec5e222015-08-17 20:18:41 +01001056
1057 for (int i = 0; i < argc; i++) {
1058 const StringPiece option(argv[i]);
1059 const bool log_options = false;
1060 if (log_options) {
1061 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
1062 }
1063 if (option.starts_with("--dex-file=")) {
1064 dex_filenames_.push_back(option.substr(strlen("--dex-file=")).data());
1065 } else if (option.starts_with("--dex-location=")) {
1066 dex_locations_.push_back(option.substr(strlen("--dex-location=")).data());
1067 } else if (option.starts_with("--zip-fd=")) {
1068 ParseZipFd(option);
1069 } else if (option.starts_with("--zip-location=")) {
1070 zip_location_ = option.substr(strlen("--zip-location=")).data();
1071 } else if (option.starts_with("--oat-file=")) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001072 oat_filenames_.push_back(option.substr(strlen("--oat-file=")).data());
Roland Levillain9ec5e222015-08-17 20:18:41 +01001073 } else if (option.starts_with("--oat-symbols=")) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001074 parser_options->oat_symbols.push_back(option.substr(strlen("--oat-symbols=")).data());
Roland Levillain9ec5e222015-08-17 20:18:41 +01001075 } else if (option.starts_with("--oat-fd=")) {
1076 ParseOatFd(option);
1077 } else if (option == "--watch-dog") {
1078 parser_options->watch_dog_enabled = true;
1079 } else if (option == "--no-watch-dog") {
1080 parser_options->watch_dog_enabled = false;
1081 } else if (option.starts_with("-j")) {
1082 ParseJ(option);
1083 } else if (option.starts_with("--oat-location=")) {
1084 oat_location_ = option.substr(strlen("--oat-location=")).data();
1085 } else if (option.starts_with("--image=")) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001086 image_filenames_.push_back(option.substr(strlen("--image=")).data());
Roland Levillain9ec5e222015-08-17 20:18:41 +01001087 } else if (option.starts_with("--image-classes=")) {
1088 image_classes_filename_ = option.substr(strlen("--image-classes=")).data();
1089 } else if (option.starts_with("--image-classes-zip=")) {
1090 image_classes_zip_filename_ = option.substr(strlen("--image-classes-zip=")).data();
Mathieu Chartierceb07b32015-12-10 09:33:21 -08001091 } else if (option.starts_with("--image-format=")) {
1092 ParseImageFormat(option);
Roland Levillain9ec5e222015-08-17 20:18:41 +01001093 } else if (option.starts_with("--compiled-classes=")) {
1094 compiled_classes_filename_ = option.substr(strlen("--compiled-classes=")).data();
1095 } else if (option.starts_with("--compiled-classes-zip=")) {
1096 compiled_classes_zip_filename_ = option.substr(strlen("--compiled-classes-zip=")).data();
1097 } else if (option.starts_with("--compiled-methods=")) {
1098 compiled_methods_filename_ = option.substr(strlen("--compiled-methods=")).data();
1099 } else if (option.starts_with("--compiled-methods-zip=")) {
1100 compiled_methods_zip_filename_ = option.substr(strlen("--compiled-methods-zip=")).data();
1101 } else if (option.starts_with("--base=")) {
1102 ParseBase(option);
1103 } else if (option.starts_with("--boot-image=")) {
1104 parser_options->boot_image_filename = option.substr(strlen("--boot-image=")).data();
1105 } else if (option.starts_with("--android-root=")) {
1106 android_root_ = option.substr(strlen("--android-root=")).data();
1107 } else if (option.starts_with("--instruction-set=")) {
1108 ParseInstructionSet(option);
1109 } else if (option.starts_with("--instruction-set-variant=")) {
1110 ParseInstructionSetVariant(option, parser_options.get());
1111 } else if (option.starts_with("--instruction-set-features=")) {
1112 ParseInstructionSetFeatures(option, parser_options.get());
1113 } else if (option.starts_with("--compiler-backend=")) {
1114 ParseCompilerBackend(option, parser_options.get());
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001115 } else if (option.starts_with("--profile-file=")) {
Calin Juravle2e2db782016-02-23 12:00:03 +00001116 profile_file_ = option.substr(strlen("--profile-file=")).ToString();
Calin Juravle877fd962016-01-05 14:29:29 +00001117 } else if (option.starts_with("--profile-file-fd=")) {
Calin Juravle2e2db782016-02-23 12:00:03 +00001118 ParseUintOption(option, "--profile-file-fd", &profile_file_fd_, Usage);
Roland Levillain9ec5e222015-08-17 20:18:41 +01001119 } else if (option == "--host") {
1120 is_host_ = true;
1121 } else if (option == "--runtime-arg") {
1122 if (++i >= argc) {
1123 Usage("Missing required argument for --runtime-arg");
1124 }
1125 if (log_options) {
1126 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
1127 }
1128 runtime_args_.push_back(argv[i]);
1129 } else if (option == "--dump-timing") {
1130 dump_timing_ = true;
1131 } else if (option == "--dump-passes") {
1132 dump_passes_ = true;
Roland Levillain9ec5e222015-08-17 20:18:41 +01001133 } else if (option == "--dump-stats") {
1134 dump_stats_ = true;
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001135 } else if (option.starts_with("--swap-file=")) {
1136 swap_file_name_ = option.substr(strlen("--swap-file=")).data();
1137 } else if (option.starts_with("--swap-fd=")) {
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001138 ParseUintOption(option, "--swap-fd", &swap_fd_, Usage);
1139 } else if (option.starts_with("--app-image-file=")) {
1140 app_image_file_name_ = option.substr(strlen("--app-image-file=")).data();
1141 } else if (option.starts_with("--app-image-fd=")) {
1142 ParseUintOption(option, "--app-image-fd", &app_image_fd_, Usage);
Roland Levillain9ec5e222015-08-17 20:18:41 +01001143 } else if (option.starts_with("--verbose-methods=")) {
1144 // TODO: rather than switch off compiler logging, make all VLOG(compiler) messages
1145 // conditional on having verbost methods.
1146 gLogVerbosity.compiler = false;
1147 Split(option.substr(strlen("--verbose-methods=")).ToString(), ',', &verbose_methods_);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001148 } else if (option == "--multi-image") {
Jeff Hao436183f2016-01-12 16:36:50 -08001149 multi_image_ = true;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001150 } else if (option.starts_with("--no-inline-from=")) {
1151 no_inline_from_string_ = option.substr(strlen("--no-inline-from=")).data();
Andreas Gampeace0dc12016-01-20 13:33:13 -08001152 } else if (option == "--force-determinism") {
Hiroshi Yamauchi6af53482016-01-29 15:38:58 -08001153 if (!SupportsDeterministicCompilation()) {
1154 Usage("Cannot use --force-determinism with read barriers or non-CMS garbage collector");
Roland Levillaineb2c7412016-01-28 14:37:01 +00001155 }
Andreas Gampeace0dc12016-01-20 13:33:13 -08001156 force_determinism_ = true;
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001157 } else if (!compiler_options_->ParseCompilerOption(option, Usage)) {
Roland Levillain9ec5e222015-08-17 20:18:41 +01001158 Usage("Unknown argument %s", option.data());
1159 }
1160 }
1161
Jeff Hao436183f2016-01-12 16:36:50 -08001162 ProcessOptions(parser_options.get());
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001163
1164 // Insert some compiler things.
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001165 InsertCompileOptions(argc, argv);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001166 }
1167
Jeff Haodcdc85b2015-12-04 14:06:18 -08001168 // Check whether the oat output files are writable, and open them for later. Also open a swap
1169 // file, if a name is given.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001170 bool OpenFile() {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001171 // Prune non-existent dex files now so that we don't create empty oat files for multi-image.
1172 PruneNonExistentDexFiles();
1173
Jeff Hao436183f2016-01-12 16:36:50 -08001174 // Expand oat and image filenames for multi image.
1175 if (IsBootImage() && multi_image_) {
1176 ExpandOatAndImageFilenames();
1177 }
1178
Jeff Haodcdc85b2015-12-04 14:06:18 -08001179 bool create_file = oat_fd_ == -1; // as opposed to using open file descriptor
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001180 if (create_file) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001181 for (const char* oat_filename : oat_filenames_) {
1182 std::unique_ptr<File> oat_file(OS::CreateEmptyFile(oat_filename));
1183 if (oat_file.get() == nullptr) {
1184 PLOG(ERROR) << "Failed to create oat file: " << oat_filename;
1185 return false;
1186 }
1187 if (create_file && fchmod(oat_file->Fd(), 0644) != 0) {
1188 PLOG(ERROR) << "Failed to make oat file world readable: " << oat_filename;
1189 oat_file->Erase();
1190 return false;
1191 }
1192 oat_files_.push_back(std::move(oat_file));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001193 }
1194 } else {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001195 std::unique_ptr<File> oat_file(new File(oat_fd_, oat_location_, true));
1196 oat_file->DisableAutoClose();
1197 if (oat_file->SetLength(0) != 0) {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001198 PLOG(WARNING) << "Truncating oat file " << oat_location_ << " failed.";
1199 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001200 if (oat_file.get() == nullptr) {
1201 PLOG(ERROR) << "Failed to create oat file: " << oat_location_;
1202 return false;
1203 }
1204 if (create_file && fchmod(oat_file->Fd(), 0644) != 0) {
1205 PLOG(ERROR) << "Failed to make oat file world readable: " << oat_location_;
1206 oat_file->Erase();
1207 return false;
1208 }
1209 oat_filenames_.push_back(oat_location_.c_str());
1210 oat_files_.push_back(std::move(oat_file));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001211 }
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001212
1213 // Swap file handling.
1214 //
1215 // If the swap fd is not -1, we assume this is the file descriptor of an open but unlinked file
1216 // that we can use for swap.
1217 //
1218 // If the swap fd is -1 and we have a swap-file string, open the given file as a swap file. We
1219 // will immediately unlink to satisfy the swap fd assumption.
1220 if (swap_fd_ == -1 && !swap_file_name_.empty()) {
1221 std::unique_ptr<File> swap_file(OS::CreateEmptyFile(swap_file_name_.c_str()));
1222 if (swap_file.get() == nullptr) {
1223 PLOG(ERROR) << "Failed to create swap file: " << swap_file_name_;
1224 return false;
1225 }
1226 swap_fd_ = swap_file->Fd();
1227 swap_file->MarkUnchecked(); // We don't we to track this, it will be unlinked immediately.
1228 swap_file->DisableAutoClose(); // We'll handle it ourselves, the File object will be
1229 // released immediately.
1230 unlink(swap_file_name_.c_str());
1231 }
Jeff Hao436183f2016-01-12 16:36:50 -08001232
1233 // If we use a swap file, ensure we are above the threshold to make it necessary.
1234 if (swap_fd_ != -1) {
1235 if (!UseSwap(IsBootImage(), dex_files_)) {
1236 close(swap_fd_);
1237 swap_fd_ = -1;
1238 VLOG(compiler) << "Decided to run without swap.";
1239 } else {
1240 LOG(INFO) << "Large app, accepted running with swap.";
1241 }
1242 }
1243 // Note that dex2oat won't close the swap_fd_. The compiler driver's swap space will do that.
1244
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001245 return true;
1246 }
1247
Jeff Haodcdc85b2015-12-04 14:06:18 -08001248 void EraseOatFiles() {
1249 for (size_t i = 0; i < oat_files_.size(); ++i) {
1250 DCHECK(oat_files_[i].get() != nullptr);
1251 oat_files_[i]->Erase();
1252 oat_files_[i].reset();
1253 }
Andreas Gampea650e702014-12-03 14:28:02 -08001254 }
1255
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001256 void Shutdown() {
1257 ScopedObjectAccess soa(Thread::Current());
1258 for (jobject dex_cache : dex_caches_) {
1259 soa.Env()->DeleteLocalRef(dex_cache);
1260 }
1261 dex_caches_.clear();
1262 }
1263
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001264 // Set up the environment for compilation. Includes starting the runtime and loading/opening the
1265 // boot class path.
1266 bool Setup() {
1267 TimingLogger::ScopedTiming t("dex2oat Setup", timings_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001268 art::MemMap::Init(); // For ZipEntry::ExtractToMemMap.
Vladimir Marko49b0f452015-12-10 13:49:19 +00001269
1270 if (!PrepareImageClasses() || !PrepareCompiledClasses() || !PrepareCompiledMethods()) {
1271 return false;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001272 }
Brian Carlstromd76e0832013-08-29 15:17:42 -07001273
Vladimir Marko307dac92015-10-20 11:20:09 +01001274 verification_results_.reset(new VerificationResults(compiler_options_.get()));
Andreas Gampe4585f872015-03-27 23:45:15 -07001275 callbacks_.reset(new QuickCompilerCallbacks(
Vladimir Marko307dac92015-10-20 11:20:09 +01001276 verification_results_.get(),
Andreas Gampe4585f872015-03-27 23:45:15 -07001277 &method_inliner_map_,
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001278 IsBootImage() ?
Andreas Gampe4585f872015-03-27 23:45:15 -07001279 CompilerCallbacks::CallbackMode::kCompileBootImage :
1280 CompilerCallbacks::CallbackMode::kCompileApp));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001281
Vladimir Marko49b0f452015-12-10 13:49:19 +00001282 RuntimeArgumentMap runtime_options;
1283 if (!PrepareRuntimeOptions(&runtime_options)) {
1284 return false;
Andreas Gampe1d00add2015-02-27 19:35:46 -08001285 }
1286
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001287 CreateOatWriters();
1288 if (!AddDexFileSources()) {
1289 return false;
1290 }
1291
1292 if (IsBootImage() && image_filenames_.size() > 1) {
1293 // If we're compiling the boot image, store the boot classpath into the Key-Value store.
1294 // We need this for the multi-image case.
1295 key_value_store_->Put(OatHeader::kBootClassPath, GetMultiImageBootClassPath());
1296 }
1297
1298 if (!IsBootImage()) {
1299 // When compiling an app, create the runtime early to retrieve
1300 // the image location key needed for the oat header.
1301 if (!CreateRuntime(std::move(runtime_options))) {
1302 return false;
1303 }
1304
David Brazdilce4b0ba2016-01-28 15:05:49 +00001305 if (compiler_options_->IsExtractOnly()) {
1306 // ExtractOnly oat files only contain non-quickened DEX code and are
1307 // therefore independent of the image file.
1308 image_file_location_oat_checksum_ = 0u;
1309 image_file_location_oat_data_begin_ = 0u;
1310 image_patch_delta_ = 0;
1311 } else {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001312 TimingLogger::ScopedTiming t3("Loading image checksum", timings_);
1313 std::vector<gc::space::ImageSpace*> image_spaces =
1314 Runtime::Current()->GetHeap()->GetBootImageSpaces();
1315 image_file_location_oat_checksum_ = image_spaces[0]->GetImageHeader().GetOatChecksum();
1316 image_file_location_oat_data_begin_ =
1317 reinterpret_cast<uintptr_t>(image_spaces[0]->GetImageHeader().GetOatDataBegin());
1318 image_patch_delta_ = image_spaces[0]->GetImageHeader().GetPatchDelta();
1319 // Store the boot image filename(s).
1320 std::vector<std::string> image_filenames;
1321 for (const gc::space::ImageSpace* image_space : image_spaces) {
1322 image_filenames.push_back(image_space->GetImageFilename());
1323 }
1324 std::string image_file_location = Join(image_filenames, ':');
1325 if (!image_file_location.empty()) {
1326 key_value_store_->Put(OatHeader::kImageLocationKey, image_file_location);
1327 }
1328 }
1329
1330 // Open dex files for class path.
1331 const std::vector<std::string> class_path_locations =
1332 GetClassPathLocations(runtime_->GetClassPathString());
1333 OpenClassPathFiles(class_path_locations, &class_path_files_);
1334
1335 // Store the classpath we have right now.
1336 std::vector<const DexFile*> class_path_files = MakeNonOwningPointerVector(class_path_files_);
1337 key_value_store_->Put(OatHeader::kClassPathKey,
1338 OatFile::EncodeDexFileDependencies(class_path_files));
1339 }
1340
1341 // Now that we have finalized key_value_store_, start writing the oat file.
Andreas Gampec7ae55d2015-09-15 20:04:54 -07001342 {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001343 TimingLogger::ScopedTiming t_dex("Writing and opening dex files", timings_);
1344 rodata_.reserve(oat_writers_.size());
1345 for (size_t i = 0, size = oat_writers_.size(); i != size; ++i) {
1346 rodata_.push_back(elf_writers_[i]->StartRoData());
1347 // Unzip or copy dex files straight to the oat file.
1348 std::unique_ptr<MemMap> opened_dex_files_map;
1349 std::vector<std::unique_ptr<const DexFile>> opened_dex_files;
1350 if (!oat_writers_[i]->WriteAndOpenDexFiles(rodata_.back(),
1351 oat_files_[i].get(),
1352 instruction_set_,
1353 instruction_set_features_.get(),
1354 key_value_store_.get(),
Andreas Gampe3a2bd292016-01-26 17:23:47 -08001355 /* verify */ true,
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001356 &opened_dex_files_map,
1357 &opened_dex_files)) {
1358 return false;
1359 }
1360 dex_files_per_oat_file_.push_back(MakeNonOwningPointerVector(opened_dex_files));
1361 if (opened_dex_files_map != nullptr) {
1362 opened_dex_files_maps_.push_back(std::move(opened_dex_files_map));
1363 for (std::unique_ptr<const DexFile>& dex_file : opened_dex_files) {
Vladimir Marko944da602016-02-19 12:27:55 +00001364 dex_file_oat_index_map_.emplace(dex_file.get(), i);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001365 opened_dex_files_.push_back(std::move(dex_file));
1366 }
1367 } else {
1368 DCHECK(opened_dex_files.empty());
1369 }
1370 }
1371 }
1372
1373 dex_files_ = MakeNonOwningPointerVector(opened_dex_files_);
1374 if (IsBootImage()) {
1375 // For boot image, pass opened dex files to the Runtime::Create().
1376 // Note: Runtime acquires ownership of these dex files.
1377 runtime_options.Set(RuntimeArgumentMap::BootClassPathDexList, &opened_dex_files_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001378 if (!CreateRuntime(std::move(runtime_options))) {
Andreas Gampec7ae55d2015-09-15 20:04:54 -07001379 return false;
1380 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001381 }
1382
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001383 // If we're doing the image, override the compiler filter to force full compilation. Must be
1384 // done ahead of WellKnownClasses::Init that causes verification. Note: doesn't force
1385 // compilation of class initializers.
1386 // Whilst we're in native take the opportunity to initialize well known classes.
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001387 Thread* self = Thread::Current();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001388 WellKnownClasses::Init(self->GetJniEnv());
1389
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001390 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001391 if (!IsBootImage()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001392 constexpr bool kSaveDexInput = false;
1393 if (kSaveDexInput) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001394 SaveDexInput();
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001395 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001396
1397 // Handle and ClassLoader creation needs to come after Runtime::Create.
1398 ScopedObjectAccess soa(self);
1399
1400 // Classpath: first the class-path given.
1401 std::vector<const DexFile*> class_path_files = MakeNonOwningPointerVector(class_path_files_);
1402
1403 // Then the dex files we'll compile. Thus we'll resolve the class-path first.
1404 class_path_files.insert(class_path_files.end(), dex_files_.begin(), dex_files_.end());
1405
1406 class_loader_ = class_linker->CreatePathClassLoader(self, class_path_files);
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001407 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001408
1409 // Ensure opened dex files are writable for dex-to-dex transformations.
1410 for (const std::unique_ptr<MemMap>& map : opened_dex_files_maps_) {
1411 if (!map->Protect(PROT_READ | PROT_WRITE)) {
1412 PLOG(ERROR) << "Failed to make .dex files writeable.";
1413 return false;
Vladimir Marko919f5532016-01-20 19:13:01 +00001414 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001415 }
1416
1417 // Ensure that the dex caches stay live since we don't want class unloading
1418 // to occur during compilation.
1419 for (const auto& dex_file : dex_files_) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001420 ScopedObjectAccess soa(self);
1421 dex_caches_.push_back(soa.AddLocalReference<jobject>(
Mathieu Chartierd57d4542015-10-14 10:55:30 -07001422 class_linker->RegisterDexFile(*dex_file, Runtime::Current()->GetLinearAlloc())));
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001423 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001424
1425 /*
1426 * If we're not in interpret-only or verify-none mode, go ahead and compile small applications.
1427 * Don't bother to check if we're doing the image.
1428 */
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001429 if (!IsBootImage() &&
Brian Carlstrom95b033b2014-12-03 22:29:37 -08001430 compiler_options_->IsCompilationEnabled() &&
1431 compiler_kind_ == Compiler::kQuick) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001432 size_t num_methods = 0;
1433 for (size_t i = 0; i != dex_files_.size(); ++i) {
1434 const DexFile* dex_file = dex_files_[i];
1435 CHECK(dex_file != nullptr);
1436 num_methods += dex_file->NumMethodIds();
1437 }
1438 if (num_methods <= compiler_options_->GetNumDexMethodsThreshold()) {
1439 compiler_options_->SetCompilerFilter(CompilerOptions::kSpeed);
1440 VLOG(compiler) << "Below method threshold, compiling anyways";
1441 }
1442 }
1443
1444 return true;
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001445 }
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001446
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001447 // If we need to keep the oat file open for the image writer.
1448 bool ShouldKeepOatFileOpen() const {
1449 return IsImage() && oat_fd_ != kInvalidFd;
1450 }
1451
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001452 // Create and invoke the compiler driver. This will compile all the dex files.
1453 void Compile() {
1454 TimingLogger::ScopedTiming t("dex2oat Compile", timings_);
1455 compiler_phases_timings_.reset(new CumulativeLogger("compilation times"));
Vladimir Markof4da6752014-08-01 19:04:18 +01001456
Vladimir Marko47496c22016-01-27 16:15:08 +00001457 // Find the dex files we should not inline from.
1458
1459 std::vector<std::string> no_inline_filters;
1460 Split(no_inline_from_string_, ',', &no_inline_filters);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001461
1462 // For now, on the host always have core-oj removed.
Vladimir Marko47496c22016-01-27 16:15:08 +00001463 const std::string core_oj = "core-oj";
1464 if (!kIsTargetBuild && !ContainsElement(no_inline_filters, core_oj)) {
1465 no_inline_filters.push_back(core_oj);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001466 }
1467
Vladimir Marko47496c22016-01-27 16:15:08 +00001468 if (!no_inline_filters.empty()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001469 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1470 std::vector<const DexFile*> class_path_files = MakeNonOwningPointerVector(class_path_files_);
1471 std::vector<const std::vector<const DexFile*>*> dex_file_vectors = {
1472 &class_linker->GetBootClassPath(),
1473 &class_path_files,
1474 &dex_files_
1475 };
1476 for (const std::vector<const DexFile*>* dex_file_vector : dex_file_vectors) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001477 for (const DexFile* dex_file : *dex_file_vector) {
Vladimir Marko47496c22016-01-27 16:15:08 +00001478 for (const std::string& filter : no_inline_filters) {
1479 // Use dex_file->GetLocation() rather than dex_file->GetBaseLocation(). This
1480 // allows tests to specify <test-dexfile>:classes2.dex if needed but if the
1481 // base location passes the StartsWith() test, so do all extra locations.
1482 std::string dex_location = dex_file->GetLocation();
1483 if (filter.find('/') == std::string::npos) {
1484 // The filter does not contain the path. Remove the path from dex_location as well.
1485 size_t last_slash = dex_file->GetLocation().rfind('/');
1486 if (last_slash != std::string::npos) {
1487 dex_location = dex_location.substr(last_slash + 1);
1488 }
1489 }
1490
1491 if (StartsWith(dex_location, filter.c_str())) {
1492 VLOG(compiler) << "Disabling inlining from " << dex_file->GetLocation();
1493 no_inline_from_dex_files_.push_back(dex_file);
1494 break;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001495 }
1496 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001497 }
Vladimir Marko47496c22016-01-27 16:15:08 +00001498 }
1499 if (!no_inline_from_dex_files_.empty()) {
1500 compiler_options_->no_inline_from_ = &no_inline_from_dex_files_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001501 }
1502 }
1503
Vladimir Marko307dac92015-10-20 11:20:09 +01001504 driver_.reset(new CompilerDriver(compiler_options_.get(),
1505 verification_results_.get(),
1506 &method_inliner_map_,
1507 compiler_kind_,
1508 instruction_set_,
1509 instruction_set_features_.get(),
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001510 IsBootImage(),
Vladimir Marko307dac92015-10-20 11:20:09 +01001511 image_classes_.release(),
1512 compiled_classes_.release(),
Vladimir Marko944da602016-02-19 12:27:55 +00001513 /* compiled_methods */ nullptr,
Vladimir Marko307dac92015-10-20 11:20:09 +01001514 thread_count_,
1515 dump_stats_,
1516 dump_passes_,
Vladimir Marko307dac92015-10-20 11:20:09 +01001517 compiler_phases_timings_.get(),
1518 swap_fd_,
Calin Juravle998c2162015-12-21 15:39:33 +02001519 profile_compilation_info_.get()));
Vladimir Markod1eaf0d2015-10-29 12:18:29 +00001520 driver_->SetDexFilesForOatFile(dex_files_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001521 driver_->CompileAll(class_loader_, dex_files_, timings_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001522 }
1523
Jeff Hao436183f2016-01-12 16:36:50 -08001524 // Notes on the interleaving of creating the images and oat files to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001525 // ensure the references between the two are correct.
1526 //
1527 // Currently we have a memory layout that looks something like this:
1528 //
1529 // +--------------+
Jeff Hao436183f2016-01-12 16:36:50 -08001530 // | images |
Brian Carlstrom7940e442013-07-12 13:46:57 -07001531 // +--------------+
Jeff Hao436183f2016-01-12 16:36:50 -08001532 // | oat files |
Brian Carlstrom7940e442013-07-12 13:46:57 -07001533 // +--------------+
1534 // | alloc spaces |
1535 // +--------------+
1536 //
Jeff Hao436183f2016-01-12 16:36:50 -08001537 // There are several constraints on the loading of the images and oat files.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001538 //
Jeff Hao436183f2016-01-12 16:36:50 -08001539 // 1. The images are expected to be loaded at an absolute address and
1540 // contain Objects with absolute pointers within the images.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001541 //
Jeff Hao436183f2016-01-12 16:36:50 -08001542 // 2. There are absolute pointers from Methods in the images to their
1543 // code in the oat files.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001544 //
Jeff Hao436183f2016-01-12 16:36:50 -08001545 // 3. There are absolute pointers from the code in the oat files to Methods
1546 // in the images.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001547 //
Jeff Hao436183f2016-01-12 16:36:50 -08001548 // 4. There are absolute pointers from code in the oat files to other code
1549 // in the oat files.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001550 //
1551 // To get this all correct, we go through several steps.
1552 //
Jeff Hao436183f2016-01-12 16:36:50 -08001553 // 1. We prepare offsets for all data in the oat files and calculate
Vladimir Markof4da6752014-08-01 19:04:18 +01001554 // the oat data size and code size. During this stage, we also set
1555 // oat code offsets in methods for use by the image writer.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001556 //
Jeff Hao436183f2016-01-12 16:36:50 -08001557 // 2. We prepare offsets for the objects in the images and calculate
1558 // the image sizes.
Vladimir Markof4da6752014-08-01 19:04:18 +01001559 //
Jeff Hao436183f2016-01-12 16:36:50 -08001560 // 3. We create the oat files. Originally this was just our own proprietary
Vladimir Markof4da6752014-08-01 19:04:18 +01001561 // file but now it is contained within an ELF dynamic object (aka an .so
Jeff Hao436183f2016-01-12 16:36:50 -08001562 // file). Since we know the image sizes and oat data sizes and code sizes we
Vladimir Markof4da6752014-08-01 19:04:18 +01001563 // can prepare the ELF headers and we then know the ELF memory segment
1564 // layout and we can now resolve all references. The compiler provides
1565 // LinkerPatch information in each CompiledMethod and we resolve these,
1566 // using the layout information and image object locations provided by
1567 // image writer, as we're writing the method code.
1568 //
Jeff Hao436183f2016-01-12 16:36:50 -08001569 // 4. We create the image files. They need to know where the oat files
1570 // will be loaded after itself. Originally oat files were simply
1571 // memory mapped so we could predict where their contents were based
1572 // on the file size. Now that they are ELF files, we need to inspect
1573 // the ELF files to understand the in memory segment layout including
Vladimir Markof4da6752014-08-01 19:04:18 +01001574 // where the oat header is located within.
1575 // TODO: We could just remember this information from step 3.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001576 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001577 // 5. We fixup the ELF program headers so that dlopen will try to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001578 // load the .so at the desired location at runtime by offsetting the
1579 // Elf32_Phdr.p_vaddr values by the desired base address.
Vladimir Markof4da6752014-08-01 19:04:18 +01001580 // TODO: Do this in step 3. We already know the layout there.
1581 //
1582 // Steps 1.-3. are done by the CreateOatFile() above, steps 4.-5.
1583 // are done by the CreateImageFile() below.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001584
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001585 // Write out the generated code part. Calls the OatWriter and ElfBuilder. Also prepares the
1586 // ImageWriter, if necessary.
Andreas Gampe10e477d2014-11-19 12:57:42 -08001587 // Note: Flushing (and closing) the file is the caller's responsibility, except for the failure
1588 // case (when the file will be explicitly erased).
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001589 bool WriteOatFiles() {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001590 TimingLogger::ScopedTiming t("dex2oat Oat", timings_);
1591
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001592 // Sync the data to the file, in case we did dex2dex transformations.
1593 for (const std::unique_ptr<MemMap>& map : opened_dex_files_maps_) {
1594 if (!map->Sync()) {
1595 PLOG(ERROR) << "Failed to Sync() dex2dex output. Map: " << map->GetName();
1596 return false;
1597 }
1598 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001599
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001600 if (IsImage()) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001601 if (app_image_ && image_base_ == 0) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001602 gc::Heap* const heap = Runtime::Current()->GetHeap();
1603 for (gc::space::ImageSpace* image_space : heap->GetBootImageSpaces()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001604 image_base_ = std::max(image_base_, RoundUp(
1605 reinterpret_cast<uintptr_t>(image_space->GetImageHeader().GetOatFileEnd()),
1606 kPageSize));
1607 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001608 // The non moving space is right after the oat file. Put the preferred app image location
1609 // right after the non moving space so that we ideally get a continuous immune region for
1610 // the GC.
1611 const size_t non_moving_space_capacity = heap->GetNonMovingSpace()->Capacity();
1612 image_base_ += non_moving_space_capacity;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001613 VLOG(compiler) << "App image base=" << reinterpret_cast<void*>(image_base_);
1614 }
1615
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001616 image_writer_.reset(new ImageWriter(*driver_,
1617 image_base_,
1618 compiler_options_->GetCompilePic(),
1619 IsAppImage(),
1620 image_storage_mode_,
1621 oat_filenames_,
Vladimir Marko944da602016-02-19 12:27:55 +00001622 dex_file_oat_index_map_));
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001623
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001624 // We need to prepare method offsets in the image address space for direct method patching.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001625 TimingLogger::ScopedTiming t2("dex2oat Prepare image address space", timings_);
1626 if (!image_writer_->PrepareImageAddressSpace()) {
1627 LOG(ERROR) << "Failed to prepare image address space.";
1628 return false;
1629 }
1630 }
1631
Vladimir Marko944da602016-02-19 12:27:55 +00001632 linker::MultiOatRelativePatcher patcher(instruction_set_, instruction_set_features_.get());
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001633 {
1634 TimingLogger::ScopedTiming t2("dex2oat Write ELF", timings_);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001635 for (size_t i = 0, size = oat_files_.size(); i != size; ++i) {
Vladimir Marko944da602016-02-19 12:27:55 +00001636 std::unique_ptr<ElfWriter>& elf_writer = elf_writers_[i];
1637 std::unique_ptr<OatWriter>& oat_writer = oat_writers_[i];
1638
1639 std::vector<const DexFile*>& dex_files = dex_files_per_oat_file_[i];
1640 oat_writer->PrepareLayout(driver_.get(), image_writer_.get(), dex_files, &patcher);
1641
1642 size_t rodata_size = oat_writer->GetOatHeader().GetExecutableOffset();
1643 size_t text_size = oat_writer->GetSize() - rodata_size;
1644 elf_writer->SetLoadedSectionSizes(rodata_size, text_size, oat_writer->GetBssSize());
1645
1646 if (IsImage()) {
1647 // Update oat layout.
1648 DCHECK(image_writer_ != nullptr);
1649 DCHECK_LT(i, oat_filenames_.size());
1650 image_writer_->UpdateOatFileLayout(i,
1651 elf_writer->GetLoadedSize(),
1652 oat_writer->GetOatDataOffset(),
1653 oat_writer->GetSize());
1654 }
1655 }
1656
1657 for (size_t i = 0, size = oat_files_.size(); i != size; ++i) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001658 std::unique_ptr<File>& oat_file = oat_files_[i];
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001659 std::unique_ptr<ElfWriter>& elf_writer = elf_writers_[i];
1660 std::unique_ptr<OatWriter>& oat_writer = oat_writers_[i];
Vladimir Marko10c13562015-11-25 14:33:36 +00001661
David Srbecky0c4572e2016-01-22 19:19:25 +00001662 // We need to mirror the layout of the ELF file in the compressed debug-info.
Vladimir Marko944da602016-02-19 12:27:55 +00001663 // Therefore PrepareDebugInfo() relies on the SetLoadedSectionSizes() call further above.
1664 elf_writer->PrepareDebugInfo(oat_writer->GetMethodDebugInfo());
David Srbecky0c4572e2016-01-22 19:19:25 +00001665
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001666 OutputStream*& rodata = rodata_[i];
1667 DCHECK(rodata != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001668 if (!oat_writer->WriteRodata(rodata)) {
1669 LOG(ERROR) << "Failed to write .rodata section to the ELF file " << oat_file->GetPath();
1670 return false;
1671 }
1672 elf_writer->EndRoData(rodata);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001673 rodata = nullptr;
Vladimir Marko10c13562015-11-25 14:33:36 +00001674
Jeff Haodcdc85b2015-12-04 14:06:18 -08001675 OutputStream* text = elf_writer->StartText();
1676 if (!oat_writer->WriteCode(text)) {
1677 LOG(ERROR) << "Failed to write .text section to the ELF file " << oat_file->GetPath();
1678 return false;
1679 }
1680 elf_writer->EndText(text);
Vladimir Marko10c13562015-11-25 14:33:36 +00001681
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001682 if (!oat_writer->WriteHeader(elf_writer->GetStream(),
1683 image_file_location_oat_checksum_,
1684 image_file_location_oat_data_begin_,
1685 image_patch_delta_)) {
1686 LOG(ERROR) << "Failed to write oat header to the ELF file " << oat_file->GetPath();
1687 return false;
1688 }
1689
Vladimir Marko944da602016-02-19 12:27:55 +00001690 if (IsImage()) {
1691 // Update oat header information.
1692 DCHECK(image_writer_ != nullptr);
1693 DCHECK_LT(i, oat_filenames_.size());
1694 image_writer_->UpdateOatFileHeader(i, oat_writer->GetOatHeader());
1695 }
1696
Jeff Haodcdc85b2015-12-04 14:06:18 -08001697 elf_writer->WriteDynamicSection();
1698 elf_writer->WriteDebugInfo(oat_writer->GetMethodDebugInfo());
1699 elf_writer->WritePatchLocations(oat_writer->GetAbsolutePatchLocations());
Vladimir Marko10c13562015-11-25 14:33:36 +00001700
Jeff Haodcdc85b2015-12-04 14:06:18 -08001701 if (!elf_writer->End()) {
1702 LOG(ERROR) << "Failed to write ELF file " << oat_file->GetPath();
1703 return false;
1704 }
1705
1706 // Flush the oat file.
1707 if (oat_files_[i] != nullptr) {
1708 if (oat_files_[i]->Flush() != 0) {
1709 PLOG(ERROR) << "Failed to flush oat file: " << oat_filenames_[i];
Jeff Haodcdc85b2015-12-04 14:06:18 -08001710 return false;
1711 }
1712 }
1713
Jeff Haodcdc85b2015-12-04 14:06:18 -08001714 VLOG(compiler) << "Oat file written successfully: " << oat_filenames_[i];
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001715
1716 oat_writer.reset();
1717 elf_writer.reset();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001718 }
1719 }
1720
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001721 return true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001722 }
1723
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001724 // If we are compiling an image, invoke the image creation routine. Else just skip.
1725 bool HandleImage() {
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001726 if (IsImage()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001727 TimingLogger::ScopedTiming t("dex2oat ImageWriter", timings_);
1728 if (!CreateImageFile()) {
1729 return false;
1730 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001731 VLOG(compiler) << "Images written successfully";
Brian Carlstrom45602482013-07-21 22:07:55 -07001732 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001733 return true;
1734 }
1735
Jeff Haodcdc85b2015-12-04 14:06:18 -08001736 // Create a copy from stripped to unstripped.
1737 bool CopyStrippedToUnstripped() {
1738 for (size_t i = 0; i < oat_unstripped_.size(); ++i) {
1739 // If we don't want to strip in place, copy from stripped location to unstripped location.
1740 // We need to strip after image creation because FixupElf needs to use .strtab.
1741 if (strcmp(oat_unstripped_[i], oat_filenames_[i]) != 0) {
1742 // If the oat file is still open, flush it.
1743 if (oat_files_[i].get() != nullptr && oat_files_[i]->IsOpened()) {
1744 if (!FlushCloseOatFile(i)) {
1745 return false;
1746 }
1747 }
1748
1749 TimingLogger::ScopedTiming t("dex2oat OatFile copy", timings_);
1750 std::unique_ptr<File> in(OS::OpenFileForReading(oat_filenames_[i]));
1751 std::unique_ptr<File> out(OS::CreateEmptyFile(oat_unstripped_[i]));
1752 size_t buffer_size = 8192;
1753 std::unique_ptr<uint8_t[]> buffer(new uint8_t[buffer_size]);
1754 while (true) {
1755 int bytes_read = TEMP_FAILURE_RETRY(read(in->Fd(), buffer.get(), buffer_size));
1756 if (bytes_read <= 0) {
1757 break;
1758 }
1759 bool write_ok = out->WriteFully(buffer.get(), bytes_read);
1760 CHECK(write_ok);
1761 }
1762 if (out->FlushCloseOrErase() != 0) {
1763 PLOG(ERROR) << "Failed to flush and close copied oat file: " << oat_unstripped_[i];
1764 return false;
1765 }
1766 VLOG(compiler) << "Oat file copied successfully (unstripped): " << oat_unstripped_[i];
1767 }
1768 }
1769 return true;
1770 }
1771
1772 bool FlushOatFiles() {
1773 TimingLogger::ScopedTiming t2("dex2oat Flush ELF", timings_);
1774 for (size_t i = 0; i < oat_files_.size(); ++i) {
1775 if (oat_files_[i].get() != nullptr) {
1776 if (oat_files_[i]->Flush() != 0) {
1777 PLOG(ERROR) << "Failed to flush oat file: " << oat_filenames_[i];
1778 oat_files_[i]->Erase();
Andreas Gampe10e477d2014-11-19 12:57:42 -08001779 return false;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001780 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001781 }
Nicolas Geoffrayea3fa0b2014-02-10 11:59:41 +00001782 }
Andreas Gampe10e477d2014-11-19 12:57:42 -08001783 return true;
1784 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001785
Jeff Haodcdc85b2015-12-04 14:06:18 -08001786 bool FlushCloseOatFile(size_t i) {
1787 if (oat_files_[i].get() != nullptr) {
1788 std::unique_ptr<File> tmp(oat_files_[i].release());
Andreas Gampe10e477d2014-11-19 12:57:42 -08001789 if (tmp->FlushCloseOrErase() != 0) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001790 PLOG(ERROR) << "Failed to flush and close oat file: " << oat_filenames_[i];
Andreas Gampe10e477d2014-11-19 12:57:42 -08001791 return false;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001792 }
1793 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001794 return true;
1795 }
1796
Jeff Haodcdc85b2015-12-04 14:06:18 -08001797 bool FlushCloseOatFiles() {
1798 bool result = true;
1799 for (size_t i = 0; i < oat_files_.size(); ++i) {
1800 result &= FlushCloseOatFile(i);
1801 }
1802 return result;
1803 }
1804
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001805 void DumpTiming() {
1806 if (dump_timing_ || (dump_slow_timing_ && timings_->GetTotalNs() > MsToNs(1000))) {
1807 LOG(INFO) << Dumpable<TimingLogger>(*timings_);
1808 }
1809 if (dump_passes_) {
1810 LOG(INFO) << Dumpable<CumulativeLogger>(*driver_->GetTimingsLogger());
1811 }
1812 }
1813
1814 CompilerOptions* GetCompilerOptions() const {
1815 return compiler_options_.get();
1816 }
1817
Andreas Gampe10e477d2014-11-19 12:57:42 -08001818 bool IsImage() const {
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001819 return IsAppImage() || IsBootImage();
1820 }
1821
1822 bool IsAppImage() const {
1823 return app_image_;
1824 }
1825
1826 bool IsBootImage() const {
1827 return boot_image_;
Andreas Gampe10e477d2014-11-19 12:57:42 -08001828 }
1829
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001830 bool IsHost() const {
1831 return is_host_;
1832 }
1833
Calin Juravle998c2162015-12-21 15:39:33 +02001834 bool UseProfileGuidedCompilation() const {
Calin Juravle2e2db782016-02-23 12:00:03 +00001835 return !profile_file_.empty() || (profile_file_fd_ != kInvalidFd);
Calin Juravle998c2162015-12-21 15:39:33 +02001836 }
1837
Calin Juravle2e2db782016-02-23 12:00:03 +00001838 bool LoadProfile() {
Calin Juravle998c2162015-12-21 15:39:33 +02001839 DCHECK(UseProfileGuidedCompilation());
Calin Juravle2e2db782016-02-23 12:00:03 +00001840
1841 profile_compilation_info_.reset(new ProfileCompilationInfo());
1842 ScopedFlock flock;
1843 bool success = false;
1844 std::string error;
1845 if (profile_file_fd_ != -1) {
1846 // The file doesn't need to be flushed so don't check the usage.
1847 // Pass a bogus path so that we can easily attribute any reported error.
1848 File file(profile_file_fd_, "profile", /*check_usage*/ false, /*read_only_mode*/ true);
1849 if (flock.Init(&file, &error)) {
1850 success = profile_compilation_info_->Load(profile_file_fd_);
1851 }
Calin Juravle877fd962016-01-05 14:29:29 +00001852 } else {
Calin Juravle2e2db782016-02-23 12:00:03 +00001853 if (flock.Init(profile_file_.c_str(), O_RDONLY, /* block */ true, &error)) {
1854 success = profile_compilation_info_->Load(flock.GetFile()->Fd());
1855 }
1856 }
1857 if (!error.empty()) {
1858 LOG(WARNING) << "Cannot lock profiles: " << error;
Calin Juravle998c2162015-12-21 15:39:33 +02001859 }
Calin Juravle877fd962016-01-05 14:29:29 +00001860
Calin Juravle2e2db782016-02-23 12:00:03 +00001861 if (!success) {
1862 profile_compilation_info_.reset(nullptr);
1863 }
Calin Juravle877fd962016-01-05 14:29:29 +00001864
Calin Juravle2e2db782016-02-23 12:00:03 +00001865 return success;
Calin Juravle998c2162015-12-21 15:39:33 +02001866 }
1867
1868 bool ShouldCompileBasedOnProfiles() const {
1869 DCHECK(UseProfileGuidedCompilation());
Calin Juravle2e2db782016-02-23 12:00:03 +00001870 // If we are given a profile, compile only if we have some data in it.
1871 return (profile_compilation_info_ != nullptr) &&
1872 (profile_compilation_info_->GetNumberOfMethods() != 0);
Calin Juravle998c2162015-12-21 15:39:33 +02001873 }
1874
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001875 private:
Vladimir Marko49b0f452015-12-10 13:49:19 +00001876 template <typename T>
1877 static std::vector<T*> MakeNonOwningPointerVector(const std::vector<std::unique_ptr<T>>& src) {
1878 std::vector<T*> result;
1879 result.reserve(src.size());
1880 for (const std::unique_ptr<T>& t : src) {
1881 result.push_back(t.get());
1882 }
1883 return result;
1884 }
1885
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001886 std::string GetMultiImageBootClassPath() {
1887 DCHECK(IsBootImage());
1888 DCHECK_GT(oat_filenames_.size(), 1u);
1889 // If the image filename was adapted (e.g., for our tests), we need to change this here,
1890 // too, but need to strip all path components (they will be re-established when loading).
1891 std::ostringstream bootcp_oss;
1892 bool first_bootcp = true;
1893 for (size_t i = 0; i < dex_locations_.size(); ++i) {
1894 if (!first_bootcp) {
1895 bootcp_oss << ":";
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001896 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001897
1898 std::string dex_loc = dex_locations_[i];
1899 std::string image_filename = image_filenames_[i];
1900
1901 // Use the dex_loc path, but the image_filename name (without path elements).
1902 size_t dex_last_slash = dex_loc.rfind('/');
1903
1904 // npos is max(size_t). That makes this a bit ugly.
1905 size_t image_last_slash = image_filename.rfind('/');
1906 size_t image_last_at = image_filename.rfind('@');
1907 size_t image_last_sep = (image_last_slash == std::string::npos)
1908 ? image_last_at
1909 : (image_last_at == std::string::npos)
1910 ? std::string::npos
1911 : std::max(image_last_slash, image_last_at);
1912 // Note: whenever image_last_sep == npos, +1 overflow means using the full string.
1913
1914 if (dex_last_slash == std::string::npos) {
1915 dex_loc = image_filename.substr(image_last_sep + 1);
1916 } else {
1917 dex_loc = dex_loc.substr(0, dex_last_slash + 1) +
1918 image_filename.substr(image_last_sep + 1);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001919 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001920
1921 // Image filenames already end with .art, no need to replace.
1922
1923 bootcp_oss << dex_loc;
1924 first_bootcp = false;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001925 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001926 return bootcp_oss.str();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001927 }
1928
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001929 std::vector<std::string> GetClassPathLocations(const std::string& class_path) {
1930 // This function is used only for apps and for an app we have exactly one oat file.
1931 DCHECK(!IsBootImage());
1932 DCHECK_EQ(oat_writers_.size(), 1u);
1933 std::vector<std::string> dex_files_canonical_locations;
1934 for (const char* location : oat_writers_[0]->GetSourceLocations()) {
1935 dex_files_canonical_locations.push_back(DexFile::GetDexCanonicalLocation(location));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001936 }
Vladimir Marko625a64a2015-11-26 14:44:16 +00001937
Vladimir Marko919f5532016-01-20 19:13:01 +00001938 std::vector<std::string> parsed;
1939 Split(class_path, ':', &parsed);
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001940 auto kept_it = std::remove_if(parsed.begin(),
1941 parsed.end(),
1942 [dex_files_canonical_locations](const std::string& location) {
1943 return ContainsElement(dex_files_canonical_locations,
1944 DexFile::GetDexCanonicalLocation(location.c_str()));
1945 });
1946 parsed.erase(kept_it, parsed.end());
1947 return parsed;
1948 }
1949
1950 // Opens requested class path files and appends them to opened_dex_files.
1951 static void OpenClassPathFiles(const std::vector<std::string>& class_path_locations,
1952 std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
1953 DCHECK(opened_dex_files != nullptr) << "OpenClassPathFiles out-param is nullptr";
1954 for (const std::string& location : class_path_locations) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001955 std::string error_msg;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00001956 if (!DexFile::Open(location.c_str(), location.c_str(), &error_msg, opened_dex_files)) {
1957 LOG(WARNING) << "Failed to open dex file '" << location << "': " << error_msg;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001958 }
1959 }
1960 }
1961
Vladimir Marko49b0f452015-12-10 13:49:19 +00001962 bool PrepareImageClasses() {
1963 // If --image-classes was specified, calculate the full list of classes to include in the image.
1964 if (image_classes_filename_ != nullptr) {
1965 image_classes_ =
1966 ReadClasses(image_classes_zip_filename_, image_classes_filename_, "image");
1967 if (image_classes_ == nullptr) {
1968 return false;
1969 }
1970 } else if (IsBootImage()) {
1971 image_classes_.reset(new std::unordered_set<std::string>);
1972 }
1973 return true;
1974 }
1975
1976 bool PrepareCompiledClasses() {
1977 // If --compiled-classes was specified, calculate the full list of classes to compile in the
1978 // image.
1979 if (compiled_classes_filename_ != nullptr) {
1980 compiled_classes_ =
1981 ReadClasses(compiled_classes_zip_filename_, compiled_classes_filename_, "compiled");
1982 if (compiled_classes_ == nullptr) {
1983 return false;
1984 }
1985 } else {
1986 compiled_classes_.reset(nullptr); // By default compile everything.
1987 }
1988 return true;
1989 }
1990
1991 static std::unique_ptr<std::unordered_set<std::string>> ReadClasses(const char* zip_filename,
1992 const char* classes_filename,
1993 const char* tag) {
1994 std::unique_ptr<std::unordered_set<std::string>> classes;
1995 std::string error_msg;
1996 if (zip_filename != nullptr) {
1997 classes.reset(ReadImageClassesFromZip(zip_filename, classes_filename, &error_msg));
1998 } else {
1999 classes.reset(ReadImageClassesFromFile(classes_filename));
2000 }
2001 if (classes == nullptr) {
2002 LOG(ERROR) << "Failed to create list of " << tag << " classes from '"
2003 << classes_filename << "': " << error_msg;
2004 }
2005 return classes;
2006 }
2007
2008 bool PrepareCompiledMethods() {
2009 // If --compiled-methods was specified, read the methods to compile from the given file(s).
2010 if (compiled_methods_filename_ != nullptr) {
2011 std::string error_msg;
2012 if (compiled_methods_zip_filename_ != nullptr) {
2013 compiled_methods_.reset(ReadCommentedInputFromZip(compiled_methods_zip_filename_,
2014 compiled_methods_filename_,
2015 nullptr, // No post-processing.
2016 &error_msg));
2017 } else {
2018 compiled_methods_.reset(ReadCommentedInputFromFile(compiled_methods_filename_,
2019 nullptr)); // No post-processing.
2020 }
2021 if (compiled_methods_.get() == nullptr) {
2022 LOG(ERROR) << "Failed to create list of compiled methods from '"
2023 << compiled_methods_filename_ << "': " << error_msg;
2024 return false;
2025 }
2026 } else {
2027 compiled_methods_.reset(nullptr); // By default compile everything.
2028 }
2029 return true;
2030 }
2031
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002032 void PruneNonExistentDexFiles() {
2033 DCHECK_EQ(dex_filenames_.size(), dex_locations_.size());
2034 size_t kept = 0u;
2035 for (size_t i = 0, size = dex_filenames_.size(); i != size; ++i) {
2036 if (!OS::FileExists(dex_filenames_[i])) {
2037 LOG(WARNING) << "Skipping non-existent dex file '" << dex_filenames_[i] << "'";
2038 } else {
2039 dex_filenames_[kept] = dex_filenames_[i];
2040 dex_locations_[kept] = dex_locations_[i];
2041 ++kept;
2042 }
2043 }
2044 dex_filenames_.resize(kept);
2045 dex_locations_.resize(kept);
2046 }
2047
2048 bool AddDexFileSources() {
2049 TimingLogger::ScopedTiming t2("AddDexFileSources", timings_);
2050 if (zip_fd_ != -1) {
2051 DCHECK_EQ(oat_writers_.size(), 1u);
2052 if (!oat_writers_[0]->AddZippedDexFilesSource(ScopedFd(zip_fd_), zip_location_.c_str())) {
2053 return false;
2054 }
2055 } else if (oat_writers_.size() > 1u) {
2056 // Multi-image.
2057 DCHECK_EQ(oat_writers_.size(), dex_filenames_.size());
2058 DCHECK_EQ(oat_writers_.size(), dex_locations_.size());
2059 for (size_t i = 0, size = oat_writers_.size(); i != size; ++i) {
2060 if (!oat_writers_[i]->AddDexFileSource(dex_filenames_[i], dex_locations_[i])) {
2061 return false;
2062 }
2063 }
2064 } else {
2065 DCHECK_EQ(oat_writers_.size(), 1u);
2066 DCHECK_EQ(dex_filenames_.size(), dex_locations_.size());
2067 DCHECK_NE(dex_filenames_.size(), 0u);
2068 for (size_t i = 0; i != dex_filenames_.size(); ++i) {
2069 if (!oat_writers_[0]->AddDexFileSource(dex_filenames_[i], dex_locations_[i])) {
2070 return false;
2071 }
2072 }
2073 }
2074 return true;
2075 }
2076
2077 void CreateOatWriters() {
2078 TimingLogger::ScopedTiming t2("CreateOatWriters", timings_);
2079 elf_writers_.reserve(oat_files_.size());
2080 oat_writers_.reserve(oat_files_.size());
2081 for (const std::unique_ptr<File>& oat_file : oat_files_) {
2082 elf_writers_.emplace_back(
2083 CreateElfWriterQuick(instruction_set_, compiler_options_.get(), oat_file.get()));
2084 elf_writers_.back()->Start();
2085 oat_writers_.emplace_back(new OatWriter(IsBootImage(), timings_));
2086 }
2087 }
2088
Vladimir Marko49b0f452015-12-10 13:49:19 +00002089 void SaveDexInput() {
2090 for (size_t i = 0; i < dex_files_.size(); ++i) {
2091 const DexFile* dex_file = dex_files_[i];
2092 std::string tmp_file_name(StringPrintf("/data/local/tmp/dex2oat.%d.%zd.dex",
2093 getpid(), i));
2094 std::unique_ptr<File> tmp_file(OS::CreateEmptyFile(tmp_file_name.c_str()));
2095 if (tmp_file.get() == nullptr) {
2096 PLOG(ERROR) << "Failed to open file " << tmp_file_name
2097 << ". Try: adb shell chmod 777 /data/local/tmp";
2098 continue;
2099 }
2100 // This is just dumping files for debugging. Ignore errors, and leave remnants.
2101 UNUSED(tmp_file->WriteFully(dex_file->Begin(), dex_file->Size()));
2102 UNUSED(tmp_file->Flush());
2103 UNUSED(tmp_file->Close());
2104 LOG(INFO) << "Wrote input to " << tmp_file_name;
2105 }
2106 }
2107
2108 bool PrepareRuntimeOptions(RuntimeArgumentMap* runtime_options) {
2109 RuntimeOptions raw_options;
2110 if (boot_image_filename_.empty()) {
2111 std::string boot_class_path = "-Xbootclasspath:";
2112 boot_class_path += Join(dex_filenames_, ':');
2113 raw_options.push_back(std::make_pair(boot_class_path, nullptr));
2114 std::string boot_class_path_locations = "-Xbootclasspath-locations:";
2115 boot_class_path_locations += Join(dex_locations_, ':');
2116 raw_options.push_back(std::make_pair(boot_class_path_locations, nullptr));
2117 } else {
2118 std::string boot_image_option = "-Ximage:";
2119 boot_image_option += boot_image_filename_;
2120 raw_options.push_back(std::make_pair(boot_image_option, nullptr));
2121 }
2122 for (size_t i = 0; i < runtime_args_.size(); i++) {
2123 raw_options.push_back(std::make_pair(runtime_args_[i], nullptr));
2124 }
2125
2126 raw_options.push_back(std::make_pair("compilercallbacks", callbacks_.get()));
2127 raw_options.push_back(
2128 std::make_pair("imageinstructionset", GetInstructionSetString(instruction_set_)));
2129
2130 // Only allow no boot image for the runtime if we're compiling one. When we compile an app,
2131 // we don't want fallback mode, it will abort as we do not push a boot classpath (it might
2132 // have been stripped in preopting, anyways).
2133 if (!IsBootImage()) {
2134 raw_options.push_back(std::make_pair("-Xno-dex-file-fallback", nullptr));
2135 }
2136 // Disable libsigchain. We don't don't need it during compilation and it prevents us
2137 // from getting a statically linked version of dex2oat (because of dlsym and RTLD_NEXT).
2138 raw_options.push_back(std::make_pair("-Xno-sig-chain", nullptr));
Lin Zang97f3f7d2016-01-13 10:25:00 +08002139 // Disable Hspace compaction to save heap size virtual space.
2140 // Only need disable Hspace for OOM becasue background collector is equal to
2141 // foreground collector by default for dex2oat.
2142 raw_options.push_back(std::make_pair("-XX:DisableHSpaceCompactForOOM", nullptr));
Vladimir Marko49b0f452015-12-10 13:49:19 +00002143
Andreas Gampeace0dc12016-01-20 13:33:13 -08002144 // If we're asked to be deterministic, ensure non-concurrent GC for determinism. Also
2145 // force the free-list implementation for large objects.
2146 if (compiler_options_->IsForceDeterminism()) {
2147 raw_options.push_back(std::make_pair("-Xgc:nonconcurrent", nullptr));
2148 raw_options.push_back(std::make_pair("-XX:LargeObjectSpace=freelist", nullptr));
2149
2150 // We also need to turn off the nonmoving space. For that, we need to disable HSpace
2151 // compaction (done above) and ensure that neither foreground nor background collectors
2152 // are concurrent.
2153 raw_options.push_back(std::make_pair("-XX:BackgroundGC=nonconcurrent", nullptr));
2154
2155 // To make identity hashcode deterministic, set a known seed.
2156 mirror::Object::SetHashCodeSeed(987654321U);
2157 }
2158
Vladimir Marko49b0f452015-12-10 13:49:19 +00002159 if (!Runtime::ParseOptions(raw_options, false, runtime_options)) {
2160 LOG(ERROR) << "Failed to parse runtime options";
2161 return false;
2162 }
2163 return true;
2164 }
2165
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002166 // Create a runtime necessary for compilation.
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002167 bool CreateRuntime(RuntimeArgumentMap&& runtime_options) {
2168 TimingLogger::ScopedTiming t_runtime("Create runtime", timings_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00002169 if (!Runtime::Create(std::move(runtime_options))) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002170 LOG(ERROR) << "Failed to create runtime";
2171 return false;
2172 }
Vladimir Marko307dac92015-10-20 11:20:09 +01002173 runtime_.reset(Runtime::Current());
2174 runtime_->SetInstructionSet(instruction_set_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002175 for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
2176 Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i);
Vladimir Marko307dac92015-10-20 11:20:09 +01002177 if (!runtime_->HasCalleeSaveMethod(type)) {
2178 runtime_->SetCalleeSaveMethod(runtime_->CreateCalleeSaveMethod(), type);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002179 }
2180 }
Vladimir Marko307dac92015-10-20 11:20:09 +01002181 runtime_->GetClassLinker()->FixupDexCaches(runtime_->GetResolutionMethod());
Andreas Gampe2969bcd2015-03-09 12:57:41 -07002182
2183 // Initialize maps for unstarted runtime. This needs to be here, as running clinits needs this
2184 // set up.
Andreas Gampe799681b2015-05-15 19:24:12 -07002185 interpreter::UnstartedRuntime::Initialize();
Andreas Gampe2969bcd2015-03-09 12:57:41 -07002186
Vladimir Marko307dac92015-10-20 11:20:09 +01002187 runtime_->GetClassLinker()->RunRootClinits();
Andreas Gampe2969bcd2015-03-09 12:57:41 -07002188
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002189 // Runtime::Create acquired the mutator_lock_ that is normally given away when we
2190 // Runtime::Start, give it away now so that we don't starve GC.
2191 Thread* self = Thread::Current();
2192 self->TransitionFromRunnableToSuspended(kNative);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002193
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002194 return true;
Vladimir Marko919f5532016-01-20 19:13:01 +00002195 }
2196
Jeff Haodcdc85b2015-12-04 14:06:18 -08002197 // 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 -08002198 bool CreateImageFile()
Mathieu Chartier90443472015-07-16 20:32:27 -07002199 REQUIRES(!Locks::mutator_lock_) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002200 CHECK(image_writer_ != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002201 if (!IsBootImage()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002202 CHECK(image_filenames_.empty());
Jeff Haodcdc85b2015-12-04 14:06:18 -08002203 image_filenames_.push_back(app_image_file_name_.c_str());
2204 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002205 if (!image_writer_->Write(app_image_fd_,
2206 image_filenames_,
Vladimir Marko944da602016-02-19 12:27:55 +00002207 oat_filenames_)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002208 LOG(ERROR) << "Failure during image file creation";
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002209 return false;
2210 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002211
Jeff Haodcdc85b2015-12-04 14:06:18 -08002212 // We need the OatDataBegin entries.
Vladimir Marko944da602016-02-19 12:27:55 +00002213 dchecked_vector<uintptr_t> oat_data_begins;
2214 for (size_t i = 0, size = oat_filenames_.size(); i != size; ++i) {
2215 oat_data_begins.push_back(image_writer_->GetOatDataBegin(i));
Jeff Haodcdc85b2015-12-04 14:06:18 -08002216 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002217 // Destroy ImageWriter before doing FixupElf.
2218 image_writer_.reset();
2219
Vladimir Marko944da602016-02-19 12:27:55 +00002220 for (size_t i = 0, size = oat_filenames_.size(); i != size; ++i) {
2221 const char* oat_filename = oat_filenames_[i];
Jeff Haodcdc85b2015-12-04 14:06:18 -08002222 // Do not fix up the ELF file if we are --compile-pic or compiling the app image
2223 if (!compiler_options_->GetCompilePic() && IsBootImage()) {
2224 std::unique_ptr<File> oat_file(OS::OpenFileReadWrite(oat_filename));
2225 if (oat_file.get() == nullptr) {
2226 PLOG(ERROR) << "Failed to open ELF file: " << oat_filename;
2227 return false;
2228 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08002229
Vladimir Marko944da602016-02-19 12:27:55 +00002230 if (!ElfWriter::Fixup(oat_file.get(), oat_data_begins[i])) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002231 oat_file->Erase();
2232 LOG(ERROR) << "Failed to fixup ELF file " << oat_file->GetPath();
2233 return false;
2234 }
2235
2236 if (oat_file->FlushCloseOrErase()) {
2237 PLOG(ERROR) << "Failed to flush and close fixed ELF file " << oat_file->GetPath();
2238 return false;
2239 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08002240 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002241 }
2242
2243 return true;
2244 }
2245
2246 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
Andreas Gampeb1fcead2015-04-20 18:53:51 -07002247 static std::unordered_set<std::string>* ReadImageClassesFromFile(
2248 const char* image_classes_filename) {
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002249 std::function<std::string(const char*)> process = DotToDescriptor;
2250 return ReadCommentedInputFromFile(image_classes_filename, &process);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002251 }
2252
2253 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
Andreas Gampeb1fcead2015-04-20 18:53:51 -07002254 static std::unordered_set<std::string>* ReadImageClassesFromZip(
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002255 const char* zip_filename,
2256 const char* image_classes_filename,
2257 std::string* error_msg) {
2258 std::function<std::string(const char*)> process = DotToDescriptor;
2259 return ReadCommentedInputFromZip(zip_filename, image_classes_filename, &process, error_msg);
2260 }
2261
2262 // Read lines from the given file, dropping comments and empty lines. Post-process each line with
2263 // the given function.
2264 static std::unordered_set<std::string>* ReadCommentedInputFromFile(
2265 const char* input_filename, std::function<std::string(const char*)>* process) {
2266 std::unique_ptr<std::ifstream> input_file(new std::ifstream(input_filename, std::ifstream::in));
2267 if (input_file.get() == nullptr) {
2268 LOG(ERROR) << "Failed to open input file " << input_filename;
2269 return nullptr;
2270 }
2271 std::unique_ptr<std::unordered_set<std::string>> result(
2272 ReadCommentedInputStream(*input_file, process));
2273 input_file->close();
2274 return result.release();
2275 }
2276
2277 // Read lines from the given file from the given zip file, dropping comments and empty lines.
2278 // Post-process each line with the given function.
2279 static std::unordered_set<std::string>* ReadCommentedInputFromZip(
Andreas Gampeb1fcead2015-04-20 18:53:51 -07002280 const char* zip_filename,
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002281 const char* input_filename,
2282 std::function<std::string(const char*)>* process,
Andreas Gampeb1fcead2015-04-20 18:53:51 -07002283 std::string* error_msg) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002284 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::Open(zip_filename, error_msg));
2285 if (zip_archive.get() == nullptr) {
2286 return nullptr;
2287 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002288 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(input_filename, error_msg));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002289 if (zip_entry.get() == nullptr) {
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002290 *error_msg = StringPrintf("Failed to find '%s' within '%s': %s", input_filename,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002291 zip_filename, error_msg->c_str());
2292 return nullptr;
2293 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002294 std::unique_ptr<MemMap> input_file(zip_entry->ExtractToMemMap(zip_filename,
2295 input_filename,
2296 error_msg));
2297 if (input_file.get() == nullptr) {
2298 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", input_filename,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002299 zip_filename, error_msg->c_str());
2300 return nullptr;
2301 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002302 const std::string input_string(reinterpret_cast<char*>(input_file->Begin()),
2303 input_file->Size());
2304 std::istringstream input_stream(input_string);
2305 return ReadCommentedInputStream(input_stream, process);
2306 }
2307
2308 // Read lines from the given stream, dropping comments and empty lines. Post-process each line
2309 // with the given function.
2310 static std::unordered_set<std::string>* ReadCommentedInputStream(
2311 std::istream& in_stream,
2312 std::function<std::string(const char*)>* process) {
2313 std::unique_ptr<std::unordered_set<std::string>> image_classes(
2314 new std::unordered_set<std::string>);
2315 while (in_stream.good()) {
2316 std::string dot;
2317 std::getline(in_stream, dot);
2318 if (StartsWith(dot, "#") || dot.empty()) {
2319 continue;
2320 }
2321 if (process != nullptr) {
2322 std::string descriptor((*process)(dot.c_str()));
2323 image_classes->insert(descriptor);
2324 } else {
2325 image_classes->insert(dot);
2326 }
2327 }
2328 return image_classes.release();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002329 }
2330
Mathieu Chartier49285c52014-12-02 15:43:48 -08002331 void LogCompletionTime() {
Andreas Gampe1d00add2015-02-27 19:35:46 -08002332 // Note: when creation of a runtime fails, e.g., when trying to compile an app but when there
2333 // is no image, there won't be a Runtime::Current().
Brian Carlstroma11a34c2015-03-06 08:44:45 -08002334 // Note: driver creation can fail when loading an invalid dex file.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002335 LOG(INFO) << "dex2oat took " << PrettyDuration(NanoTime() - start_ns_)
Mathieu Chartierab972ef2014-12-03 17:38:22 -08002336 << " (threads: " << thread_count_ << ") "
Andreas Gampe3f30e122015-09-17 14:03:21 -07002337 << ((Runtime::Current() != nullptr && driver_ != nullptr) ?
Andreas Gampe1d00add2015-02-27 19:35:46 -08002338 driver_->GetMemoryUsageString(kIsDebugBuild || VLOG_IS_ON(compiler)) :
2339 "");
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002340 }
2341
Jeff Haodcdc85b2015-12-04 14:06:18 -08002342 std::string StripIsaFrom(const char* image_filename, InstructionSet isa) {
2343 std::string res(image_filename);
2344 size_t last_slash = res.rfind('/');
2345 if (last_slash == std::string::npos || last_slash == 0) {
2346 return res;
2347 }
2348 size_t penultimate_slash = res.rfind('/', last_slash - 1);
2349 if (penultimate_slash == std::string::npos) {
2350 return res;
2351 }
2352 // Check that the string in-between is the expected one.
2353 if (res.substr(penultimate_slash + 1, last_slash - penultimate_slash - 1) !=
2354 GetInstructionSetString(isa)) {
2355 LOG(WARNING) << "Unexpected string when trying to strip isa: " << res;
2356 return res;
2357 }
2358 return res.substr(0, penultimate_slash) + res.substr(last_slash);
2359 }
2360
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002361 std::unique_ptr<CompilerOptions> compiler_options_;
2362 Compiler::Kind compiler_kind_;
2363
2364 InstructionSet instruction_set_;
2365 std::unique_ptr<const InstructionSetFeatures> instruction_set_features_;
2366
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002367 uint32_t image_file_location_oat_checksum_;
2368 uintptr_t image_file_location_oat_data_begin_;
2369 int32_t image_patch_delta_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002370 std::unique_ptr<SafeMap<std::string, std::string> > key_value_store_;
2371
Vladimir Marko307dac92015-10-20 11:20:09 +01002372 std::unique_ptr<VerificationResults> verification_results_;
Andreas Gampe3f30e122015-09-17 14:03:21 -07002373
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002374 DexFileToMethodInlinerMap method_inliner_map_;
2375 std::unique_ptr<QuickCompilerCallbacks> callbacks_;
2376
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002377 std::unique_ptr<Runtime> runtime_;
2378
Richard Uhlerfbef44d2014-12-23 09:48:51 -08002379 // Ownership for the class path files.
2380 std::vector<std::unique_ptr<const DexFile>> class_path_files_;
2381
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002382 size_t thread_count_;
2383 uint64_t start_ns_;
2384 std::unique_ptr<WatchDog> watchdog_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002385 std::vector<std::unique_ptr<File>> oat_files_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002386 std::string oat_location_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002387 std::vector<const char*> oat_filenames_;
2388 std::vector<const char*> oat_unstripped_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002389 int oat_fd_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002390 std::vector<const char*> dex_filenames_;
2391 std::vector<const char*> dex_locations_;
2392 int zip_fd_;
2393 std::string zip_location_;
Vladimir Marko49b0f452015-12-10 13:49:19 +00002394 std::string boot_image_filename_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002395 std::vector<const char*> runtime_args_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002396 std::vector<const char*> image_filenames_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002397 uintptr_t image_base_;
2398 const char* image_classes_zip_filename_;
2399 const char* image_classes_filename_;
Mathieu Chartierceb07b32015-12-10 09:33:21 -08002400 ImageHeader::StorageMode image_storage_mode_;
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08002401 const char* compiled_classes_zip_filename_;
2402 const char* compiled_classes_filename_;
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002403 const char* compiled_methods_zip_filename_;
2404 const char* compiled_methods_filename_;
Andreas Gampeb1fcead2015-04-20 18:53:51 -07002405 std::unique_ptr<std::unordered_set<std::string>> image_classes_;
2406 std::unique_ptr<std::unordered_set<std::string>> compiled_classes_;
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002407 std::unique_ptr<std::unordered_set<std::string>> compiled_methods_;
Mathieu Chartiera90c7722015-10-29 15:41:36 -07002408 bool app_image_;
2409 bool boot_image_;
Jeff Hao436183f2016-01-12 16:36:50 -08002410 bool multi_image_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002411 bool is_host_;
2412 std::string android_root_;
2413 std::vector<const DexFile*> dex_files_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002414 std::string no_inline_from_string_;
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002415 std::vector<jobject> dex_caches_;
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002416 jobject class_loader_;
Andreas Gampe3f30e122015-09-17 14:03:21 -07002417
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002418 std::vector<std::unique_ptr<ElfWriter>> elf_writers_;
2419 std::vector<std::unique_ptr<OatWriter>> oat_writers_;
2420 std::vector<OutputStream*> rodata_;
Vladimir Marko307dac92015-10-20 11:20:09 +01002421 std::unique_ptr<ImageWriter> image_writer_;
2422 std::unique_ptr<CompilerDriver> driver_;
Andreas Gampe3f30e122015-09-17 14:03:21 -07002423
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002424 std::vector<std::unique_ptr<MemMap>> opened_dex_files_maps_;
2425 std::vector<std::unique_ptr<const DexFile>> opened_dex_files_;
2426
Vladimir Marko47496c22016-01-27 16:15:08 +00002427 std::vector<const DexFile*> no_inline_from_dex_files_;
2428
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002429 std::vector<std::string> verbose_methods_;
2430 bool dump_stats_;
2431 bool dump_passes_;
2432 bool dump_timing_;
2433 bool dump_slow_timing_;
Andreas Gampee21dc3d2014-12-08 16:59:43 -08002434 std::string swap_file_name_;
2435 int swap_fd_;
Mathieu Chartiera90c7722015-10-29 15:41:36 -07002436 std::string app_image_file_name_;
2437 int app_image_fd_;
Calin Juravle2e2db782016-02-23 12:00:03 +00002438 std::string profile_file_;
2439 int profile_file_fd_;
Calin Juravle998c2162015-12-21 15:39:33 +02002440 std::unique_ptr<ProfileCompilationInfo> profile_compilation_info_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002441 TimingLogger* timings_;
2442 std::unique_ptr<CumulativeLogger> compiler_phases_timings_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002443 std::vector<std::vector<const DexFile*>> dex_files_per_oat_file_;
Vladimir Marko944da602016-02-19 12:27:55 +00002444 std::unordered_map<const DexFile*, size_t> dex_file_oat_index_map_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002445
2446 // Backing storage.
2447 std::vector<std::string> char_backing_storage_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002448
Andreas Gampeace0dc12016-01-20 13:33:13 -08002449 // See CompilerOptions.force_determinism_.
2450 bool force_determinism_;
2451
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002452 DISALLOW_IMPLICIT_CONSTRUCTORS(Dex2Oat);
2453};
2454
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002455static void b13564922() {
2456#if defined(__linux__) && defined(__arm__)
2457 int major, minor;
2458 struct utsname uts;
2459 if (uname(&uts) != -1 &&
2460 sscanf(uts.release, "%d.%d", &major, &minor) == 2 &&
2461 ((major < 3) || ((major == 3) && (minor < 4)))) {
2462 // Kernels before 3.4 don't handle the ASLR well and we can run out of address
2463 // space (http://b/13564922). Work around the issue by inhibiting further mmap() randomization.
2464 int old_personality = personality(0xffffffff);
2465 if ((old_personality & ADDR_NO_RANDOMIZE) == 0) {
2466 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
2467 if (new_personality == -1) {
2468 LOG(WARNING) << "personality(. | ADDR_NO_RANDOMIZE) failed.";
2469 }
2470 }
2471 }
2472#endif
2473}
2474
Andreas Gampe10e477d2014-11-19 12:57:42 -08002475static int CompileImage(Dex2Oat& dex2oat) {
2476 dex2oat.Compile();
2477
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002478 if (!dex2oat.WriteOatFiles()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002479 dex2oat.EraseOatFiles();
Andreas Gampe10e477d2014-11-19 12:57:42 -08002480 return EXIT_FAILURE;
2481 }
2482
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002483 // Flush boot.oat. We always expect the output file by name, and it will be re-opened from the
2484 // unstripped name. Do not close the file if we are compiling the image with an oat fd since the
2485 // image writer will require this fd to generate the image.
2486 if (dex2oat.ShouldKeepOatFileOpen()) {
2487 if (!dex2oat.FlushOatFiles()) {
2488 return EXIT_FAILURE;
2489 }
2490 } else if (!dex2oat.FlushCloseOatFiles()) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08002491 return EXIT_FAILURE;
2492 }
2493
Jeff Haodcdc85b2015-12-04 14:06:18 -08002494 // Creates the boot.art and patches the oat files.
Andreas Gampe10e477d2014-11-19 12:57:42 -08002495 if (!dex2oat.HandleImage()) {
2496 return EXIT_FAILURE;
2497 }
2498
2499 // When given --host, finish early without stripping.
2500 if (dex2oat.IsHost()) {
2501 dex2oat.DumpTiming();
2502 return EXIT_SUCCESS;
2503 }
2504
Jeff Haodcdc85b2015-12-04 14:06:18 -08002505 // Copy stripped to unstripped location, if necessary.
2506 if (!dex2oat.CopyStrippedToUnstripped()) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08002507 return EXIT_FAILURE;
2508 }
2509
Jeff Haodcdc85b2015-12-04 14:06:18 -08002510 // FlushClose again, as stripping might have re-opened the oat files.
2511 if (!dex2oat.FlushCloseOatFiles()) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08002512 return EXIT_FAILURE;
2513 }
2514
2515 dex2oat.DumpTiming();
2516 return EXIT_SUCCESS;
2517}
2518
2519static int CompileApp(Dex2Oat& dex2oat) {
2520 dex2oat.Compile();
2521
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002522 if (!dex2oat.WriteOatFiles()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002523 dex2oat.EraseOatFiles();
Andreas Gampe10e477d2014-11-19 12:57:42 -08002524 return EXIT_FAILURE;
2525 }
2526
Jeff Haodcdc85b2015-12-04 14:06:18 -08002527 // Do not close the oat files here. We might have gotten the output file by file descriptor,
Andreas Gampe10e477d2014-11-19 12:57:42 -08002528 // which we would lose.
Andreas Gampe10e477d2014-11-19 12:57:42 -08002529
2530 // When given --host, finish early without stripping.
2531 if (dex2oat.IsHost()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002532 if (!dex2oat.FlushCloseOatFiles()) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08002533 return EXIT_FAILURE;
2534 }
2535
2536 dex2oat.DumpTiming();
2537 return EXIT_SUCCESS;
2538 }
2539
Jeff Haodcdc85b2015-12-04 14:06:18 -08002540 // Copy stripped to unstripped location, if necessary. This will implicitly flush & close the
2541 // stripped versions. If this is given, we expect to be able to open writable files by name.
2542 if (!dex2oat.CopyStrippedToUnstripped()) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08002543 return EXIT_FAILURE;
2544 }
2545
Jeff Haodcdc85b2015-12-04 14:06:18 -08002546 // Flush and close the files.
2547 if (!dex2oat.FlushCloseOatFiles()) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08002548 return EXIT_FAILURE;
2549 }
2550
2551 dex2oat.DumpTiming();
2552 return EXIT_SUCCESS;
2553}
2554
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002555static int dex2oat(int argc, char** argv) {
2556 b13564922();
2557
2558 TimingLogger timings("compiler", false, false);
2559
Roland Levillain5c7e2602016-02-23 18:08:53 +00002560 // Allocate `dex2oat` on the heap instead of on the stack, as Clang
2561 // might produce a stack frame too large for this function or for
2562 // functions inlining it (such as main), that would not fit the
2563 // requirements of the `-Wframe-larger-than` option.
2564 std::unique_ptr<Dex2Oat> dex2oat = MakeUnique<Dex2Oat>(&timings);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002565
2566 // Parse arguments. Argument mistakes will lead to exit(EXIT_FAILURE) in UsageError.
Roland Levillain5c7e2602016-02-23 18:08:53 +00002567 dex2oat->ParseArgs(argc, argv);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002568
Calin Juravle998c2162015-12-21 15:39:33 +02002569 // Process profile information and assess if we need to do a profile guided compilation.
2570 // This operation involves I/O.
Roland Levillain5c7e2602016-02-23 18:08:53 +00002571 if (dex2oat->UseProfileGuidedCompilation()) {
2572 if (dex2oat->LoadProfile()) {
2573 if (!dex2oat->ShouldCompileBasedOnProfiles()) {
Calin Juravle998c2162015-12-21 15:39:33 +02002574 LOG(INFO) << "Skipped compilation because of insignificant profile delta";
2575 return EXIT_SUCCESS;
2576 }
2577 } else {
2578 LOG(WARNING) << "Failed to process profile files";
2579 return EXIT_FAILURE;
2580 }
2581 }
2582
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002583 // Check early that the result of compilation can be written
Roland Levillain5c7e2602016-02-23 18:08:53 +00002584 if (!dex2oat->OpenFile()) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +00002585 return EXIT_FAILURE;
2586 }
2587
Andreas Gampe046c7062015-05-18 23:22:54 -07002588 // Print the complete line when any of the following is true:
2589 // 1) Debug build
2590 // 2) Compiling an image
2591 // 3) Compiling with --host
2592 // 4) Compiling on the host (not a target build)
2593 // Otherwise, print a stripped command line.
Roland Levillain5c7e2602016-02-23 18:08:53 +00002594 if (kIsDebugBuild || dex2oat->IsBootImage() || dex2oat->IsHost() || !kIsTargetBuild) {
Andreas Gampe046c7062015-05-18 23:22:54 -07002595 LOG(INFO) << CommandLine();
2596 } else {
2597 LOG(INFO) << StrippedCommandLine();
2598 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002599
Roland Levillain5c7e2602016-02-23 18:08:53 +00002600 if (!dex2oat->Setup()) {
2601 dex2oat->EraseOatFiles();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002602 return EXIT_FAILURE;
2603 }
2604
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002605 bool result;
Roland Levillain5c7e2602016-02-23 18:08:53 +00002606 if (dex2oat->IsImage()) {
2607 result = CompileImage(*dex2oat);
Andreas Gampe10e477d2014-11-19 12:57:42 -08002608 } else {
Roland Levillain5c7e2602016-02-23 18:08:53 +00002609 result = CompileApp(*dex2oat);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002610 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002611
Roland Levillain5c7e2602016-02-23 18:08:53 +00002612 dex2oat->Shutdown();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002613 return result;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002614}
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002615} // namespace art
Brian Carlstrom7940e442013-07-12 13:46:57 -07002616
2617int main(int argc, char** argv) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002618 int result = art::dex2oat(argc, argv);
2619 // Everything was done, do an explicit exit here to avoid running Runtime destructors that take
2620 // time (bug 10645725) unless we're a debug build or running on valgrind. Note: The Dex2Oat class
2621 // should not destruct the runtime in this case.
Evgenii Stepanov1e133742015-05-20 12:30:59 -07002622 if (!art::kIsDebugBuild && (RUNNING_ON_MEMORY_TOOL == 0)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002623 exit(result);
2624 }
2625 return result;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002626}