blob: dcfd5c7cbbe7b9118d947c26c67c2f44bb47a07e [file] [log] [blame]
Brian Carlstrom7940e442013-07-12 13:46:57 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Andreas Gamped687e372015-04-28 23:16:03 -070017#include <inttypes.h>
Brian Carlstrom7940e442013-07-12 13:46:57 -070018#include <stdio.h>
19#include <stdlib.h>
20#include <sys/stat.h>
Evgenii Stepanov1e133742015-05-20 12:30:59 -070021#include "base/memory_tool.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070022
23#include <fstream>
24#include <iostream>
25#include <sstream>
26#include <string>
Andreas Gampeb1fcead2015-04-20 18:53:51 -070027#include <unordered_set>
Brian Carlstrom7940e442013-07-12 13:46:57 -070028#include <vector>
29
Vladimir Markof94b7812014-06-05 15:48:04 +010030#if defined(__linux__) && defined(__arm__)
31#include <sys/personality.h>
32#include <sys/utsname.h>
33#endif
34
Ian Rogerscf7f1912014-10-22 22:06:39 -070035#define ATRACE_TAG ATRACE_TAG_DALVIK
Ian Rogersd582fa42014-11-05 23:46:43 -080036#include <cutils/trace.h>
Ian Rogerscf7f1912014-10-22 22:06:39 -070037
Mathieu Chartiere401d142015-04-22 13:56:20 -070038#include "art_method-inl.h"
Ian Rogersd582fa42014-11-05 23:46:43 -080039#include "arch/instruction_set_features.h"
Andreas Gampec5a3ea72015-01-13 16:41:53 -080040#include "arch/mips/instruction_set_features_mips.h"
Ian Rogersc7dd2952014-10-21 23:31:19 -070041#include "base/dumpable.h"
Andreas Gampe794ad762015-02-23 08:12:24 -080042#include "base/macros.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070043#include "base/stl_util.h"
44#include "base/stringpiece.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010045#include "base/time_utils.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070046#include "base/timing_logger.h"
47#include "base/unix_file/fd_file.h"
48#include "class_linker.h"
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +000049#include "compiler.h"
Vladimir Marko2b5eaa22013-12-13 13:59:30 +000050#include "compiler_callbacks.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070051#include "dex_file-inl.h"
Mathieu Chartier5bdab122015-01-26 18:30:19 -080052#include "dex/pass_manager.h"
Vladimir Markoc7f83202014-01-24 17:55:18 +000053#include "dex/verification_results.h"
Ian Rogerse63db272014-07-15 15:36:11 -070054#include "dex/quick_compiler_callbacks.h"
55#include "dex/quick/dex_file_to_method_inliner_map.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070056#include "driver/compiler_driver.h"
Brian Carlstrom6449c622014-02-10 23:48:36 -080057#include "driver/compiler_options.h"
Vladimir Marko10c13562015-11-25 14:33:36 +000058#include "dwarf/method_debug_info.h"
Andreas Gampe88ec7f42014-11-05 10:18:32 -080059#include "elf_file.h"
Tong Shen62d1ca32014-09-03 17:24:56 -070060#include "elf_writer.h"
Vladimir Marko10c13562015-11-25 14:33:36 +000061#include "elf_writer_quick.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070062#include "gc/space/image_space.h"
63#include "gc/space/space-inl.h"
64#include "image_writer.h"
Andreas Gampe2969bcd2015-03-09 12:57:41 -070065#include "interpreter/unstarted_runtime.h"
Calin Juravle998c2162015-12-21 15:39:33 +020066#include "jit/offline_profiling_info.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070067#include "leb128.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070068#include "mirror/class-inl.h"
69#include "mirror/class_loader.h"
70#include "mirror/object-inl.h"
71#include "mirror/object_array-inl.h"
72#include "oat_writer.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070073#include "os.h"
Calin Juravle998c2162015-12-21 15:39:33 +020074#include "profile_assistant.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070075#include "runtime.h"
Vladimir Marko49b0f452015-12-10 13:49:19 +000076#include "runtime_options.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070077#include "ScopedLocalRef.h"
78#include "scoped_thread_state_change.h"
Alex Light53cb16b2014-06-12 11:26:29 -070079#include "utils.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070080#include "well_known_classes.h"
81#include "zip_archive.h"
82
83namespace art {
84
Brian Carlstrom6449c622014-02-10 23:48:36 -080085static int original_argc;
86static char** original_argv;
87
88static std::string CommandLine() {
89 std::vector<std::string> command;
90 for (int i = 0; i < original_argc; ++i) {
91 command.push_back(original_argv[i]);
92 }
93 return Join(command, ' ');
94}
95
Andreas Gampe046c7062015-05-18 23:22:54 -070096// A stripped version. Remove some less essential parameters. If we see a "--zip-fd=" parameter, be
97// even more aggressive. There won't be much reasonable data here for us in that case anyways (the
98// locations are all staged).
99static std::string StrippedCommandLine() {
100 std::vector<std::string> command;
101
102 // Do a pre-pass to look for zip-fd.
103 bool saw_zip_fd = false;
104 for (int i = 0; i < original_argc; ++i) {
105 if (StartsWith(original_argv[i], "--zip-fd=")) {
106 saw_zip_fd = true;
107 break;
108 }
109 }
110
111 // Now filter out things.
112 for (int i = 0; i < original_argc; ++i) {
113 // All runtime-arg parameters are dropped.
114 if (strcmp(original_argv[i], "--runtime-arg") == 0) {
115 i++; // Drop the next part, too.
116 continue;
117 }
118
119 // Any instruction-setXXX is dropped.
120 if (StartsWith(original_argv[i], "--instruction-set")) {
121 continue;
122 }
123
124 // The boot image is dropped.
125 if (StartsWith(original_argv[i], "--boot-image=")) {
126 continue;
127 }
128
129 // This should leave any dex-file and oat-file options, describing what we compiled.
130
131 // However, we prefer to drop this when we saw --zip-fd.
132 if (saw_zip_fd) {
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700133 // Drop anything --zip-X, --dex-X, --oat-X, --swap-X, or --app-image-X
Andreas Gampe046c7062015-05-18 23:22:54 -0700134 if (StartsWith(original_argv[i], "--zip-") ||
135 StartsWith(original_argv[i], "--dex-") ||
136 StartsWith(original_argv[i], "--oat-") ||
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700137 StartsWith(original_argv[i], "--swap-") ||
138 StartsWith(original_argv[i], "--app-image-")) {
Andreas Gampe046c7062015-05-18 23:22:54 -0700139 continue;
140 }
141 }
142
143 command.push_back(original_argv[i]);
144 }
145
146 // Construct the final output.
147 if (command.size() <= 1U) {
148 // It seems only "/system/bin/dex2oat" is left, or not even that. Use a pretty line.
149 return "Starting dex2oat.";
150 }
151 return Join(command, ' ');
152}
153
Brian Carlstrom7940e442013-07-12 13:46:57 -0700154static void UsageErrorV(const char* fmt, va_list ap) {
155 std::string error;
156 StringAppendV(&error, fmt, ap);
157 LOG(ERROR) << error;
158}
159
160static void UsageError(const char* fmt, ...) {
161 va_list ap;
162 va_start(ap, fmt);
163 UsageErrorV(fmt, ap);
164 va_end(ap);
165}
166
Andreas Gampe794ad762015-02-23 08:12:24 -0800167NO_RETURN static void Usage(const char* fmt, ...) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700168 va_list ap;
169 va_start(ap, fmt);
170 UsageErrorV(fmt, ap);
171 va_end(ap);
172
Brian Carlstrom6449c622014-02-10 23:48:36 -0800173 UsageError("Command: %s", CommandLine().c_str());
174
Brian Carlstrom7940e442013-07-12 13:46:57 -0700175 UsageError("Usage: dex2oat [options]...");
176 UsageError("");
Jean-Philippe Halimi3d329d72015-03-23 14:09:48 +0100177 UsageError(" -j<number>: specifies the number of threads used for compilation.");
178 UsageError(" Default is the number of detected hardware threads available on the");
179 UsageError(" host system.");
180 UsageError(" Example: -j12");
181 UsageError("");
Richard Uhlere934df22015-03-17 11:26:16 -0700182 UsageError(" --dex-file=<dex-file>: specifies a .dex, .jar, or .apk file to compile.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700183 UsageError(" Example: --dex-file=/system/framework/core.jar");
184 UsageError("");
Richard Uhlere934df22015-03-17 11:26:16 -0700185 UsageError(" --dex-location=<dex-location>: specifies an alternative dex location to");
186 UsageError(" encode in the oat file for the corresponding --dex-file argument.");
187 UsageError(" Example: --dex-file=/home/build/out/system/framework/core.jar");
188 UsageError(" --dex-location=/system/framework/core.jar");
189 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700190 UsageError(" --zip-fd=<file-descriptor>: specifies a file descriptor of a zip file");
191 UsageError(" containing a classes.dex file to compile.");
192 UsageError(" Example: --zip-fd=5");
193 UsageError("");
Brian Carlstrom45602482013-07-21 22:07:55 -0700194 UsageError(" --zip-location=<zip-location>: specifies a symbolic name for the file");
195 UsageError(" corresponding to the file descriptor specified by --zip-fd.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700196 UsageError(" Example: --zip-location=/system/app/Calculator.apk");
197 UsageError("");
Jeff Haodcdc85b2015-12-04 14:06:18 -0800198 UsageError(" --oat-file=<file.oat>: specifies an oat output destination via a filename.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700199 UsageError(" Example: --oat-file=/system/framework/boot.oat");
200 UsageError("");
201 UsageError(" --oat-fd=<number>: specifies the oat output destination via a file descriptor.");
Wonil Kim9cb554a2014-04-28 11:26:55 +0900202 UsageError(" Example: --oat-fd=6");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700203 UsageError("");
204 UsageError(" --oat-location=<oat-name>: specifies a symbolic name for the file corresponding");
205 UsageError(" to the file descriptor specified by --oat-fd.");
206 UsageError(" Example: --oat-location=/data/dalvik-cache/system@app@Calculator.apk.oat");
207 UsageError("");
Jeff Haodcdc85b2015-12-04 14:06:18 -0800208 UsageError(" --oat-symbols=<file.oat>: specifies an oat output destination with full symbols.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700209 UsageError(" Example: --oat-symbols=/symbols/system/framework/boot.oat");
210 UsageError("");
Jeff Haodcdc85b2015-12-04 14:06:18 -0800211 UsageError(" --image=<file.art>: specifies an output image filename.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700212 UsageError(" Example: --image=/system/framework/boot.art");
213 UsageError("");
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800214 UsageError(" --image-format=(uncompressed|lz4):");
215 UsageError(" Which format to store the image.");
216 UsageError(" Example: --image-format=lz4");
217 UsageError(" Default: uncompressed");
218 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700219 UsageError(" --image-classes=<classname-file>: specifies classes to include in an image.");
220 UsageError(" Example: --image=frameworks/base/preloaded-classes");
221 UsageError("");
222 UsageError(" --base=<hex-address>: specifies the base address when creating a boot image.");
223 UsageError(" Example: --base=0x50000000");
224 UsageError("");
225 UsageError(" --boot-image=<file.art>: provide the image file for the boot class path.");
Kevin Brodsky64fff412015-11-24 14:24:34 +0000226 UsageError(" Do not include the arch as part of the name, it is added automatically.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700227 UsageError(" Example: --boot-image=/system/framework/boot.art");
Kevin Brodsky64fff412015-11-24 14:24:34 +0000228 UsageError(" (specifies /system/framework/<arch>/boot.art as the image file)");
Nicolas Geoffray9583fbc2014-02-28 15:21:07 +0000229 UsageError(" Default: $ANDROID_ROOT/system/framework/boot.art");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700230 UsageError("");
231 UsageError(" --android-root=<path>: used to locate libraries for portable linking.");
232 UsageError(" Example: --android-root=out/host/linux-x86");
233 UsageError(" Default: $ANDROID_ROOT");
234 UsageError("");
Andreas Gampe57b34292015-01-14 15:45:59 -0800235 UsageError(" --instruction-set=(arm|arm64|mips|mips64|x86|x86_64): compile for a particular");
Alex Light53cb16b2014-06-12 11:26:29 -0700236 UsageError(" instruction set.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700237 UsageError(" Example: --instruction-set=x86");
238 UsageError(" Default: arm");
239 UsageError("");
Dave Allison70202782013-10-22 17:52:19 -0700240 UsageError(" --instruction-set-features=...,: Specify instruction set features");
241 UsageError(" Example: --instruction-set-features=div");
242 UsageError(" Default: default");
243 UsageError("");
Igor Murashkin46774762014-10-22 11:37:02 -0700244 UsageError(" --compile-pic: Force indirect use of code, methods, and classes");
245 UsageError(" Default: disabled");
246 UsageError("");
Elliott Hughes956af0f2014-12-11 14:34:28 -0800247 UsageError(" --compiler-backend=(Quick|Optimizing): select compiler backend");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700248 UsageError(" set.");
Elliott Hughes956af0f2014-12-11 14:34:28 -0800249 UsageError(" Example: --compiler-backend=Optimizing");
Nicolas Geoffray409e8092015-10-01 10:32:19 +0100250 UsageError(" Default: Optimizing");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700251 UsageError("");
Nicolas Geoffray88157ef2014-09-12 10:29:53 +0100252 UsageError(" --compiler-filter="
253 "(verify-none"
254 "|interpret-only"
255 "|space"
256 "|balanced"
257 "|speed"
258 "|everything"
259 "|time):");
Jeff Hao4a200f52014-04-01 14:58:49 -0700260 UsageError(" select compiler filter.");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800261 UsageError(" Example: --compiler-filter=everything");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800262 UsageError(" Default: speed");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800263 UsageError("");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800264 UsageError(" --huge-method-max=<method-instruction-count>: threshold size for a huge");
265 UsageError(" method for compiler filter tuning.");
266 UsageError(" Example: --huge-method-max=%d", CompilerOptions::kDefaultHugeMethodThreshold);
267 UsageError(" Default: %d", CompilerOptions::kDefaultHugeMethodThreshold);
268 UsageError("");
269 UsageError(" --large-method-max=<method-instruction-count>: threshold size for a large");
270 UsageError(" method for compiler filter tuning.");
271 UsageError(" Example: --large-method-max=%d", CompilerOptions::kDefaultLargeMethodThreshold);
272 UsageError(" Default: %d", CompilerOptions::kDefaultLargeMethodThreshold);
273 UsageError("");
274 UsageError(" --small-method-max=<method-instruction-count>: threshold size for a small");
275 UsageError(" method for compiler filter tuning.");
276 UsageError(" Example: --small-method-max=%d", CompilerOptions::kDefaultSmallMethodThreshold);
277 UsageError(" Default: %d", CompilerOptions::kDefaultSmallMethodThreshold);
278 UsageError("");
279 UsageError(" --tiny-method-max=<method-instruction-count>: threshold size for a tiny");
280 UsageError(" method for compiler filter tuning.");
281 UsageError(" Example: --tiny-method-max=%d", CompilerOptions::kDefaultTinyMethodThreshold);
282 UsageError(" Default: %d", CompilerOptions::kDefaultTinyMethodThreshold);
283 UsageError("");
284 UsageError(" --num-dex-methods=<method-count>: threshold size for a small dex file for");
285 UsageError(" compiler filter tuning. If the input has fewer than this many methods");
Jeff Hao4a200f52014-04-01 14:58:49 -0700286 UsageError(" and the filter is not interpret-only or verify-none, overrides the");
287 UsageError(" filter to use speed");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800288 UsageError(" Example: --num-dex-method=%d", CompilerOptions::kDefaultNumDexMethodsThreshold);
289 UsageError(" Default: %d", CompilerOptions::kDefaultNumDexMethodsThreshold);
290 UsageError("");
Calin Juravleec748352015-07-29 13:52:12 +0100291 UsageError(" --inline-depth-limit=<depth-limit>: the depth limit of inlining for fine tuning");
292 UsageError(" the compiler. A zero value will disable inlining. Honored only by Optimizing.");
Roland Levillaina215b952015-08-07 11:38:32 +0100293 UsageError(" Has priority over the --compiler-filter option. Intended for ");
294 UsageError(" development/experimental use.");
Calin Juravleec748352015-07-29 13:52:12 +0100295 UsageError(" Example: --inline-depth-limit=%d", CompilerOptions::kDefaultInlineDepthLimit);
296 UsageError(" Default: %d", CompilerOptions::kDefaultInlineDepthLimit);
297 UsageError("");
298 UsageError(" --inline-max-code-units=<code-units-count>: the maximum code units that a method");
299 UsageError(" can have to be considered for inlining. A zero value will disable inlining.");
Roland Levillaina215b952015-08-07 11:38:32 +0100300 UsageError(" Honored only by Optimizing. Has priority over the --compiler-filter option.");
301 UsageError(" Intended for development/experimental use.");
Calin Juravleec748352015-07-29 13:52:12 +0100302 UsageError(" Example: --inline-max-code-units=%d",
303 CompilerOptions::kDefaultInlineMaxCodeUnits);
304 UsageError(" Default: %d", CompilerOptions::kDefaultInlineMaxCodeUnits);
305 UsageError("");
Ian Rogers46398602013-08-20 07:50:36 -0700306 UsageError(" --dump-timing: display a breakdown of where time was spent");
307 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700308 UsageError(" --include-patch-information: Include patching information so the generated code");
309 UsageError(" can have its base address moved without full recompilation.");
310 UsageError("");
311 UsageError(" --no-include-patch-information: Do not include patching information.");
312 UsageError("");
David Srbecky8363c772015-05-28 16:12:43 +0100313 UsageError(" -g");
314 UsageError(" --generate-debug-info: Generate debug information for native debugging,");
315 UsageError(" such as stack unwinding information, ELF symbols and DWARF sections.");
David Srbecky3e09eeb2016-01-12 14:54:03 +0000316 UsageError(" If used without --native-debuggable, it will be best-effort only.");
317 UsageError(" This option does not affect the generated code. (disabled by default)");
Alex Light78382fa2014-06-06 15:45:32 -0700318 UsageError("");
David Srbecky8363c772015-05-28 16:12:43 +0100319 UsageError(" --no-generate-debug-info: Do not generate debug information for native debugging.");
David Srbecky8dc73242015-04-12 11:40:39 +0100320 UsageError("");
David Srbecky3e09eeb2016-01-12 14:54:03 +0000321 UsageError(" --debuggable: Produce code debuggable with Java debugger.");
David Srbecky0cf44932015-12-09 14:09:59 +0000322 UsageError("");
323 UsageError(" --native-debuggable: Produce code debuggable with native debugger (like LLDB).");
324 UsageError(" Implies --debuggable.");
325 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700326 UsageError(" --runtime-arg <argument>: used to specify various arguments for the runtime,");
327 UsageError(" such as initial heap size, maximum heap size, and verbose output.");
328 UsageError(" Use a separate --runtime-arg switch for each argument.");
329 UsageError(" Example: --runtime-arg -Xms256m");
Jeff Hao4a200f52014-04-01 14:58:49 -0700330 UsageError("");
Dave Allisond6ed6422014-04-09 23:36:15 +0000331 UsageError(" --profile-file=<filename>: specify profiler output file to use for compilation.");
Calin Juravle998c2162015-12-21 15:39:33 +0200332 UsageError(" Can be specified multiple time, in which case the data from the different");
333 UsageError(" profiles will be aggregated.");
334 UsageError("");
335 UsageError(" --reference-profile-file=<filename>: specify a reference profile file to use when");
336 UsageError(" compiling. The data in this file will be compared with the data in the");
337 UsageError(" associated --profile-file and the compilation will proceed only if there is");
338 UsageError(" a significant difference (--reference-profile-file is paired with");
339 UsageError(" --profile-file in the natural order). If the compilation was attempted then");
340 UsageError(" --profile-file will be merged into --reference-profile-file. Valid only when");
341 UsageError(" specified together with --profile-file.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700342 UsageError("");
Chao-ying Fucd8ce662014-03-11 14:57:19 -0700343 UsageError(" --print-pass-names: print a list of pass names");
344 UsageError("");
345 UsageError(" --disable-passes=<pass-names>: disable one or more passes separated by comma.");
346 UsageError(" Example: --disable-passes=UseCount,BBOptimizations");
347 UsageError("");
Razvan A Lupusorubd25d4b2014-07-02 18:16:51 -0700348 UsageError(" --print-pass-options: print a list of passes that have configurable options along "
349 "with the setting.");
350 UsageError(" Will print default if no overridden setting exists.");
351 UsageError("");
352 UsageError(" --pass-options=Pass1Name:Pass1OptionName:Pass1Option#,"
353 "Pass2Name:Pass2OptionName:Pass2Option#");
354 UsageError(" Used to specify a pass specific option. The setting itself must be integer.");
355 UsageError(" Separator used between options is a comma.");
356 UsageError("");
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800357 UsageError(" --swap-file=<file-name>: specifies a file to use for swap.");
358 UsageError(" Example: --swap-file=/data/tmp/swap.001");
359 UsageError("");
360 UsageError(" --swap-fd=<file-descriptor>: specifies a file to use for swap (by descriptor).");
361 UsageError(" Example: --swap-fd=10");
362 UsageError("");
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700363 UsageError(" --app-image-fd=<file-descriptor>: specify output file descriptor for app image.");
364 UsageError(" Example: --app-image-fd=10");
365 UsageError("");
366 UsageError(" --app-image-file=<file-name>: specify a file name for app image.");
367 UsageError(" Example: --app-image-file=/data/dalvik-cache/system@app@Calculator.apk.art");
368 UsageError("");
Jeff Haodcdc85b2015-12-04 14:06:18 -0800369 UsageError(" --multi-image: specify that separate oat and image files be generated for each "
370 "input dex file.");
371 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700372 std::cerr << "See log for usage error information\n";
373 exit(EXIT_FAILURE);
374}
375
Brian Carlstrom7940e442013-07-12 13:46:57 -0700376// The primary goal of the watchdog is to prevent stuck build servers
377// during development when fatal aborts lead to a cascade of failures
378// that result in a deadlock.
379class WatchDog {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800380// WatchDog defines its own CHECK_PTHREAD_CALL to avoid using LOG which uses locks
Brian Carlstrom7940e442013-07-12 13:46:57 -0700381#undef CHECK_PTHREAD_CALL
382#define CHECK_WATCH_DOG_PTHREAD_CALL(call, args, what) \
383 do { \
384 int rc = call args; \
385 if (rc != 0) { \
386 errno = rc; \
387 std::string message(# call); \
388 message += " failed for "; \
389 message += reason; \
390 Fatal(message); \
391 } \
392 } while (false)
393
394 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -0700395 explicit WatchDog(bool is_watch_dog_enabled) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700396 is_watch_dog_enabled_ = is_watch_dog_enabled;
397 if (!is_watch_dog_enabled_) {
398 return;
399 }
400 shutting_down_ = false;
401 const char* reason = "dex2oat watch dog thread startup";
Kenny Root51316382014-05-13 14:59:37 -0700402 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_init, (&mutex_, nullptr), reason);
403 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_init, (&cond_, nullptr), reason);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700404 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_init, (&attr_), reason);
405 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_create, (&pthread_, &attr_, &CallBack, this), reason);
406 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_destroy, (&attr_), reason);
407 }
408 ~WatchDog() {
409 if (!is_watch_dog_enabled_) {
410 return;
411 }
412 const char* reason = "dex2oat watch dog thread shutdown";
413 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
414 shutting_down_ = true;
415 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_signal, (&cond_), reason);
416 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
417
Kenny Root51316382014-05-13 14:59:37 -0700418 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_join, (pthread_, nullptr), reason);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700419
420 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_destroy, (&cond_), reason);
421 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_destroy, (&mutex_), reason);
422 }
423
424 private:
425 static void* CallBack(void* arg) {
426 WatchDog* self = reinterpret_cast<WatchDog*>(arg);
427 ::art::SetThreadName("dex2oat watch dog");
428 self->Wait();
Kenny Root51316382014-05-13 14:59:37 -0700429 return nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700430 }
431
Andreas Gampe794ad762015-02-23 08:12:24 -0800432 NO_RETURN static void Fatal(const std::string& message) {
Andreas Gamped687e372015-04-28 23:16:03 -0700433 // TODO: When we can guarantee it won't prevent shutdown in error cases, move to LOG. However,
434 // it's rather easy to hang in unwinding.
435 // LogLine also avoids ART logging lock issues, as it's really only a wrapper around
436 // logcat logging or stderr output.
437 LogMessage::LogLine(__FILE__, __LINE__, LogSeverity::FATAL, message.c_str());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700438 exit(1);
439 }
440
441 void Wait() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700442 // TODO: tune the multiplier for GC verification, the following is just to make the timeout
443 // large.
Andreas Gamped687e372015-04-28 23:16:03 -0700444 constexpr int64_t multiplier = kVerifyObjectSupport > kVerifyObjectModeFast ? 100 : 1;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700445 timespec timeout_ts;
446 InitTimeSpec(true, CLOCK_REALTIME, multiplier * kWatchDogTimeoutSeconds * 1000, 0, &timeout_ts);
447 const char* reason = "dex2oat watch dog thread waiting";
448 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
449 while (!shutting_down_) {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800450 int rc = TEMP_FAILURE_RETRY(pthread_cond_timedwait(&cond_, &mutex_, &timeout_ts));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700451 if (rc == ETIMEDOUT) {
Andreas Gamped687e372015-04-28 23:16:03 -0700452 Fatal(StringPrintf("dex2oat did not finish after %" PRId64 " seconds",
453 kWatchDogTimeoutSeconds));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700454 } else if (rc != 0) {
455 std::string message(StringPrintf("pthread_cond_timedwait failed: %s",
456 strerror(errno)));
457 Fatal(message.c_str());
458 }
459 }
460 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
461 }
462
463 // 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 -0700464 // Debug builds are slower so they have larger timeouts.
Andreas Gamped687e372015-04-28 23:16:03 -0700465 static constexpr int64_t kSlowdownFactor = kIsDebugBuild ? 5U : 1U;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800466
Andreas Gampe540138a2015-09-14 15:34:38 -0700467 // 9.5 minutes scaled by kSlowdownFactor. This is slightly smaller than the Package Manager
468 // watchdog (PackageManagerService.WATCHDOG_TIMEOUT, 10 minutes), so that dex2oat will abort
469 // itself before that watchdog would take down the system server.
470 static constexpr int64_t kWatchDogTimeoutSeconds = kSlowdownFactor * (9 * 60 + 30);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700471
472 bool is_watch_dog_enabled_;
473 bool shutting_down_;
474 // TODO: Switch to Mutex when we can guarantee it won't prevent shutdown in error cases.
475 pthread_mutex_t mutex_;
476 pthread_cond_t cond_;
477 pthread_attr_t attr_;
478 pthread_t pthread_;
479};
Brian Carlstrom7940e442013-07-12 13:46:57 -0700480
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800481static constexpr size_t kMinDexFilesForSwap = 2;
482static constexpr size_t kMinDexFileCumulativeSizeForSwap = 20 * MB;
483
484static bool UseSwap(bool is_image, std::vector<const DexFile*>& dex_files) {
485 if (is_image) {
486 // Don't use swap, we know generation should succeed, and we don't want to slow it down.
487 return false;
488 }
489 if (dex_files.size() < kMinDexFilesForSwap) {
490 // If there are less dex files than the threshold, assume it's gonna be fine.
491 return false;
492 }
493 size_t dex_files_size = 0;
494 for (const auto* dex_file : dex_files) {
495 dex_files_size += dex_file->GetHeader().file_size_;
496 }
497 return dex_files_size >= kMinDexFileCumulativeSizeForSwap;
498}
499
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800500class Dex2Oat FINAL {
501 public:
502 explicit Dex2Oat(TimingLogger* timings) :
Nicolas Geoffray409e8092015-10-01 10:32:19 +0100503 compiler_kind_(Compiler::kOptimizing),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800504 instruction_set_(kRuntimeISA),
505 // Take the default set of instruction features from the build.
Andreas Gampe3f30e122015-09-17 14:03:21 -0700506 verification_results_(nullptr),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800507 method_inliner_map_(),
508 runtime_(nullptr),
509 thread_count_(sysconf(_SC_NPROCESSORS_CONF)),
510 start_ns_(NanoTime()),
511 oat_fd_(-1),
512 zip_fd_(-1),
513 image_base_(0U),
514 image_classes_zip_filename_(nullptr),
515 image_classes_filename_(nullptr),
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800516 image_storage_mode_(ImageHeader::kStorageModeUncompressed),
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800517 compiled_classes_zip_filename_(nullptr),
518 compiled_classes_filename_(nullptr),
Andreas Gampe70bef0d2015-04-15 02:37:28 -0700519 compiled_methods_zip_filename_(nullptr),
520 compiled_methods_filename_(nullptr),
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700521 app_image_(false),
522 boot_image_(false),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800523 is_host_(false),
Vladimir Marko10c13562015-11-25 14:33:36 +0000524 image_writer_(nullptr),
Andreas Gampe3f30e122015-09-17 14:03:21 -0700525 driver_(nullptr),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800526 dump_stats_(false),
527 dump_passes_(false),
528 dump_timing_(false),
529 dump_slow_timing_(kIsDebugBuild),
Calin Juravle87000a92015-08-24 15:34:44 +0100530 dump_cfg_append_(false),
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800531 swap_fd_(-1),
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700532 app_image_fd_(kInvalidImageFd),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800533 timings_(timings) {}
534
535 ~Dex2Oat() {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800536 // Free opened dex files before deleting the runtime_, because ~DexFile
537 // uses MemMap, which is shut down by ~Runtime.
538 class_path_files_.clear();
539 opened_dex_files_.clear();
540
541 // Log completion time before deleting the runtime_, because this accesses
542 // the runtime.
543 LogCompletionTime();
544
Vladimir Marko307dac92015-10-20 11:20:09 +0100545 if (!kIsDebugBuild && !(RUNNING_ON_MEMORY_TOOL && kMemoryToolDetectsLeaks)) {
546 // We want to just exit on non-debug builds, not bringing the runtime down
547 // in an orderly fashion. So release the following fields.
548 driver_.release();
549 image_writer_.release();
550 for (std::unique_ptr<const DexFile>& dex_file : opened_dex_files_) {
551 dex_file.release();
552 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800553 for (std::unique_ptr<File>& oat_file : oat_files_) {
554 oat_file.release();
555 }
Vladimir Marko307dac92015-10-20 11:20:09 +0100556 runtime_.release();
557 verification_results_.release();
558 key_value_store_.release();
Vladimir Markof94b7812014-06-05 15:48:04 +0100559 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700560 }
561
Roland Levillain9ec5e222015-08-17 20:18:41 +0100562 struct ParserOptions {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800563 std::vector<const char*> oat_symbols;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800564 std::string boot_image_filename;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800565 bool watch_dog_enabled = true;
Nicolas Geoffray1412dfa2015-03-20 14:48:13 +0000566 bool requested_specific_compiler = false;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800567 std::string error_msg;
Roland Levillain9ec5e222015-08-17 20:18:41 +0100568 };
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800569
Roland Levillain9ec5e222015-08-17 20:18:41 +0100570 void ParseZipFd(const StringPiece& option) {
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000571 ParseUintOption(option, "--zip-fd", &zip_fd_, Usage);
Roland Levillain9ec5e222015-08-17 20:18:41 +0100572 }
573
574 void ParseOatFd(const StringPiece& option) {
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000575 ParseUintOption(option, "--oat-fd", &oat_fd_, Usage);
Roland Levillain9ec5e222015-08-17 20:18:41 +0100576 }
577
578 void ParseJ(const StringPiece& option) {
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000579 ParseUintOption(option, "-j", &thread_count_, Usage, /* is_long_option */ false);
Roland Levillain9ec5e222015-08-17 20:18:41 +0100580 }
581
582 void ParseBase(const StringPiece& option) {
583 DCHECK(option.starts_with("--base="));
584 const char* image_base_str = option.substr(strlen("--base=")).data();
585 char* end;
586 image_base_ = strtoul(image_base_str, &end, 16);
587 if (end == image_base_str || *end != '\0') {
588 Usage("Failed to parse hexadecimal value for option %s", option.data());
589 }
590 }
591
592 void ParseInstructionSet(const StringPiece& option) {
593 DCHECK(option.starts_with("--instruction-set="));
594 StringPiece instruction_set_str = option.substr(strlen("--instruction-set=")).data();
595 // StringPiece is not necessarily zero-terminated, so need to make a copy and ensure it.
596 std::unique_ptr<char[]> buf(new char[instruction_set_str.length() + 1]);
597 strncpy(buf.get(), instruction_set_str.data(), instruction_set_str.length());
598 buf.get()[instruction_set_str.length()] = 0;
599 instruction_set_ = GetInstructionSetFromString(buf.get());
600 // arm actually means thumb2.
601 if (instruction_set_ == InstructionSet::kArm) {
602 instruction_set_ = InstructionSet::kThumb2;
603 }
604 }
605
606 void ParseInstructionSetVariant(const StringPiece& option, ParserOptions* parser_options) {
607 DCHECK(option.starts_with("--instruction-set-variant="));
608 StringPiece str = option.substr(strlen("--instruction-set-variant=")).data();
609 instruction_set_features_.reset(
610 InstructionSetFeatures::FromVariant(
611 instruction_set_, str.as_string(), &parser_options->error_msg));
612 if (instruction_set_features_.get() == nullptr) {
613 Usage("%s", parser_options->error_msg.c_str());
614 }
615 }
616
617 void ParseInstructionSetFeatures(const StringPiece& option, ParserOptions* parser_options) {
618 DCHECK(option.starts_with("--instruction-set-features="));
619 StringPiece str = option.substr(strlen("--instruction-set-features=")).data();
620 if (instruction_set_features_.get() == nullptr) {
621 instruction_set_features_.reset(
622 InstructionSetFeatures::FromVariant(
623 instruction_set_, "default", &parser_options->error_msg));
624 if (instruction_set_features_.get() == nullptr) {
625 Usage("Problem initializing default instruction set features variant: %s",
626 parser_options->error_msg.c_str());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700627 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800628 }
Roland Levillain9ec5e222015-08-17 20:18:41 +0100629 instruction_set_features_.reset(
630 instruction_set_features_->AddFeaturesFromString(str.as_string(),
631 &parser_options->error_msg));
632 if (instruction_set_features_.get() == nullptr) {
633 Usage("Error parsing '%s': %s", option.data(), parser_options->error_msg.c_str());
634 }
635 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800636
Roland Levillain9ec5e222015-08-17 20:18:41 +0100637 void ParseCompilerBackend(const StringPiece& option, ParserOptions* parser_options) {
638 DCHECK(option.starts_with("--compiler-backend="));
639 parser_options->requested_specific_compiler = true;
640 StringPiece backend_str = option.substr(strlen("--compiler-backend=")).data();
641 if (backend_str == "Quick") {
642 compiler_kind_ = Compiler::kQuick;
643 } else if (backend_str == "Optimizing") {
644 compiler_kind_ = Compiler::kOptimizing;
645 } else {
646 Usage("Unknown compiler backend: %s", backend_str.data());
647 }
648 }
649
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800650 void ParseImageFormat(const StringPiece& option) {
651 const StringPiece substr("--image-format=");
652 DCHECK(option.starts_with(substr));
653 const StringPiece format_str = option.substr(substr.length());
654 if (format_str == "lz4") {
655 image_storage_mode_ = ImageHeader::kStorageModeLZ4;
656 } else if (format_str == "uncompressed") {
657 image_storage_mode_ = ImageHeader::kStorageModeUncompressed;
658 } else {
659 Usage("Unknown image format: %s", format_str.data());
660 }
661 }
662
Jeff Haodcdc85b2015-12-04 14:06:18 -0800663 void ProcessOptions(ParserOptions* parser_options, bool multi_image) {
664 boot_image_ = !image_filenames_.empty();
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700665 app_image_ = app_image_fd_ != -1 || !app_image_file_name_.empty();
666
667 if (IsAppImage() && IsBootImage()) {
668 Usage("Can't have both --image and (--app-image-fd or --app-image-file)");
669 }
670
671 if (IsBootImage()) {
Nicolas Geoffray409e8092015-10-01 10:32:19 +0100672 // We need the boot image to always be debuggable.
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000673 compiler_options_->debuggable_ = true;
Nicolas Geoffray1412dfa2015-03-20 14:48:13 +0000674 }
Nicolas Geoffray9bb492a2014-11-25 23:42:00 +0000675
Jeff Haodcdc85b2015-12-04 14:06:18 -0800676 if (oat_filenames_.empty() && oat_fd_ == -1) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800677 Usage("Output must be supplied with either --oat-file or --oat-fd");
678 }
679
Jeff Haodcdc85b2015-12-04 14:06:18 -0800680 if (!oat_filenames_.empty() && oat_fd_ != -1) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800681 Usage("--oat-file should not be used with --oat-fd");
682 }
683
Roland Levillain9ec5e222015-08-17 20:18:41 +0100684 if (!parser_options->oat_symbols.empty() && oat_fd_ != -1) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800685 Usage("--oat-symbols should not be used with --oat-fd");
686 }
687
Roland Levillain9ec5e222015-08-17 20:18:41 +0100688 if (!parser_options->oat_symbols.empty() && is_host_) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800689 Usage("--oat-symbols should not be used with --host");
690 }
691
Jeff Haodcdc85b2015-12-04 14:06:18 -0800692 if (oat_fd_ != -1 && !image_filenames_.empty()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800693 Usage("--oat-fd should not be used with --image");
694 }
695
Jeff Haodcdc85b2015-12-04 14:06:18 -0800696 if (!parser_options->oat_symbols.empty() &&
697 parser_options->oat_symbols.size() != oat_filenames_.size()) {
698 Usage("--oat-file arguments do not match --oat-symbols arguments");
699 }
700
701 if (!image_filenames_.empty() && image_filenames_.size() != oat_filenames_.size()) {
702 Usage("--oat-file arguments do not match --image arguments");
703 }
704
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800705 if (android_root_.empty()) {
706 const char* android_root_env_var = getenv("ANDROID_ROOT");
707 if (android_root_env_var == nullptr) {
708 Usage("--android-root unspecified and ANDROID_ROOT not set");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700709 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800710 android_root_ += android_root_env_var;
711 }
712
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700713 if (!boot_image_ && parser_options->boot_image_filename.empty()) {
Roland Levillain9ec5e222015-08-17 20:18:41 +0100714 parser_options->boot_image_filename += android_root_;
715 parser_options->boot_image_filename += "/framework/boot.art";
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800716 }
Roland Levillain9ec5e222015-08-17 20:18:41 +0100717 if (!parser_options->boot_image_filename.empty()) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000718 boot_image_filename_ = parser_options->boot_image_filename;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800719 }
720
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700721 if (image_classes_filename_ != nullptr && !IsBootImage()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800722 Usage("--image-classes should only be used with --image");
723 }
724
Vladimir Marko49b0f452015-12-10 13:49:19 +0000725 if (image_classes_filename_ != nullptr && !boot_image_filename_.empty()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800726 Usage("--image-classes should not be used with --boot-image");
727 }
728
729 if (image_classes_zip_filename_ != nullptr && image_classes_filename_ == nullptr) {
730 Usage("--image-classes-zip should be used with --image-classes");
731 }
732
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700733 if (compiled_classes_filename_ != nullptr && !IsBootImage()) {
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800734 Usage("--compiled-classes should only be used with --image");
735 }
736
Vladimir Marko49b0f452015-12-10 13:49:19 +0000737 if (compiled_classes_filename_ != nullptr && !boot_image_filename_.empty()) {
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800738 Usage("--compiled-classes should not be used with --boot-image");
739 }
740
741 if (compiled_classes_zip_filename_ != nullptr && compiled_classes_filename_ == nullptr) {
742 Usage("--compiled-classes-zip should be used with --compiled-classes");
743 }
744
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800745 if (dex_filenames_.empty() && zip_fd_ == -1) {
746 Usage("Input must be supplied with either --dex-file or --zip-fd");
747 }
748
749 if (!dex_filenames_.empty() && zip_fd_ != -1) {
750 Usage("--dex-file should not be used with --zip-fd");
751 }
752
753 if (!dex_filenames_.empty() && !zip_location_.empty()) {
754 Usage("--dex-file should not be used with --zip-location");
755 }
756
757 if (dex_locations_.empty()) {
758 for (const char* dex_file_name : dex_filenames_) {
759 dex_locations_.push_back(dex_file_name);
760 }
761 } else if (dex_locations_.size() != dex_filenames_.size()) {
762 Usage("--dex-location arguments do not match --dex-file arguments");
763 }
764
Jeff Haodcdc85b2015-12-04 14:06:18 -0800765 if (!dex_filenames_.empty() && !oat_filenames_.empty()) {
766 if (oat_filenames_.size() != 1 && oat_filenames_.size() != dex_filenames_.size()) {
767 Usage("--oat-file arguments must be singular or match --dex-file arguments");
768 }
769 }
770
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800771 if (zip_fd_ != -1 && zip_location_.empty()) {
772 Usage("--zip-location should be supplied with --zip-fd");
773 }
774
Vladimir Marko49b0f452015-12-10 13:49:19 +0000775 if (boot_image_filename_.empty()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800776 if (image_base_ == 0) {
777 Usage("Non-zero --base not specified");
778 }
779 }
780
Calin Juravle998c2162015-12-21 15:39:33 +0200781 if (!profile_files_.empty()) {
782 if (!reference_profile_files_.empty() &&
783 (reference_profile_files_.size() != profile_files_.size())) {
784 Usage("If specified, --reference-profile-file should match the number of --profile-file.");
785 }
786 }
787
Roland Levillain9ec5e222015-08-17 20:18:41 +0100788 if (!parser_options->oat_symbols.empty()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800789 oat_unstripped_ = std::move(parser_options->oat_symbols);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800790 }
791
792 // If no instruction set feature was given, use the default one for the target
793 // instruction set.
794 if (instruction_set_features_.get() == nullptr) {
795 instruction_set_features_.reset(
Roland Levillain9ec5e222015-08-17 20:18:41 +0100796 InstructionSetFeatures::FromVariant(
797 instruction_set_, "default", &parser_options->error_msg));
Ian Rogersd582fa42014-11-05 23:46:43 -0800798 if (instruction_set_features_.get() == nullptr) {
799 Usage("Problem initializing default instruction set features variant: %s",
Roland Levillain9ec5e222015-08-17 20:18:41 +0100800 parser_options->error_msg.c_str());
Ian Rogersd582fa42014-11-05 23:46:43 -0800801 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800802 }
803
804 if (instruction_set_ == kRuntimeISA) {
805 std::unique_ptr<const InstructionSetFeatures> runtime_features(
806 InstructionSetFeatures::FromCppDefines());
807 if (!instruction_set_features_->Equals(runtime_features.get())) {
808 LOG(WARNING) << "Mismatch between dex2oat instruction set features ("
809 << *instruction_set_features_ << ") and those of dex2oat executable ("
810 << *runtime_features <<") for the command line:\n"
811 << CommandLine();
812 }
813 }
814
Roland Levillaina215b952015-08-07 11:38:32 +0100815 // It they are not set, use default values for inlining settings.
816 // TODO: We should rethink the compiler filter. We mostly save
817 // time here, which is orthogonal to space.
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000818 if (compiler_options_->inline_depth_limit_ == CompilerOptions::kUnsetInlineDepthLimit) {
819 compiler_options_->inline_depth_limit_ =
820 (compiler_options_->compiler_filter_ == CompilerOptions::kSpace)
Roland Levillaina215b952015-08-07 11:38:32 +0100821 // Implementation of the space filter: limit inlining depth.
822 ? CompilerOptions::kSpaceFilterInlineDepthLimit
823 : CompilerOptions::kDefaultInlineDepthLimit;
824 }
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000825 if (compiler_options_->inline_max_code_units_ == CompilerOptions::kUnsetInlineMaxCodeUnits) {
826 compiler_options_->inline_max_code_units_ =
827 (compiler_options_->compiler_filter_ == CompilerOptions::kSpace)
Roland Levillaina215b952015-08-07 11:38:32 +0100828 // Implementation of the space filter: limit inlining max code units.
829 ? CompilerOptions::kSpaceFilterInlineMaxCodeUnits
830 : CompilerOptions::kDefaultInlineMaxCodeUnits;
831 }
832
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800833 // Checks are all explicit until we know the architecture.
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800834 // Set the compilation target's implicit checks options.
835 switch (instruction_set_) {
836 case kArm:
837 case kThumb2:
838 case kArm64:
839 case kX86:
840 case kX86_64:
Douglas Leung22bb5a22015-07-02 16:42:08 -0700841 case kMips:
842 case kMips64:
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000843 compiler_options_->implicit_null_checks_ = true;
844 compiler_options_->implicit_so_checks_ = true;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800845 break;
846
847 default:
848 // Defaults are correct.
849 break;
850 }
851
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000852 compiler_options_->verbose_methods_ = verbose_methods_.empty() ? nullptr : &verbose_methods_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800853
Jeff Haodcdc85b2015-12-04 14:06:18 -0800854 if (!IsBootImage() && multi_image) {
855 Usage("--multi-image can only be used when creating boot images");
856 }
857 if (IsBootImage() && multi_image && image_filenames_.size() > 1) {
858 Usage("--multi-image cannot be used with multiple image names");
859 }
860
861 // For now, if we're on the host and compile the boot image, *always* use multiple image files.
862 if (!kIsTargetBuild && IsBootImage()) {
863 if (image_filenames_.size() == 1) {
864 multi_image = true;
865 }
866 }
867
868 if (IsBootImage() && multi_image) {
869 // Expand the oat and image filenames.
870 std::string base_oat = oat_filenames_[0];
871 size_t last_oat_slash = base_oat.rfind('/');
872 if (last_oat_slash == std::string::npos) {
873 Usage("--multi-image used with unusable oat filename %s", base_oat.c_str());
874 }
Andreas Gampe8994a042015-12-30 19:03:17 +0000875 // We also need to honor path components that were encoded through '@'. Otherwise the loading
876 // code won't be able to find the images.
877 if (base_oat.find('@', last_oat_slash) != std::string::npos) {
878 last_oat_slash = base_oat.rfind('@');
879 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800880 base_oat = base_oat.substr(0, last_oat_slash + 1);
881
882 std::string base_img = image_filenames_[0];
883 size_t last_img_slash = base_img.rfind('/');
884 if (last_img_slash == std::string::npos) {
885 Usage("--multi-image used with unusable image filename %s", base_img.c_str());
886 }
Andreas Gampe8994a042015-12-30 19:03:17 +0000887 // We also need to honor path components that were encoded through '@'. Otherwise the loading
888 // code won't be able to find the images.
889 if (base_img.find('@', last_img_slash) != std::string::npos) {
890 last_img_slash = base_img.rfind('@');
891 }
892
893 // Get the prefix, which is the primary image name (without path components). Strip the
894 // extension.
895 std::string prefix = base_img.substr(last_img_slash + 1);
896 if (prefix.rfind('.') != std::string::npos) {
897 prefix = prefix.substr(0, prefix.rfind('.'));
898 }
899 if (!prefix.empty()) {
900 prefix = prefix + "-";
901 }
902
Jeff Haodcdc85b2015-12-04 14:06:18 -0800903 base_img = base_img.substr(0, last_img_slash + 1);
904
Jeff Haodcdc85b2015-12-04 14:06:18 -0800905 // Note: we have some special case here for our testing. We have to inject the differentiating
906 // parts for the different core images.
907 std::string infix; // Empty infix by default.
908 {
909 // Check the first name.
910 std::string dex_file = oat_filenames_[0];
911 size_t last_dex_slash = dex_file.rfind('/');
912 if (last_dex_slash != std::string::npos) {
913 dex_file = dex_file.substr(last_dex_slash + 1);
914 }
915 size_t last_dex_dot = dex_file.rfind('.');
916 if (last_dex_dot != std::string::npos) {
917 dex_file = dex_file.substr(0, last_dex_dot);
918 }
919 if (StartsWith(dex_file, "core-")) {
920 infix = dex_file.substr(strlen("core"));
921 }
922 }
Andreas Gampe8994a042015-12-30 19:03:17 +0000923
924 // Now create the other names. Use a counted loop to skip the first one.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800925 for (size_t i = 1; i < dex_locations_.size(); ++i) {
926 // TODO: Make everything properly std::string.
Andreas Gampe8994a042015-12-30 19:03:17 +0000927 std::string image_name = CreateMultiImageName(dex_locations_[i], prefix, infix, ".art");
Jeff Haodcdc85b2015-12-04 14:06:18 -0800928 char_backing_storage_.push_back(base_img + image_name);
929 image_filenames_.push_back((char_backing_storage_.end() - 1)->c_str());
930
Andreas Gampe8994a042015-12-30 19:03:17 +0000931 std::string oat_name = CreateMultiImageName(dex_locations_[i], prefix, infix, ".oat");
Jeff Haodcdc85b2015-12-04 14:06:18 -0800932 char_backing_storage_.push_back(base_oat + oat_name);
933 oat_filenames_.push_back((char_backing_storage_.end() - 1)->c_str());
934 }
935 }
936
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800937 // Done with usage checks, enable watchdog if requested
Roland Levillain9ec5e222015-08-17 20:18:41 +0100938 if (parser_options->watch_dog_enabled) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800939 watchdog_.reset(new WatchDog(true));
940 }
941
942 // Fill some values into the key-value store for the oat header.
943 key_value_store_.reset(new SafeMap<std::string, std::string>());
Roland Levillain9ec5e222015-08-17 20:18:41 +0100944 }
945
Andreas Gampe8994a042015-12-30 19:03:17 +0000946 // Modify the input string in the following way:
947 // 0) Assume input is /a/b/c.d
948 // 1) Strip the path -> c.d
949 // 2) Inject prefix p -> pc.d
950 // 3) Inject infix i -> pci.d
951 // 4) Replace suffix with s if it's "jar" -> d == "jar" -> pci.s
Jeff Haodcdc85b2015-12-04 14:06:18 -0800952 static std::string CreateMultiImageName(std::string in,
Andreas Gampe8994a042015-12-30 19:03:17 +0000953 const std::string& prefix,
Jeff Haodcdc85b2015-12-04 14:06:18 -0800954 const std::string& infix,
Andreas Gampe8994a042015-12-30 19:03:17 +0000955 const char* replace_suffix) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800956 size_t last_dex_slash = in.rfind('/');
957 if (last_dex_slash != std::string::npos) {
958 in = in.substr(last_dex_slash + 1);
959 }
Andreas Gampe8994a042015-12-30 19:03:17 +0000960 if (!prefix.empty()) {
961 in = prefix + in;
962 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800963 if (!infix.empty()) {
964 // Inject infix.
965 size_t last_dot = in.rfind('.');
966 if (last_dot != std::string::npos) {
967 in.insert(last_dot, infix);
968 }
969 }
970 if (EndsWith(in, ".jar")) {
Andreas Gampe8994a042015-12-30 19:03:17 +0000971 in = in.substr(0, in.length() - strlen(".jar")) +
972 (replace_suffix != nullptr ? replace_suffix : "");
Jeff Haodcdc85b2015-12-04 14:06:18 -0800973 }
974 return in;
975 }
976
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000977 void InsertCompileOptions(int argc, char** argv) {
Roland Levillain9ec5e222015-08-17 20:18:41 +0100978 std::ostringstream oss;
979 for (int i = 0; i < argc; ++i) {
980 if (i > 0) {
981 oss << ' ';
982 }
983 oss << argv[i];
984 }
985 key_value_store_->Put(OatHeader::kDex2OatCmdLineKey, oss.str());
986 oss.str(""); // Reset.
987 oss << kRuntimeISA;
988 key_value_store_->Put(OatHeader::kDex2OatHostKey, oss.str());
989 key_value_store_->Put(
990 OatHeader::kPicKey,
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000991 compiler_options_->compile_pic_ ? OatHeader::kTrueValue : OatHeader::kFalseValue);
Roland Levillain9ec5e222015-08-17 20:18:41 +0100992 key_value_store_->Put(
993 OatHeader::kDebuggableKey,
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000994 compiler_options_->debuggable_ ? OatHeader::kTrueValue : OatHeader::kFalseValue);
Roland Levillain9ec5e222015-08-17 20:18:41 +0100995 }
996
997 // Parse the arguments from the command line. In case of an unrecognized option or impossible
998 // values/combinations, a usage error will be displayed and exit() is called. Thus, if the method
999 // returns, arguments have been successfully parsed.
1000 void ParseArgs(int argc, char** argv) {
1001 original_argc = argc;
1002 original_argv = argv;
1003
1004 InitLogging(argv);
1005
1006 // Skip over argv[0].
1007 argv++;
1008 argc--;
1009
1010 if (argc == 0) {
1011 Usage("No arguments specified");
1012 }
1013
1014 std::unique_ptr<ParserOptions> parser_options(new ParserOptions());
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001015 compiler_options_.reset(new CompilerOptions());
Roland Levillain9ec5e222015-08-17 20:18:41 +01001016
Jeff Haodcdc85b2015-12-04 14:06:18 -08001017 bool multi_image = false;
1018
Roland Levillain9ec5e222015-08-17 20:18:41 +01001019 for (int i = 0; i < argc; i++) {
1020 const StringPiece option(argv[i]);
1021 const bool log_options = false;
1022 if (log_options) {
1023 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
1024 }
1025 if (option.starts_with("--dex-file=")) {
1026 dex_filenames_.push_back(option.substr(strlen("--dex-file=")).data());
1027 } else if (option.starts_with("--dex-location=")) {
1028 dex_locations_.push_back(option.substr(strlen("--dex-location=")).data());
1029 } else if (option.starts_with("--zip-fd=")) {
1030 ParseZipFd(option);
1031 } else if (option.starts_with("--zip-location=")) {
1032 zip_location_ = option.substr(strlen("--zip-location=")).data();
1033 } else if (option.starts_with("--oat-file=")) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001034 oat_filenames_.push_back(option.substr(strlen("--oat-file=")).data());
Roland Levillain9ec5e222015-08-17 20:18:41 +01001035 } else if (option.starts_with("--oat-symbols=")) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001036 parser_options->oat_symbols.push_back(option.substr(strlen("--oat-symbols=")).data());
Roland Levillain9ec5e222015-08-17 20:18:41 +01001037 } else if (option.starts_with("--oat-fd=")) {
1038 ParseOatFd(option);
1039 } else if (option == "--watch-dog") {
1040 parser_options->watch_dog_enabled = true;
1041 } else if (option == "--no-watch-dog") {
1042 parser_options->watch_dog_enabled = false;
1043 } else if (option.starts_with("-j")) {
1044 ParseJ(option);
1045 } else if (option.starts_with("--oat-location=")) {
1046 oat_location_ = option.substr(strlen("--oat-location=")).data();
1047 } else if (option.starts_with("--image=")) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001048 image_filenames_.push_back(option.substr(strlen("--image=")).data());
Roland Levillain9ec5e222015-08-17 20:18:41 +01001049 } else if (option.starts_with("--image-classes=")) {
1050 image_classes_filename_ = option.substr(strlen("--image-classes=")).data();
1051 } else if (option.starts_with("--image-classes-zip=")) {
1052 image_classes_zip_filename_ = option.substr(strlen("--image-classes-zip=")).data();
Mathieu Chartierceb07b32015-12-10 09:33:21 -08001053 } else if (option.starts_with("--image-format=")) {
1054 ParseImageFormat(option);
Roland Levillain9ec5e222015-08-17 20:18:41 +01001055 } else if (option.starts_with("--compiled-classes=")) {
1056 compiled_classes_filename_ = option.substr(strlen("--compiled-classes=")).data();
1057 } else if (option.starts_with("--compiled-classes-zip=")) {
1058 compiled_classes_zip_filename_ = option.substr(strlen("--compiled-classes-zip=")).data();
1059 } else if (option.starts_with("--compiled-methods=")) {
1060 compiled_methods_filename_ = option.substr(strlen("--compiled-methods=")).data();
1061 } else if (option.starts_with("--compiled-methods-zip=")) {
1062 compiled_methods_zip_filename_ = option.substr(strlen("--compiled-methods-zip=")).data();
1063 } else if (option.starts_with("--base=")) {
1064 ParseBase(option);
1065 } else if (option.starts_with("--boot-image=")) {
1066 parser_options->boot_image_filename = option.substr(strlen("--boot-image=")).data();
1067 } else if (option.starts_with("--android-root=")) {
1068 android_root_ = option.substr(strlen("--android-root=")).data();
1069 } else if (option.starts_with("--instruction-set=")) {
1070 ParseInstructionSet(option);
1071 } else if (option.starts_with("--instruction-set-variant=")) {
1072 ParseInstructionSetVariant(option, parser_options.get());
1073 } else if (option.starts_with("--instruction-set-features=")) {
1074 ParseInstructionSetFeatures(option, parser_options.get());
1075 } else if (option.starts_with("--compiler-backend=")) {
1076 ParseCompilerBackend(option, parser_options.get());
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001077 } else if (option.starts_with("--profile-file=")) {
Calin Juravle998c2162015-12-21 15:39:33 +02001078 profile_files_.push_back(option.substr(strlen("--profile-file=")).ToString());
1079 } else if (option.starts_with("--reference-profile-file=")) {
1080 reference_profile_files_.push_back(
1081 option.substr(strlen("--reference-profile-file=")).ToString());
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001082 } else if (option == "--no-profile-file") {
1083 // No profile
Roland Levillain9ec5e222015-08-17 20:18:41 +01001084 } else if (option == "--host") {
1085 is_host_ = true;
1086 } else if (option == "--runtime-arg") {
1087 if (++i >= argc) {
1088 Usage("Missing required argument for --runtime-arg");
1089 }
1090 if (log_options) {
1091 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
1092 }
1093 runtime_args_.push_back(argv[i]);
1094 } else if (option == "--dump-timing") {
1095 dump_timing_ = true;
1096 } else if (option == "--dump-passes") {
1097 dump_passes_ = true;
1098 } else if (option.starts_with("--dump-cfg=")) {
1099 dump_cfg_file_name_ = option.substr(strlen("--dump-cfg=")).data();
Calin Juravle87000a92015-08-24 15:34:44 +01001100 } else if (option.starts_with("--dump-cfg-append")) {
1101 dump_cfg_append_ = true;
Roland Levillain9ec5e222015-08-17 20:18:41 +01001102 } else if (option == "--dump-stats") {
1103 dump_stats_ = true;
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001104 } else if (option.starts_with("--swap-file=")) {
1105 swap_file_name_ = option.substr(strlen("--swap-file=")).data();
1106 } else if (option.starts_with("--swap-fd=")) {
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001107 ParseUintOption(option, "--swap-fd", &swap_fd_, Usage);
1108 } else if (option.starts_with("--app-image-file=")) {
1109 app_image_file_name_ = option.substr(strlen("--app-image-file=")).data();
1110 } else if (option.starts_with("--app-image-fd=")) {
1111 ParseUintOption(option, "--app-image-fd", &app_image_fd_, Usage);
Roland Levillain9ec5e222015-08-17 20:18:41 +01001112 } else if (option.starts_with("--verbose-methods=")) {
1113 // TODO: rather than switch off compiler logging, make all VLOG(compiler) messages
1114 // conditional on having verbost methods.
1115 gLogVerbosity.compiler = false;
1116 Split(option.substr(strlen("--verbose-methods=")).ToString(), ',', &verbose_methods_);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001117 } else if (option == "--multi-image") {
1118 multi_image = true;
1119 } else if (option.starts_with("--no-inline-from=")) {
1120 no_inline_from_string_ = option.substr(strlen("--no-inline-from=")).data();
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001121 } else if (!compiler_options_->ParseCompilerOption(option, Usage)) {
Roland Levillain9ec5e222015-08-17 20:18:41 +01001122 Usage("Unknown argument %s", option.data());
1123 }
1124 }
1125
Jeff Haodcdc85b2015-12-04 14:06:18 -08001126 ProcessOptions(parser_options.get(), multi_image);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001127
1128 // Insert some compiler things.
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001129 InsertCompileOptions(argc, argv);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001130 }
1131
Jeff Haodcdc85b2015-12-04 14:06:18 -08001132 // Check whether the oat output files are writable, and open them for later. Also open a swap
1133 // file, if a name is given.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001134 bool OpenFile() {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001135 bool create_file = oat_fd_ == -1; // as opposed to using open file descriptor
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001136 if (create_file) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001137 for (const char* oat_filename : oat_filenames_) {
1138 std::unique_ptr<File> oat_file(OS::CreateEmptyFile(oat_filename));
1139 if (oat_file.get() == nullptr) {
1140 PLOG(ERROR) << "Failed to create oat file: " << oat_filename;
1141 return false;
1142 }
1143 if (create_file && fchmod(oat_file->Fd(), 0644) != 0) {
1144 PLOG(ERROR) << "Failed to make oat file world readable: " << oat_filename;
1145 oat_file->Erase();
1146 return false;
1147 }
1148 oat_files_.push_back(std::move(oat_file));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001149 }
1150 } else {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001151 std::unique_ptr<File> oat_file(new File(oat_fd_, oat_location_, true));
1152 oat_file->DisableAutoClose();
1153 if (oat_file->SetLength(0) != 0) {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001154 PLOG(WARNING) << "Truncating oat file " << oat_location_ << " failed.";
1155 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001156 if (oat_file.get() == nullptr) {
1157 PLOG(ERROR) << "Failed to create oat file: " << oat_location_;
1158 return false;
1159 }
1160 if (create_file && fchmod(oat_file->Fd(), 0644) != 0) {
1161 PLOG(ERROR) << "Failed to make oat file world readable: " << oat_location_;
1162 oat_file->Erase();
1163 return false;
1164 }
1165 oat_filenames_.push_back(oat_location_.c_str());
1166 oat_files_.push_back(std::move(oat_file));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001167 }
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001168
1169 // Swap file handling.
1170 //
1171 // If the swap fd is not -1, we assume this is the file descriptor of an open but unlinked file
1172 // that we can use for swap.
1173 //
1174 // If the swap fd is -1 and we have a swap-file string, open the given file as a swap file. We
1175 // will immediately unlink to satisfy the swap fd assumption.
1176 if (swap_fd_ == -1 && !swap_file_name_.empty()) {
1177 std::unique_ptr<File> swap_file(OS::CreateEmptyFile(swap_file_name_.c_str()));
1178 if (swap_file.get() == nullptr) {
1179 PLOG(ERROR) << "Failed to create swap file: " << swap_file_name_;
1180 return false;
1181 }
1182 swap_fd_ = swap_file->Fd();
1183 swap_file->MarkUnchecked(); // We don't we to track this, it will be unlinked immediately.
1184 swap_file->DisableAutoClose(); // We'll handle it ourselves, the File object will be
1185 // released immediately.
1186 unlink(swap_file_name_.c_str());
1187 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001188 return true;
1189 }
1190
Jeff Haodcdc85b2015-12-04 14:06:18 -08001191 void EraseOatFiles() {
1192 for (size_t i = 0; i < oat_files_.size(); ++i) {
1193 DCHECK(oat_files_[i].get() != nullptr);
1194 oat_files_[i]->Erase();
1195 oat_files_[i].reset();
1196 }
Andreas Gampea650e702014-12-03 14:28:02 -08001197 }
1198
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001199 void Shutdown() {
1200 ScopedObjectAccess soa(Thread::Current());
1201 for (jobject dex_cache : dex_caches_) {
1202 soa.Env()->DeleteLocalRef(dex_cache);
1203 }
1204 dex_caches_.clear();
1205 }
1206
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001207 // Set up the environment for compilation. Includes starting the runtime and loading/opening the
1208 // boot class path.
1209 bool Setup() {
1210 TimingLogger::ScopedTiming t("dex2oat Setup", timings_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001211 art::MemMap::Init(); // For ZipEntry::ExtractToMemMap.
Vladimir Marko49b0f452015-12-10 13:49:19 +00001212
1213 if (!PrepareImageClasses() || !PrepareCompiledClasses() || !PrepareCompiledMethods()) {
1214 return false;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001215 }
Brian Carlstromd76e0832013-08-29 15:17:42 -07001216
Vladimir Marko307dac92015-10-20 11:20:09 +01001217 verification_results_.reset(new VerificationResults(compiler_options_.get()));
Andreas Gampe4585f872015-03-27 23:45:15 -07001218 callbacks_.reset(new QuickCompilerCallbacks(
Vladimir Marko307dac92015-10-20 11:20:09 +01001219 verification_results_.get(),
Andreas Gampe4585f872015-03-27 23:45:15 -07001220 &method_inliner_map_,
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001221 IsBootImage() ?
Andreas Gampe4585f872015-03-27 23:45:15 -07001222 CompilerCallbacks::CallbackMode::kCompileBootImage :
1223 CompilerCallbacks::CallbackMode::kCompileApp));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001224
Vladimir Marko49b0f452015-12-10 13:49:19 +00001225 RuntimeArgumentMap runtime_options;
1226 if (!PrepareRuntimeOptions(&runtime_options)) {
1227 return false;
Andreas Gampe1d00add2015-02-27 19:35:46 -08001228 }
1229
Andreas Gampec7ae55d2015-09-15 20:04:54 -07001230 {
1231 TimingLogger::ScopedTiming t_runtime("Create runtime", timings_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001232 if (!CreateRuntime(std::move(runtime_options))) {
Andreas Gampec7ae55d2015-09-15 20:04:54 -07001233 return false;
1234 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001235 }
1236
1237 // Runtime::Create acquired the mutator_lock_ that is normally given away when we
1238 // Runtime::Start, give it away now so that we don't starve GC.
1239 Thread* self = Thread::Current();
1240 self->TransitionFromRunnableToSuspended(kNative);
1241 // If we're doing the image, override the compiler filter to force full compilation. Must be
1242 // done ahead of WellKnownClasses::Init that causes verification. Note: doesn't force
1243 // compilation of class initializers.
1244 // Whilst we're in native take the opportunity to initialize well known classes.
1245 WellKnownClasses::Init(self->GetJniEnv());
1246
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001247 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
Vladimir Marko49b0f452015-12-10 13:49:19 +00001248 if (boot_image_filename_.empty()) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001249 dex_files_ = class_linker->GetBootClassPath();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001250 } else {
Andreas Gampec7ae55d2015-09-15 20:04:54 -07001251 TimingLogger::ScopedTiming t_dex("Opening dex files", timings_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001252 if (dex_filenames_.empty()) {
1253 ATRACE_BEGIN("Opening zip archive from file descriptor");
1254 std::string error_msg;
1255 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(zip_fd_,
1256 zip_location_.c_str(),
1257 &error_msg));
1258 if (zip_archive.get() == nullptr) {
1259 LOG(ERROR) << "Failed to open zip from file descriptor for '" << zip_location_ << "': "
1260 << error_msg;
1261 return false;
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001262 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001263 if (!DexFile::OpenFromZip(*zip_archive.get(), zip_location_, &error_msg, &opened_dex_files_)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001264 LOG(ERROR) << "Failed to open dex from file descriptor for zip file '" << zip_location_
1265 << "': " << error_msg;
1266 return false;
1267 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001268 for (auto& dex_file : opened_dex_files_) {
1269 dex_files_.push_back(dex_file.get());
1270 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001271 ATRACE_END();
1272 } else {
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001273 size_t failure_count = OpenDexFiles(dex_filenames_, dex_locations_, &opened_dex_files_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001274 if (failure_count > 0) {
1275 LOG(ERROR) << "Failed to open some dex files: " << failure_count;
1276 return false;
1277 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001278 for (auto& dex_file : opened_dex_files_) {
1279 dex_files_.push_back(dex_file.get());
1280 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001281 }
1282
1283 constexpr bool kSaveDexInput = false;
1284 if (kSaveDexInput) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001285 SaveDexInput();
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001286 }
1287 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001288 // Ensure opened dex files are writable for dex-to-dex transformations. Also ensure that
1289 // the dex caches stay live since we don't want class unloading to occur during compilation.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001290 for (const auto& dex_file : dex_files_) {
1291 if (!dex_file->EnableWrite()) {
1292 PLOG(ERROR) << "Failed to make .dex file writeable '" << dex_file->GetLocation() << "'\n";
Andreas Gampe7ba64962014-10-23 11:37:40 -07001293 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001294 ScopedObjectAccess soa(self);
1295 dex_caches_.push_back(soa.AddLocalReference<jobject>(
Mathieu Chartierd57d4542015-10-14 10:55:30 -07001296 class_linker->RegisterDexFile(*dex_file, Runtime::Current()->GetLinearAlloc())));
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001297 dex_file->CreateTypeLookupTable();
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001298 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001299
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001300 // If we use a swap file, ensure we are above the threshold to make it necessary.
1301 if (swap_fd_ != -1) {
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001302 if (!UseSwap(IsBootImage(), dex_files_)) {
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001303 close(swap_fd_);
1304 swap_fd_ = -1;
Andreas Gampef99bcd22015-04-24 16:22:18 -07001305 VLOG(compiler) << "Decided to run without swap.";
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001306 } else {
Andreas Gampef99bcd22015-04-24 16:22:18 -07001307 LOG(INFO) << "Large app, accepted running with swap.";
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001308 }
1309 }
1310 // Note that dex2oat won't close the swap_fd_. The compiler driver's swap space will do that.
1311
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001312 /*
1313 * If we're not in interpret-only or verify-none mode, go ahead and compile small applications.
1314 * Don't bother to check if we're doing the image.
1315 */
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001316 if (!IsBootImage() &&
Brian Carlstrom95b033b2014-12-03 22:29:37 -08001317 compiler_options_->IsCompilationEnabled() &&
1318 compiler_kind_ == Compiler::kQuick) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001319 size_t num_methods = 0;
1320 for (size_t i = 0; i != dex_files_.size(); ++i) {
1321 const DexFile* dex_file = dex_files_[i];
1322 CHECK(dex_file != nullptr);
1323 num_methods += dex_file->NumMethodIds();
1324 }
1325 if (num_methods <= compiler_options_->GetNumDexMethodsThreshold()) {
1326 compiler_options_->SetCompilerFilter(CompilerOptions::kSpeed);
1327 VLOG(compiler) << "Below method threshold, compiling anyways";
1328 }
1329 }
1330
Jeff Haodcdc85b2015-12-04 14:06:18 -08001331 // Organize inputs, handling multi-dex and multiple oat file outputs.
1332 CreateDexOatMappings();
1333
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001334 return true;
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001335 }
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001336
Jeff Haodcdc85b2015-12-04 14:06:18 -08001337 void CreateDexOatMappings() {
1338 if (oat_files_.size() > 1) {
Andreas Gampe8994a042015-12-30 19:03:17 +00001339 // TODO: This needs to change, as it is not a stable mapping. If a dex file is missing,
1340 // the images will be out of whack. b/26317072
Jeff Haodcdc85b2015-12-04 14:06:18 -08001341 size_t index = 0;
1342 for (size_t i = 0; i < oat_files_.size(); ++i) {
Andreas Gampe8994a042015-12-30 19:03:17 +00001343 std::vector<const DexFile*> dex_files;
1344 if (index < dex_files_.size()) {
Nicolas Geoffrayde38b792015-12-30 14:50:12 +00001345 dex_files.push_back(dex_files_[index]);
Andreas Gampe8994a042015-12-30 19:03:17 +00001346 dex_file_oat_filename_map_.emplace(dex_files_[index], oat_filenames_[i]);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001347 index++;
Andreas Gampe8994a042015-12-30 19:03:17 +00001348 while (index < dex_files_.size() &&
1349 (dex_files_[index]->GetBaseLocation() == dex_files_[index - 1]->GetBaseLocation())) {
1350 dex_file_oat_filename_map_.emplace(dex_files_[index], oat_filenames_[i]);
1351 dex_files.push_back(dex_files_[index]);
1352 index++;
1353 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001354 }
1355 dex_files_per_oat_file_.push_back(std::move(dex_files));
1356 }
1357 } else {
1358 dex_files_per_oat_file_.push_back(dex_files_);
1359 for (const DexFile* dex_file : dex_files_) {
1360 dex_file_oat_filename_map_.emplace(dex_file, oat_filenames_[0]);
1361 }
1362 }
1363 }
1364
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001365 // Create and invoke the compiler driver. This will compile all the dex files.
1366 void Compile() {
1367 TimingLogger::ScopedTiming t("dex2oat Compile", timings_);
1368 compiler_phases_timings_.reset(new CumulativeLogger("compilation times"));
Vladimir Markof4da6752014-08-01 19:04:18 +01001369
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001370 // Handle and ClassLoader creation needs to come after Runtime::Create
1371 jobject class_loader = nullptr;
1372 Thread* self = Thread::Current();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001373
Vladimir Marko49b0f452015-12-10 13:49:19 +00001374 if (!boot_image_filename_.empty()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001375 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001376 OpenClassPathFiles(runtime_->GetClassPathString(), dex_files_, &class_path_files_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001377 ScopedObjectAccess soa(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07001378
1379 // Classpath: first the class-path given.
Vladimir Marko49b0f452015-12-10 13:49:19 +00001380 std::vector<const DexFile*> class_path_files = MakeNonOwningPointerVector(class_path_files_);
Andreas Gampe7848da42015-04-09 11:15:04 -07001381
1382 // Store the classpath we have right now.
1383 key_value_store_->Put(OatHeader::kClassPathKey,
1384 OatFile::EncodeDexFileDependencies(class_path_files));
1385
Mathieu Chartier966878d2016-01-14 14:33:29 -08001386 // Then the dex files we'll compile. Thus we'll resolve the class-path first.
1387 class_path_files.insert(class_path_files.end(), dex_files_.begin(), dex_files_.end());
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001388
Mathieu Chartier966878d2016-01-14 14:33:29 -08001389 class_loader = class_linker->CreatePathClassLoader(self, class_path_files);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001390 }
1391
Jeff Haodcdc85b2015-12-04 14:06:18 -08001392 // Find the dex file we should not inline from.
1393
1394 // For now, on the host always have core-oj removed.
1395 if (!kIsTargetBuild && no_inline_from_string_.empty()) {
1396 no_inline_from_string_ = "core-oj";
1397 }
1398
1399 if (!no_inline_from_string_.empty()) {
1400 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1401 std::vector<const DexFile*> class_path_files = MakeNonOwningPointerVector(class_path_files_);
1402 std::vector<const std::vector<const DexFile*>*> dex_file_vectors = {
1403 &class_linker->GetBootClassPath(),
1404 &class_path_files,
1405 &dex_files_
1406 };
1407 for (const std::vector<const DexFile*>* dex_file_vector : dex_file_vectors) {
1408 if (dex_file_vector == nullptr) {
1409 continue;
1410 }
1411
1412 bool found = false;
1413
1414 for (const DexFile* dex_file : *dex_file_vector) {
1415 // Try the complete location first.
1416 found = no_inline_from_string_ == dex_file->GetLocation();
1417 // The try just the name.
1418 if (!found) {
1419 size_t last_slash = dex_file->GetLocation().rfind('/');
1420 if (last_slash != std::string::npos) {
1421 found = StartsWith(dex_file->GetLocation().substr(last_slash + 1),
1422 no_inline_from_string_.c_str());
1423 }
1424 }
1425
1426 if (found) {
1427 VLOG(compiler) << "Disabling inlining from " << dex_file->GetLocation();
1428 compiler_options_->no_inline_from_ = dex_file;
1429 break;
1430 }
1431 }
1432
1433 if (found) {
1434 break;
1435 }
1436 }
1437 }
1438
1439 if (IsBootImage() && image_filenames_.size() > 1) {
1440 // If we're compiling the boot image, store the boot classpath into the Key-Value store. If
Andreas Gampe8994a042015-12-30 19:03:17 +00001441 // the image filename was adapted (e.g., for our tests), we need to change this here, too, but
1442 // need to strip all path components (they will be re-established when loading).
1443 // We need this for the multi-image case.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001444 std::ostringstream bootcp_oss;
1445 bool first_bootcp = true;
1446 for (size_t i = 0; i < dex_locations_.size(); ++i) {
1447 if (!first_bootcp) {
1448 bootcp_oss << ":";
1449 }
1450
1451 std::string dex_loc = dex_locations_[i];
1452 std::string image_filename = image_filenames_[i];
1453
Andreas Gampe8994a042015-12-30 19:03:17 +00001454 // Use the dex_loc path, but the image_filename name (without path elements).
Jeff Haodcdc85b2015-12-04 14:06:18 -08001455 size_t dex_last_slash = dex_loc.rfind('/');
Andreas Gampe8994a042015-12-30 19:03:17 +00001456
1457 // npos is max(size_t). That makes this a bit ugly.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001458 size_t image_last_slash = image_filename.rfind('/');
Andreas Gampe8994a042015-12-30 19:03:17 +00001459 size_t image_last_at = image_filename.rfind('@');
1460 size_t image_last_sep = (image_last_slash == std::string::npos)
1461 ? image_last_at
1462 : (image_last_at == std::string::npos)
1463 ? std::string::npos
1464 : std::max(image_last_slash, image_last_at);
1465 // Note: whenever image_last_sep == npos, +1 overflow means using the full string.
1466
Jeff Haodcdc85b2015-12-04 14:06:18 -08001467 if (dex_last_slash == std::string::npos) {
Andreas Gampe8994a042015-12-30 19:03:17 +00001468 dex_loc = image_filename.substr(image_last_sep + 1);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001469 } else {
1470 dex_loc = dex_loc.substr(0, dex_last_slash + 1) +
Andreas Gampe8994a042015-12-30 19:03:17 +00001471 image_filename.substr(image_last_sep + 1);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001472 }
1473
1474 // Image filenames already end with .art, no need to replace.
1475
1476 bootcp_oss << dex_loc;
1477 first_bootcp = false;
1478 }
1479 key_value_store_->Put(OatHeader::kBootClassPath, bootcp_oss.str());
1480 }
1481
Vladimir Marko307dac92015-10-20 11:20:09 +01001482 driver_.reset(new CompilerDriver(compiler_options_.get(),
1483 verification_results_.get(),
1484 &method_inliner_map_,
1485 compiler_kind_,
1486 instruction_set_,
1487 instruction_set_features_.get(),
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001488 IsBootImage(),
Vladimir Marko307dac92015-10-20 11:20:09 +01001489 image_classes_.release(),
1490 compiled_classes_.release(),
1491 nullptr,
1492 thread_count_,
1493 dump_stats_,
1494 dump_passes_,
1495 dump_cfg_file_name_,
1496 dump_cfg_append_,
1497 compiler_phases_timings_.get(),
1498 swap_fd_,
Calin Juravle998c2162015-12-21 15:39:33 +02001499 &dex_file_oat_filename_map_,
1500 profile_compilation_info_.get()));
Vladimir Markod1eaf0d2015-10-29 12:18:29 +00001501 driver_->SetDexFilesForOatFile(dex_files_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001502 driver_->CompileAll(class_loader, dex_files_, timings_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001503 }
1504
Jeff Haodcdc85b2015-12-04 14:06:18 -08001505 // TODO: Update comments about how this works for multi image. b/26317072
Brian Carlstrom7940e442013-07-12 13:46:57 -07001506 // Notes on the interleaving of creating the image and oat file to
1507 // ensure the references between the two are correct.
1508 //
1509 // Currently we have a memory layout that looks something like this:
1510 //
1511 // +--------------+
1512 // | image |
1513 // +--------------+
1514 // | boot oat |
1515 // +--------------+
1516 // | alloc spaces |
1517 // +--------------+
1518 //
Brian Carlstrom45602482013-07-21 22:07:55 -07001519 // There are several constraints on the loading of the image and boot.oat.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001520 //
1521 // 1. The image is expected to be loaded at an absolute address and
1522 // contains Objects with absolute pointers within the image.
1523 //
1524 // 2. There are absolute pointers from Methods in the image to their
1525 // code in the oat.
1526 //
1527 // 3. There are absolute pointers from the code in the oat to Methods
1528 // in the image.
1529 //
1530 // 4. There are absolute pointers from code in the oat to other code
1531 // in the oat.
1532 //
1533 // To get this all correct, we go through several steps.
1534 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001535 // 1. We prepare offsets for all data in the oat file and calculate
1536 // the oat data size and code size. During this stage, we also set
1537 // oat code offsets in methods for use by the image writer.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001538 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001539 // 2. We prepare offsets for the objects in the image and calculate
1540 // the image size.
1541 //
1542 // 3. We create the oat file. Originally this was just our own proprietary
1543 // file but now it is contained within an ELF dynamic object (aka an .so
1544 // file). Since we know the image size and oat data size and code size we
1545 // can prepare the ELF headers and we then know the ELF memory segment
1546 // layout and we can now resolve all references. The compiler provides
1547 // LinkerPatch information in each CompiledMethod and we resolve these,
1548 // using the layout information and image object locations provided by
1549 // image writer, as we're writing the method code.
1550 //
1551 // 4. We create the image file. It needs to know where the oat file
Brian Carlstrom7940e442013-07-12 13:46:57 -07001552 // will be loaded after itself. Originally when oat file was simply
1553 // memory mapped so we could predict where its contents were based
1554 // on the file size. Now that it is an ELF file, we need to inspect
1555 // the ELF file to understand the in memory segment layout including
Vladimir Markof4da6752014-08-01 19:04:18 +01001556 // where the oat header is located within.
1557 // TODO: We could just remember this information from step 3.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001558 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001559 // 5. We fixup the ELF program headers so that dlopen will try to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001560 // load the .so at the desired location at runtime by offsetting the
1561 // Elf32_Phdr.p_vaddr values by the desired base address.
Vladimir Markof4da6752014-08-01 19:04:18 +01001562 // TODO: Do this in step 3. We already know the layout there.
1563 //
1564 // Steps 1.-3. are done by the CreateOatFile() above, steps 4.-5.
1565 // are done by the CreateImageFile() below.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001566
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001567 // Write out the generated code part. Calls the OatWriter and ElfBuilder. Also prepares the
1568 // ImageWriter, if necessary.
Andreas Gampe10e477d2014-11-19 12:57:42 -08001569 // Note: Flushing (and closing) the file is the caller's responsibility, except for the failure
1570 // case (when the file will be explicitly erased).
Jeff Haodcdc85b2015-12-04 14:06:18 -08001571 bool CreateOatFiles() {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001572 CHECK(key_value_store_.get() != nullptr);
1573
1574 TimingLogger::ScopedTiming t("dex2oat Oat", timings_);
1575
Jeff Haodcdc85b2015-12-04 14:06:18 -08001576 std::vector<std::unique_ptr<OatWriter>> oat_writers;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001577 {
1578 TimingLogger::ScopedTiming t2("dex2oat OatWriter", timings_);
1579 std::string image_file_location;
1580 uint32_t image_file_location_oat_checksum = 0;
1581 uintptr_t image_file_location_oat_data_begin = 0;
1582 int32_t image_patch_delta = 0;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001583
1584 if (app_image_ && image_base_ == 0) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001585 std::vector<gc::space::ImageSpace*> image_spaces =
1586 Runtime::Current()->GetHeap()->GetBootImageSpaces();
1587 for (gc::space::ImageSpace* image_space : image_spaces) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001588 image_base_ = std::max(image_base_, RoundUp(
1589 reinterpret_cast<uintptr_t>(image_space->GetImageHeader().GetOatFileEnd()),
1590 kPageSize));
1591 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001592 VLOG(compiler) << "App image base=" << reinterpret_cast<void*>(image_base_);
1593 }
1594
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001595 if (IsImage()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001596 PrepareImageWriter(image_base_);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001597 }
1598
1599 if (!IsBootImage()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001600 TimingLogger::ScopedTiming t3("Loading image checksum", timings_);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001601 std::vector<gc::space::ImageSpace*> image_spaces =
1602 Runtime::Current()->GetHeap()->GetBootImageSpaces();
1603 image_file_location_oat_checksum = image_spaces[0]->GetImageHeader().GetOatChecksum();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001604 image_file_location_oat_data_begin =
Jeff Haodcdc85b2015-12-04 14:06:18 -08001605 reinterpret_cast<uintptr_t>(image_spaces[0]->GetImageHeader().GetOatDataBegin());
1606 image_patch_delta = image_spaces[0]->GetImageHeader().GetPatchDelta();
1607 std::vector<std::string> image_filenames;
1608 for (const gc::space::ImageSpace* image_space : image_spaces) {
1609 image_filenames.push_back(image_space->GetImageFilename());
1610 }
1611 image_file_location = Join(image_filenames, ':');
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001612 }
1613
1614 if (!image_file_location.empty()) {
1615 key_value_store_->Put(OatHeader::kImageLocationKey, image_file_location);
1616 }
1617
Jeff Haodcdc85b2015-12-04 14:06:18 -08001618 for (size_t i = 0; i < oat_files_.size(); ++i) {
1619 std::vector<const DexFile*>& dex_files = dex_files_per_oat_file_[i];
1620 std::unique_ptr<OatWriter> oat_writer(new OatWriter(dex_files,
1621 image_file_location_oat_checksum,
1622 image_file_location_oat_data_begin,
1623 image_patch_delta,
1624 driver_.get(),
1625 image_writer_.get(),
1626 IsBootImage(),
1627 timings_,
1628 key_value_store_.get()));
1629 oat_writers.push_back(std::move(oat_writer));
1630 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001631 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001632
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001633 if (IsImage()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001634 // The OatWriter constructor has already updated offsets in methods and we need to
1635 // prepare method offsets in the image address space for direct method patching.
1636 TimingLogger::ScopedTiming t2("dex2oat Prepare image address space", timings_);
1637 if (!image_writer_->PrepareImageAddressSpace()) {
1638 LOG(ERROR) << "Failed to prepare image address space.";
1639 return false;
1640 }
1641 }
1642
1643 {
1644 TimingLogger::ScopedTiming t2("dex2oat Write ELF", timings_);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001645 for (size_t i = 0; i < oat_files_.size(); ++i) {
1646 std::unique_ptr<File>& oat_file = oat_files_[i];
1647 std::unique_ptr<OatWriter>& oat_writer = oat_writers[i];
1648 std::unique_ptr<ElfWriter> elf_writer =
1649 CreateElfWriterQuick(instruction_set_, compiler_options_.get(), oat_file.get());
Vladimir Marko10c13562015-11-25 14:33:36 +00001650
Jeff Haodcdc85b2015-12-04 14:06:18 -08001651 elf_writer->Start();
Vladimir Marko10c13562015-11-25 14:33:36 +00001652
Jeff Haodcdc85b2015-12-04 14:06:18 -08001653 OutputStream* rodata = elf_writer->StartRoData();
1654 if (!oat_writer->WriteRodata(rodata)) {
1655 LOG(ERROR) << "Failed to write .rodata section to the ELF file " << oat_file->GetPath();
1656 return false;
1657 }
1658 elf_writer->EndRoData(rodata);
Vladimir Marko10c13562015-11-25 14:33:36 +00001659
Jeff Haodcdc85b2015-12-04 14:06:18 -08001660 OutputStream* text = elf_writer->StartText();
1661 if (!oat_writer->WriteCode(text)) {
1662 LOG(ERROR) << "Failed to write .text section to the ELF file " << oat_file->GetPath();
1663 return false;
1664 }
1665 elf_writer->EndText(text);
Vladimir Marko10c13562015-11-25 14:33:36 +00001666
Jeff Haodcdc85b2015-12-04 14:06:18 -08001667 elf_writer->SetBssSize(oat_writer->GetBssSize());
1668 elf_writer->WriteDynamicSection();
1669 elf_writer->WriteDebugInfo(oat_writer->GetMethodDebugInfo());
1670 elf_writer->WritePatchLocations(oat_writer->GetAbsolutePatchLocations());
Vladimir Marko10c13562015-11-25 14:33:36 +00001671
Jeff Haodcdc85b2015-12-04 14:06:18 -08001672 if (!elf_writer->End()) {
1673 LOG(ERROR) << "Failed to write ELF file " << oat_file->GetPath();
1674 return false;
1675 }
1676
1677 // Flush the oat file.
1678 if (oat_files_[i] != nullptr) {
1679 if (oat_files_[i]->Flush() != 0) {
1680 PLOG(ERROR) << "Failed to flush oat file: " << oat_filenames_[i];
1681 oat_files_[i]->Erase();
1682 return false;
1683 }
1684 }
1685
1686 if (IsImage()) {
1687 // Update oat estimates.
1688 UpdateImageWriter(i);
1689 }
1690
1691 VLOG(compiler) << "Oat file written successfully: " << oat_filenames_[i];
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001692 }
1693 }
1694
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001695 return true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001696 }
1697
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001698 // If we are compiling an image, invoke the image creation routine. Else just skip.
1699 bool HandleImage() {
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001700 if (IsImage()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001701 TimingLogger::ScopedTiming t("dex2oat ImageWriter", timings_);
1702 if (!CreateImageFile()) {
1703 return false;
1704 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001705 VLOG(compiler) << "Images written successfully";
Brian Carlstrom45602482013-07-21 22:07:55 -07001706 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001707 return true;
1708 }
1709
Jeff Haodcdc85b2015-12-04 14:06:18 -08001710 // Create a copy from stripped to unstripped.
1711 bool CopyStrippedToUnstripped() {
1712 for (size_t i = 0; i < oat_unstripped_.size(); ++i) {
1713 // If we don't want to strip in place, copy from stripped location to unstripped location.
1714 // We need to strip after image creation because FixupElf needs to use .strtab.
1715 if (strcmp(oat_unstripped_[i], oat_filenames_[i]) != 0) {
1716 // If the oat file is still open, flush it.
1717 if (oat_files_[i].get() != nullptr && oat_files_[i]->IsOpened()) {
1718 if (!FlushCloseOatFile(i)) {
1719 return false;
1720 }
1721 }
1722
1723 TimingLogger::ScopedTiming t("dex2oat OatFile copy", timings_);
1724 std::unique_ptr<File> in(OS::OpenFileForReading(oat_filenames_[i]));
1725 std::unique_ptr<File> out(OS::CreateEmptyFile(oat_unstripped_[i]));
1726 size_t buffer_size = 8192;
1727 std::unique_ptr<uint8_t[]> buffer(new uint8_t[buffer_size]);
1728 while (true) {
1729 int bytes_read = TEMP_FAILURE_RETRY(read(in->Fd(), buffer.get(), buffer_size));
1730 if (bytes_read <= 0) {
1731 break;
1732 }
1733 bool write_ok = out->WriteFully(buffer.get(), bytes_read);
1734 CHECK(write_ok);
1735 }
1736 if (out->FlushCloseOrErase() != 0) {
1737 PLOG(ERROR) << "Failed to flush and close copied oat file: " << oat_unstripped_[i];
1738 return false;
1739 }
1740 VLOG(compiler) << "Oat file copied successfully (unstripped): " << oat_unstripped_[i];
1741 }
1742 }
1743 return true;
1744 }
1745
1746 bool FlushOatFiles() {
1747 TimingLogger::ScopedTiming t2("dex2oat Flush ELF", timings_);
1748 for (size_t i = 0; i < oat_files_.size(); ++i) {
1749 if (oat_files_[i].get() != nullptr) {
1750 if (oat_files_[i]->Flush() != 0) {
1751 PLOG(ERROR) << "Failed to flush oat file: " << oat_filenames_[i];
1752 oat_files_[i]->Erase();
Andreas Gampe10e477d2014-11-19 12:57:42 -08001753 return false;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001754 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001755 }
Nicolas Geoffrayea3fa0b2014-02-10 11:59:41 +00001756 }
Andreas Gampe10e477d2014-11-19 12:57:42 -08001757 return true;
1758 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001759
Jeff Haodcdc85b2015-12-04 14:06:18 -08001760 bool FlushCloseOatFile(size_t i) {
1761 if (oat_files_[i].get() != nullptr) {
1762 std::unique_ptr<File> tmp(oat_files_[i].release());
Andreas Gampe10e477d2014-11-19 12:57:42 -08001763 if (tmp->FlushCloseOrErase() != 0) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001764 PLOG(ERROR) << "Failed to flush and close oat file: " << oat_filenames_[i];
Andreas Gampe10e477d2014-11-19 12:57:42 -08001765 return false;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001766 }
1767 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001768 return true;
1769 }
1770
Jeff Haodcdc85b2015-12-04 14:06:18 -08001771 bool FlushCloseOatFiles() {
1772 bool result = true;
1773 for (size_t i = 0; i < oat_files_.size(); ++i) {
1774 result &= FlushCloseOatFile(i);
1775 }
1776 return result;
1777 }
1778
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001779 void DumpTiming() {
1780 if (dump_timing_ || (dump_slow_timing_ && timings_->GetTotalNs() > MsToNs(1000))) {
1781 LOG(INFO) << Dumpable<TimingLogger>(*timings_);
1782 }
1783 if (dump_passes_) {
1784 LOG(INFO) << Dumpable<CumulativeLogger>(*driver_->GetTimingsLogger());
1785 }
1786 }
1787
1788 CompilerOptions* GetCompilerOptions() const {
1789 return compiler_options_.get();
1790 }
1791
Andreas Gampe10e477d2014-11-19 12:57:42 -08001792 bool IsImage() const {
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001793 return IsAppImage() || IsBootImage();
1794 }
1795
1796 bool IsAppImage() const {
1797 return app_image_;
1798 }
1799
1800 bool IsBootImage() const {
1801 return boot_image_;
Andreas Gampe10e477d2014-11-19 12:57:42 -08001802 }
1803
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001804 bool IsHost() const {
1805 return is_host_;
1806 }
1807
Calin Juravle998c2162015-12-21 15:39:33 +02001808 bool UseProfileGuidedCompilation() const {
1809 return !profile_files_.empty();
1810 }
1811
1812 bool ProcessProfiles() {
1813 DCHECK(UseProfileGuidedCompilation());
1814 ProfileCompilationInfo* info = nullptr;
1815 if (ProfileAssistant::ProcessProfiles(profile_files_, reference_profile_files_, &info)) {
1816 profile_compilation_info_.reset(info);
1817 return true;
1818 }
1819 return false;
1820 }
1821
1822 bool ShouldCompileBasedOnProfiles() const {
1823 DCHECK(UseProfileGuidedCompilation());
1824 // If we are given profiles, compile only if we have new information.
1825 return profile_compilation_info_ != nullptr;
1826 }
1827
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001828 private:
Vladimir Marko49b0f452015-12-10 13:49:19 +00001829 template <typename T>
1830 static std::vector<T*> MakeNonOwningPointerVector(const std::vector<std::unique_ptr<T>>& src) {
1831 std::vector<T*> result;
1832 result.reserve(src.size());
1833 for (const std::unique_ptr<T>& t : src) {
1834 result.push_back(t.get());
1835 }
1836 return result;
1837 }
1838
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001839 static size_t OpenDexFiles(const std::vector<const char*>& dex_filenames,
1840 const std::vector<const char*>& dex_locations,
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001841 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001842 DCHECK(dex_files != nullptr) << "OpenDexFiles out-param is nullptr";
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001843 size_t failure_count = 0;
1844 for (size_t i = 0; i < dex_filenames.size(); i++) {
1845 const char* dex_filename = dex_filenames[i];
1846 const char* dex_location = dex_locations[i];
1847 ATRACE_BEGIN(StringPrintf("Opening dex file '%s'", dex_filenames[i]).c_str());
1848 std::string error_msg;
1849 if (!OS::FileExists(dex_filename)) {
1850 LOG(WARNING) << "Skipping non-existent dex file '" << dex_filename << "'";
1851 continue;
1852 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001853 if (!DexFile::Open(dex_filename, dex_location, &error_msg, dex_files)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001854 LOG(WARNING) << "Failed to open .dex from file '" << dex_filename << "': " << error_msg;
1855 ++failure_count;
1856 }
1857 ATRACE_END();
1858 }
1859 return failure_count;
1860 }
1861
Andreas Gampee3712d02015-04-09 14:46:31 -07001862 // Returns true if dex_files has a dex with the named location. We compare canonical locations,
1863 // so that relative and absolute paths will match. Not caching for the dex_files isn't very
1864 // efficient, but under normal circumstances the list is neither large nor is this part too
1865 // sensitive.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001866 static bool DexFilesContains(const std::vector<const DexFile*>& dex_files,
1867 const std::string& location) {
Andreas Gampee3712d02015-04-09 14:46:31 -07001868 std::string canonical_location(DexFile::GetDexCanonicalLocation(location.c_str()));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001869 for (size_t i = 0; i < dex_files.size(); ++i) {
Andreas Gampee3712d02015-04-09 14:46:31 -07001870 if (DexFile::GetDexCanonicalLocation(dex_files[i]->GetLocation().c_str()) ==
1871 canonical_location) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001872 return true;
1873 }
1874 }
1875 return false;
1876 }
1877
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001878 // Appends to opened_dex_files any elements of class_path that dex_files
1879 // doesn't already contain. This will open those dex files as necessary.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001880 static void OpenClassPathFiles(const std::string& class_path,
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001881 std::vector<const DexFile*> dex_files,
1882 std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001883 DCHECK(opened_dex_files != nullptr) << "OpenClassPathFiles out-param is nullptr";
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001884 std::vector<std::string> parsed;
1885 Split(class_path, ':', &parsed);
1886 // Take Locks::mutator_lock_ so that lock ordering on the ClassLinker::dex_lock_ is maintained.
1887 ScopedObjectAccess soa(Thread::Current());
1888 for (size_t i = 0; i < parsed.size(); ++i) {
1889 if (DexFilesContains(dex_files, parsed[i])) {
1890 continue;
1891 }
1892 std::string error_msg;
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001893 if (!DexFile::Open(parsed[i].c_str(), parsed[i].c_str(), &error_msg, opened_dex_files)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001894 LOG(WARNING) << "Failed to open dex file '" << parsed[i] << "': " << error_msg;
1895 }
1896 }
1897 }
1898
Vladimir Marko49b0f452015-12-10 13:49:19 +00001899 bool PrepareImageClasses() {
1900 // If --image-classes was specified, calculate the full list of classes to include in the image.
1901 if (image_classes_filename_ != nullptr) {
1902 image_classes_ =
1903 ReadClasses(image_classes_zip_filename_, image_classes_filename_, "image");
1904 if (image_classes_ == nullptr) {
1905 return false;
1906 }
1907 } else if (IsBootImage()) {
1908 image_classes_.reset(new std::unordered_set<std::string>);
1909 }
1910 return true;
1911 }
1912
1913 bool PrepareCompiledClasses() {
1914 // If --compiled-classes was specified, calculate the full list of classes to compile in the
1915 // image.
1916 if (compiled_classes_filename_ != nullptr) {
1917 compiled_classes_ =
1918 ReadClasses(compiled_classes_zip_filename_, compiled_classes_filename_, "compiled");
1919 if (compiled_classes_ == nullptr) {
1920 return false;
1921 }
1922 } else {
1923 compiled_classes_.reset(nullptr); // By default compile everything.
1924 }
1925 return true;
1926 }
1927
1928 static std::unique_ptr<std::unordered_set<std::string>> ReadClasses(const char* zip_filename,
1929 const char* classes_filename,
1930 const char* tag) {
1931 std::unique_ptr<std::unordered_set<std::string>> classes;
1932 std::string error_msg;
1933 if (zip_filename != nullptr) {
1934 classes.reset(ReadImageClassesFromZip(zip_filename, classes_filename, &error_msg));
1935 } else {
1936 classes.reset(ReadImageClassesFromFile(classes_filename));
1937 }
1938 if (classes == nullptr) {
1939 LOG(ERROR) << "Failed to create list of " << tag << " classes from '"
1940 << classes_filename << "': " << error_msg;
1941 }
1942 return classes;
1943 }
1944
1945 bool PrepareCompiledMethods() {
1946 // If --compiled-methods was specified, read the methods to compile from the given file(s).
1947 if (compiled_methods_filename_ != nullptr) {
1948 std::string error_msg;
1949 if (compiled_methods_zip_filename_ != nullptr) {
1950 compiled_methods_.reset(ReadCommentedInputFromZip(compiled_methods_zip_filename_,
1951 compiled_methods_filename_,
1952 nullptr, // No post-processing.
1953 &error_msg));
1954 } else {
1955 compiled_methods_.reset(ReadCommentedInputFromFile(compiled_methods_filename_,
1956 nullptr)); // No post-processing.
1957 }
1958 if (compiled_methods_.get() == nullptr) {
1959 LOG(ERROR) << "Failed to create list of compiled methods from '"
1960 << compiled_methods_filename_ << "': " << error_msg;
1961 return false;
1962 }
1963 } else {
1964 compiled_methods_.reset(nullptr); // By default compile everything.
1965 }
1966 return true;
1967 }
1968
1969 void SaveDexInput() {
1970 for (size_t i = 0; i < dex_files_.size(); ++i) {
1971 const DexFile* dex_file = dex_files_[i];
1972 std::string tmp_file_name(StringPrintf("/data/local/tmp/dex2oat.%d.%zd.dex",
1973 getpid(), i));
1974 std::unique_ptr<File> tmp_file(OS::CreateEmptyFile(tmp_file_name.c_str()));
1975 if (tmp_file.get() == nullptr) {
1976 PLOG(ERROR) << "Failed to open file " << tmp_file_name
1977 << ". Try: adb shell chmod 777 /data/local/tmp";
1978 continue;
1979 }
1980 // This is just dumping files for debugging. Ignore errors, and leave remnants.
1981 UNUSED(tmp_file->WriteFully(dex_file->Begin(), dex_file->Size()));
1982 UNUSED(tmp_file->Flush());
1983 UNUSED(tmp_file->Close());
1984 LOG(INFO) << "Wrote input to " << tmp_file_name;
1985 }
1986 }
1987
1988 bool PrepareRuntimeOptions(RuntimeArgumentMap* runtime_options) {
1989 RuntimeOptions raw_options;
1990 if (boot_image_filename_.empty()) {
1991 std::string boot_class_path = "-Xbootclasspath:";
1992 boot_class_path += Join(dex_filenames_, ':');
1993 raw_options.push_back(std::make_pair(boot_class_path, nullptr));
1994 std::string boot_class_path_locations = "-Xbootclasspath-locations:";
1995 boot_class_path_locations += Join(dex_locations_, ':');
1996 raw_options.push_back(std::make_pair(boot_class_path_locations, nullptr));
1997 } else {
1998 std::string boot_image_option = "-Ximage:";
1999 boot_image_option += boot_image_filename_;
2000 raw_options.push_back(std::make_pair(boot_image_option, nullptr));
2001 }
2002 for (size_t i = 0; i < runtime_args_.size(); i++) {
2003 raw_options.push_back(std::make_pair(runtime_args_[i], nullptr));
2004 }
2005
2006 raw_options.push_back(std::make_pair("compilercallbacks", callbacks_.get()));
2007 raw_options.push_back(
2008 std::make_pair("imageinstructionset", GetInstructionSetString(instruction_set_)));
2009
2010 // Only allow no boot image for the runtime if we're compiling one. When we compile an app,
2011 // we don't want fallback mode, it will abort as we do not push a boot classpath (it might
2012 // have been stripped in preopting, anyways).
2013 if (!IsBootImage()) {
2014 raw_options.push_back(std::make_pair("-Xno-dex-file-fallback", nullptr));
2015 }
2016 // Disable libsigchain. We don't don't need it during compilation and it prevents us
2017 // from getting a statically linked version of dex2oat (because of dlsym and RTLD_NEXT).
2018 raw_options.push_back(std::make_pair("-Xno-sig-chain", nullptr));
2019
2020 if (!Runtime::ParseOptions(raw_options, false, runtime_options)) {
2021 LOG(ERROR) << "Failed to parse runtime options";
2022 return false;
2023 }
2024 return true;
2025 }
2026
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002027 // Create a runtime necessary for compilation.
Vladimir Marko49b0f452015-12-10 13:49:19 +00002028 bool CreateRuntime(RuntimeArgumentMap&& runtime_options)
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002029 SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00002030 if (!Runtime::Create(std::move(runtime_options))) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002031 LOG(ERROR) << "Failed to create runtime";
2032 return false;
2033 }
Vladimir Marko307dac92015-10-20 11:20:09 +01002034 runtime_.reset(Runtime::Current());
2035 runtime_->SetInstructionSet(instruction_set_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002036 for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
2037 Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i);
Vladimir Marko307dac92015-10-20 11:20:09 +01002038 if (!runtime_->HasCalleeSaveMethod(type)) {
2039 runtime_->SetCalleeSaveMethod(runtime_->CreateCalleeSaveMethod(), type);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002040 }
2041 }
Vladimir Marko307dac92015-10-20 11:20:09 +01002042 runtime_->GetClassLinker()->FixupDexCaches(runtime_->GetResolutionMethod());
Andreas Gampe2969bcd2015-03-09 12:57:41 -07002043
2044 // Initialize maps for unstarted runtime. This needs to be here, as running clinits needs this
2045 // set up.
Andreas Gampe799681b2015-05-15 19:24:12 -07002046 interpreter::UnstartedRuntime::Initialize();
Andreas Gampe2969bcd2015-03-09 12:57:41 -07002047
Vladimir Marko307dac92015-10-20 11:20:09 +01002048 runtime_->GetClassLinker()->RunRootClinits();
Andreas Gampe2969bcd2015-03-09 12:57:41 -07002049
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002050 return true;
2051 }
2052
2053 void PrepareImageWriter(uintptr_t image_base) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002054 DCHECK(IsImage());
2055 image_writer_.reset(new ImageWriter(*driver_,
2056 image_base,
2057 compiler_options_->GetCompilePic(),
Mathieu Chartierceb07b32015-12-10 09:33:21 -08002058 IsAppImage(),
Jeff Haodcdc85b2015-12-04 14:06:18 -08002059 image_storage_mode_,
2060 oat_filenames_,
2061 dex_file_oat_filename_map_));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002062 }
2063
Jeff Haodcdc85b2015-12-04 14:06:18 -08002064 // 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 -08002065 bool CreateImageFile()
Mathieu Chartier90443472015-07-16 20:32:27 -07002066 REQUIRES(!Locks::mutator_lock_) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002067 CHECK(image_writer_ != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002068 if (!IsBootImage()) {
2069 image_filenames_.push_back(app_image_file_name_.c_str());
2070 }
2071 if (!image_writer_->Write(app_image_fd_, image_filenames_, oat_filenames_)) {
2072 LOG(ERROR) << "Failure during image file creation";
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002073 return false;
2074 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002075
Jeff Haodcdc85b2015-12-04 14:06:18 -08002076 // We need the OatDataBegin entries.
2077 std::map<const char*, uintptr_t> oat_data_begins;
2078 for (const char* oat_filename : oat_filenames_) {
2079 oat_data_begins.emplace(oat_filename, image_writer_->GetOatDataBegin(oat_filename));
2080 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002081 // Destroy ImageWriter before doing FixupElf.
2082 image_writer_.reset();
2083
Jeff Haodcdc85b2015-12-04 14:06:18 -08002084 for (const char* oat_filename : oat_filenames_) {
2085 // Do not fix up the ELF file if we are --compile-pic or compiling the app image
2086 if (!compiler_options_->GetCompilePic() && IsBootImage()) {
2087 std::unique_ptr<File> oat_file(OS::OpenFileReadWrite(oat_filename));
2088 if (oat_file.get() == nullptr) {
2089 PLOG(ERROR) << "Failed to open ELF file: " << oat_filename;
2090 return false;
2091 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08002092
Jeff Haodcdc85b2015-12-04 14:06:18 -08002093 uintptr_t oat_data_begin = oat_data_begins.find(oat_filename)->second;
Andreas Gampe4303ba92014-11-06 01:00:46 -08002094
Jeff Haodcdc85b2015-12-04 14:06:18 -08002095 if (!ElfWriter::Fixup(oat_file.get(), oat_data_begin)) {
2096 oat_file->Erase();
2097 LOG(ERROR) << "Failed to fixup ELF file " << oat_file->GetPath();
2098 return false;
2099 }
2100
2101 if (oat_file->FlushCloseOrErase()) {
2102 PLOG(ERROR) << "Failed to flush and close fixed ELF file " << oat_file->GetPath();
2103 return false;
2104 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08002105 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002106 }
2107
2108 return true;
2109 }
2110
2111 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
Andreas Gampeb1fcead2015-04-20 18:53:51 -07002112 static std::unordered_set<std::string>* ReadImageClassesFromFile(
2113 const char* image_classes_filename) {
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002114 std::function<std::string(const char*)> process = DotToDescriptor;
2115 return ReadCommentedInputFromFile(image_classes_filename, &process);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002116 }
2117
2118 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
Andreas Gampeb1fcead2015-04-20 18:53:51 -07002119 static std::unordered_set<std::string>* ReadImageClassesFromZip(
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002120 const char* zip_filename,
2121 const char* image_classes_filename,
2122 std::string* error_msg) {
2123 std::function<std::string(const char*)> process = DotToDescriptor;
2124 return ReadCommentedInputFromZip(zip_filename, image_classes_filename, &process, error_msg);
2125 }
2126
2127 // Read lines from the given file, dropping comments and empty lines. Post-process each line with
2128 // the given function.
2129 static std::unordered_set<std::string>* ReadCommentedInputFromFile(
2130 const char* input_filename, std::function<std::string(const char*)>* process) {
2131 std::unique_ptr<std::ifstream> input_file(new std::ifstream(input_filename, std::ifstream::in));
2132 if (input_file.get() == nullptr) {
2133 LOG(ERROR) << "Failed to open input file " << input_filename;
2134 return nullptr;
2135 }
2136 std::unique_ptr<std::unordered_set<std::string>> result(
2137 ReadCommentedInputStream(*input_file, process));
2138 input_file->close();
2139 return result.release();
2140 }
2141
2142 // Read lines from the given file from the given zip file, dropping comments and empty lines.
2143 // Post-process each line with the given function.
2144 static std::unordered_set<std::string>* ReadCommentedInputFromZip(
Andreas Gampeb1fcead2015-04-20 18:53:51 -07002145 const char* zip_filename,
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002146 const char* input_filename,
2147 std::function<std::string(const char*)>* process,
Andreas Gampeb1fcead2015-04-20 18:53:51 -07002148 std::string* error_msg) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002149 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::Open(zip_filename, error_msg));
2150 if (zip_archive.get() == nullptr) {
2151 return nullptr;
2152 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002153 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(input_filename, error_msg));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002154 if (zip_entry.get() == nullptr) {
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002155 *error_msg = StringPrintf("Failed to find '%s' within '%s': %s", input_filename,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002156 zip_filename, error_msg->c_str());
2157 return nullptr;
2158 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002159 std::unique_ptr<MemMap> input_file(zip_entry->ExtractToMemMap(zip_filename,
2160 input_filename,
2161 error_msg));
2162 if (input_file.get() == nullptr) {
2163 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", input_filename,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002164 zip_filename, error_msg->c_str());
2165 return nullptr;
2166 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002167 const std::string input_string(reinterpret_cast<char*>(input_file->Begin()),
2168 input_file->Size());
2169 std::istringstream input_stream(input_string);
2170 return ReadCommentedInputStream(input_stream, process);
2171 }
2172
2173 // Read lines from the given stream, dropping comments and empty lines. Post-process each line
2174 // with the given function.
2175 static std::unordered_set<std::string>* ReadCommentedInputStream(
2176 std::istream& in_stream,
2177 std::function<std::string(const char*)>* process) {
2178 std::unique_ptr<std::unordered_set<std::string>> image_classes(
2179 new std::unordered_set<std::string>);
2180 while (in_stream.good()) {
2181 std::string dot;
2182 std::getline(in_stream, dot);
2183 if (StartsWith(dot, "#") || dot.empty()) {
2184 continue;
2185 }
2186 if (process != nullptr) {
2187 std::string descriptor((*process)(dot.c_str()));
2188 image_classes->insert(descriptor);
2189 } else {
2190 image_classes->insert(dot);
2191 }
2192 }
2193 return image_classes.release();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002194 }
2195
Mathieu Chartier49285c52014-12-02 15:43:48 -08002196 void LogCompletionTime() {
Andreas Gampe1d00add2015-02-27 19:35:46 -08002197 // Note: when creation of a runtime fails, e.g., when trying to compile an app but when there
2198 // is no image, there won't be a Runtime::Current().
Brian Carlstroma11a34c2015-03-06 08:44:45 -08002199 // Note: driver creation can fail when loading an invalid dex file.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002200 LOG(INFO) << "dex2oat took " << PrettyDuration(NanoTime() - start_ns_)
Mathieu Chartierab972ef2014-12-03 17:38:22 -08002201 << " (threads: " << thread_count_ << ") "
Andreas Gampe3f30e122015-09-17 14:03:21 -07002202 << ((Runtime::Current() != nullptr && driver_ != nullptr) ?
Andreas Gampe1d00add2015-02-27 19:35:46 -08002203 driver_->GetMemoryUsageString(kIsDebugBuild || VLOG_IS_ON(compiler)) :
2204 "");
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002205 }
2206
Jeff Haodcdc85b2015-12-04 14:06:18 -08002207 std::string StripIsaFrom(const char* image_filename, InstructionSet isa) {
2208 std::string res(image_filename);
2209 size_t last_slash = res.rfind('/');
2210 if (last_slash == std::string::npos || last_slash == 0) {
2211 return res;
2212 }
2213 size_t penultimate_slash = res.rfind('/', last_slash - 1);
2214 if (penultimate_slash == std::string::npos) {
2215 return res;
2216 }
2217 // Check that the string in-between is the expected one.
2218 if (res.substr(penultimate_slash + 1, last_slash - penultimate_slash - 1) !=
2219 GetInstructionSetString(isa)) {
2220 LOG(WARNING) << "Unexpected string when trying to strip isa: " << res;
2221 return res;
2222 }
2223 return res.substr(0, penultimate_slash) + res.substr(last_slash);
2224 }
2225
2226 // Update the estimate for the oat file with the given index.
2227 void UpdateImageWriter(size_t index) {
2228 DCHECK(image_writer_ != nullptr);
2229 DCHECK_LT(index, oat_filenames_.size());
2230
2231 image_writer_->UpdateOatFile(oat_filenames_[index]);
2232 }
2233
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002234 std::unique_ptr<CompilerOptions> compiler_options_;
2235 Compiler::Kind compiler_kind_;
2236
2237 InstructionSet instruction_set_;
2238 std::unique_ptr<const InstructionSetFeatures> instruction_set_features_;
2239
2240 std::unique_ptr<SafeMap<std::string, std::string> > key_value_store_;
2241
Vladimir Marko307dac92015-10-20 11:20:09 +01002242 std::unique_ptr<VerificationResults> verification_results_;
Andreas Gampe3f30e122015-09-17 14:03:21 -07002243
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002244 DexFileToMethodInlinerMap method_inliner_map_;
2245 std::unique_ptr<QuickCompilerCallbacks> callbacks_;
2246
Richard Uhlerfbef44d2014-12-23 09:48:51 -08002247 // Ownership for the class path files.
2248 std::vector<std::unique_ptr<const DexFile>> class_path_files_;
2249
Vladimir Marko307dac92015-10-20 11:20:09 +01002250 std::unique_ptr<Runtime> runtime_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002251
2252 size_t thread_count_;
2253 uint64_t start_ns_;
2254 std::unique_ptr<WatchDog> watchdog_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002255 std::vector<std::unique_ptr<File>> oat_files_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002256 std::string oat_location_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002257 std::vector<const char*> oat_filenames_;
2258 std::vector<const char*> oat_unstripped_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002259 int oat_fd_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002260 std::vector<const char*> dex_filenames_;
2261 std::vector<const char*> dex_locations_;
2262 int zip_fd_;
2263 std::string zip_location_;
Vladimir Marko49b0f452015-12-10 13:49:19 +00002264 std::string boot_image_filename_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002265 std::vector<const char*> runtime_args_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002266 std::vector<const char*> image_filenames_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002267 uintptr_t image_base_;
2268 const char* image_classes_zip_filename_;
2269 const char* image_classes_filename_;
Mathieu Chartierceb07b32015-12-10 09:33:21 -08002270 ImageHeader::StorageMode image_storage_mode_;
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08002271 const char* compiled_classes_zip_filename_;
2272 const char* compiled_classes_filename_;
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002273 const char* compiled_methods_zip_filename_;
2274 const char* compiled_methods_filename_;
Andreas Gampeb1fcead2015-04-20 18:53:51 -07002275 std::unique_ptr<std::unordered_set<std::string>> image_classes_;
2276 std::unique_ptr<std::unordered_set<std::string>> compiled_classes_;
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002277 std::unique_ptr<std::unordered_set<std::string>> compiled_methods_;
Mathieu Chartiera90c7722015-10-29 15:41:36 -07002278 bool app_image_;
2279 bool boot_image_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002280 bool is_host_;
2281 std::string android_root_;
2282 std::vector<const DexFile*> dex_files_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002283 std::string no_inline_from_string_;
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002284 std::vector<jobject> dex_caches_;
Richard Uhlerfbef44d2014-12-23 09:48:51 -08002285 std::vector<std::unique_ptr<const DexFile>> opened_dex_files_;
Andreas Gampe3f30e122015-09-17 14:03:21 -07002286
Vladimir Marko307dac92015-10-20 11:20:09 +01002287 std::unique_ptr<ImageWriter> image_writer_;
2288 std::unique_ptr<CompilerDriver> driver_;
Andreas Gampe3f30e122015-09-17 14:03:21 -07002289
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002290 std::vector<std::string> verbose_methods_;
2291 bool dump_stats_;
2292 bool dump_passes_;
2293 bool dump_timing_;
2294 bool dump_slow_timing_;
David Brazdil866c0312015-01-13 21:21:31 +00002295 std::string dump_cfg_file_name_;
Calin Juravle87000a92015-08-24 15:34:44 +01002296 bool dump_cfg_append_;
Andreas Gampee21dc3d2014-12-08 16:59:43 -08002297 std::string swap_file_name_;
2298 int swap_fd_;
Mathieu Chartiera90c7722015-10-29 15:41:36 -07002299 std::string app_image_file_name_;
2300 int app_image_fd_;
Calin Juravle998c2162015-12-21 15:39:33 +02002301 std::vector<std::string> profile_files_;
2302 std::vector<std::string> reference_profile_files_;
2303 std::unique_ptr<ProfileCompilationInfo> profile_compilation_info_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002304 TimingLogger* timings_;
2305 std::unique_ptr<CumulativeLogger> compiler_phases_timings_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002306 std::vector<std::vector<const DexFile*>> dex_files_per_oat_file_;
2307 std::unordered_map<const DexFile*, const char*> dex_file_oat_filename_map_;
2308
2309 // Backing storage.
2310 std::vector<std::string> char_backing_storage_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002311
2312 DISALLOW_IMPLICIT_CONSTRUCTORS(Dex2Oat);
2313};
2314
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002315static void b13564922() {
2316#if defined(__linux__) && defined(__arm__)
2317 int major, minor;
2318 struct utsname uts;
2319 if (uname(&uts) != -1 &&
2320 sscanf(uts.release, "%d.%d", &major, &minor) == 2 &&
2321 ((major < 3) || ((major == 3) && (minor < 4)))) {
2322 // Kernels before 3.4 don't handle the ASLR well and we can run out of address
2323 // space (http://b/13564922). Work around the issue by inhibiting further mmap() randomization.
2324 int old_personality = personality(0xffffffff);
2325 if ((old_personality & ADDR_NO_RANDOMIZE) == 0) {
2326 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
2327 if (new_personality == -1) {
2328 LOG(WARNING) << "personality(. | ADDR_NO_RANDOMIZE) failed.";
2329 }
2330 }
2331 }
2332#endif
2333}
2334
Andreas Gampe10e477d2014-11-19 12:57:42 -08002335static int CompileImage(Dex2Oat& dex2oat) {
2336 dex2oat.Compile();
2337
Jeff Haodcdc85b2015-12-04 14:06:18 -08002338 if (!dex2oat.CreateOatFiles()) {
2339 dex2oat.EraseOatFiles();
Andreas Gampe10e477d2014-11-19 12:57:42 -08002340 return EXIT_FAILURE;
2341 }
2342
Jeff Haodcdc85b2015-12-04 14:06:18 -08002343 // Close the image oat files. We always expect the output file by name, and it will be
2344 // re-opened from the unstripped name. Note: it's easier to *flush* and close...
2345 if (!dex2oat.FlushCloseOatFiles()) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08002346 return EXIT_FAILURE;
2347 }
2348
Jeff Haodcdc85b2015-12-04 14:06:18 -08002349 // Creates the boot.art and patches the oat files.
Andreas Gampe10e477d2014-11-19 12:57:42 -08002350 if (!dex2oat.HandleImage()) {
2351 return EXIT_FAILURE;
2352 }
2353
2354 // When given --host, finish early without stripping.
2355 if (dex2oat.IsHost()) {
2356 dex2oat.DumpTiming();
2357 return EXIT_SUCCESS;
2358 }
2359
Jeff Haodcdc85b2015-12-04 14:06:18 -08002360 // Copy stripped to unstripped location, if necessary.
2361 if (!dex2oat.CopyStrippedToUnstripped()) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08002362 return EXIT_FAILURE;
2363 }
2364
Jeff Haodcdc85b2015-12-04 14:06:18 -08002365 // FlushClose again, as stripping might have re-opened the oat files.
2366 if (!dex2oat.FlushCloseOatFiles()) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08002367 return EXIT_FAILURE;
2368 }
2369
2370 dex2oat.DumpTiming();
2371 return EXIT_SUCCESS;
2372}
2373
2374static int CompileApp(Dex2Oat& dex2oat) {
2375 dex2oat.Compile();
2376
Jeff Haodcdc85b2015-12-04 14:06:18 -08002377 if (!dex2oat.CreateOatFiles()) {
2378 dex2oat.EraseOatFiles();
Andreas Gampe10e477d2014-11-19 12:57:42 -08002379 return EXIT_FAILURE;
2380 }
2381
Jeff Haodcdc85b2015-12-04 14:06:18 -08002382 // Do not close the oat files here. We might have gotten the output file by file descriptor,
Andreas Gampe10e477d2014-11-19 12:57:42 -08002383 // which we would lose.
Andreas Gampe10e477d2014-11-19 12:57:42 -08002384
2385 // When given --host, finish early without stripping.
2386 if (dex2oat.IsHost()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002387 if (!dex2oat.FlushCloseOatFiles()) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08002388 return EXIT_FAILURE;
2389 }
2390
2391 dex2oat.DumpTiming();
2392 return EXIT_SUCCESS;
2393 }
2394
Jeff Haodcdc85b2015-12-04 14:06:18 -08002395 // Copy stripped to unstripped location, if necessary. This will implicitly flush & close the
2396 // stripped versions. If this is given, we expect to be able to open writable files by name.
2397 if (!dex2oat.CopyStrippedToUnstripped()) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08002398 return EXIT_FAILURE;
2399 }
2400
Jeff Haodcdc85b2015-12-04 14:06:18 -08002401 // Flush and close the files.
2402 if (!dex2oat.FlushCloseOatFiles()) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08002403 return EXIT_FAILURE;
2404 }
2405
2406 dex2oat.DumpTiming();
2407 return EXIT_SUCCESS;
2408}
2409
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002410static int dex2oat(int argc, char** argv) {
2411 b13564922();
2412
2413 TimingLogger timings("compiler", false, false);
2414
2415 Dex2Oat dex2oat(&timings);
2416
2417 // Parse arguments. Argument mistakes will lead to exit(EXIT_FAILURE) in UsageError.
2418 dex2oat.ParseArgs(argc, argv);
2419
Calin Juravle998c2162015-12-21 15:39:33 +02002420 // Process profile information and assess if we need to do a profile guided compilation.
2421 // This operation involves I/O.
2422 if (dex2oat.UseProfileGuidedCompilation()) {
2423 if (dex2oat.ProcessProfiles()) {
2424 if (!dex2oat.ShouldCompileBasedOnProfiles()) {
2425 LOG(INFO) << "Skipped compilation because of insignificant profile delta";
2426 return EXIT_SUCCESS;
2427 }
2428 } else {
2429 LOG(WARNING) << "Failed to process profile files";
2430 return EXIT_FAILURE;
2431 }
2432 }
2433
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002434 // Check early that the result of compilation can be written
2435 if (!dex2oat.OpenFile()) {
2436 return EXIT_FAILURE;
2437 }
2438
Andreas Gampe046c7062015-05-18 23:22:54 -07002439 // Print the complete line when any of the following is true:
2440 // 1) Debug build
2441 // 2) Compiling an image
2442 // 3) Compiling with --host
2443 // 4) Compiling on the host (not a target build)
2444 // Otherwise, print a stripped command line.
Mathieu Chartiera90c7722015-10-29 15:41:36 -07002445 if (kIsDebugBuild || dex2oat.IsBootImage() || dex2oat.IsHost() || !kIsTargetBuild) {
Andreas Gampe046c7062015-05-18 23:22:54 -07002446 LOG(INFO) << CommandLine();
2447 } else {
2448 LOG(INFO) << StrippedCommandLine();
2449 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002450
2451 if (!dex2oat.Setup()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002452 dex2oat.EraseOatFiles();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002453 return EXIT_FAILURE;
2454 }
2455
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002456 bool result;
Andreas Gampe10e477d2014-11-19 12:57:42 -08002457 if (dex2oat.IsImage()) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002458 result = CompileImage(dex2oat);
Andreas Gampe10e477d2014-11-19 12:57:42 -08002459 } else {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002460 result = CompileApp(dex2oat);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002461 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002462
2463 dex2oat.Shutdown();
2464 return result;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002465}
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002466} // namespace art
Brian Carlstrom7940e442013-07-12 13:46:57 -07002467
2468int main(int argc, char** argv) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002469 int result = art::dex2oat(argc, argv);
2470 // Everything was done, do an explicit exit here to avoid running Runtime destructors that take
2471 // time (bug 10645725) unless we're a debug build or running on valgrind. Note: The Dex2Oat class
2472 // should not destruct the runtime in this case.
Evgenii Stepanov1e133742015-05-20 12:30:59 -07002473 if (!art::kIsDebugBuild && (RUNNING_ON_MEMORY_TOOL == 0)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002474 exit(result);
2475 }
2476 return result;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002477}