blob: c4f68ea9669b7ded13d7f676453027acb186f00d [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.");
316 UsageError(" This generates all the available information. Unneeded parts can be");
317 UsageError(" stripped using standard command line tools such as strip or objcopy.");
318 UsageError(" (enabled by default in debug builds, disabled by default otherwise)");
Alex Light78382fa2014-06-06 15:45:32 -0700319 UsageError("");
David Srbecky8363c772015-05-28 16:12:43 +0100320 UsageError(" --no-generate-debug-info: Do not generate debug information for native debugging.");
David Srbecky8dc73242015-04-12 11:40:39 +0100321 UsageError("");
David Srbecky0cf44932015-12-09 14:09:59 +0000322 UsageError(" --debuggable: Produce code debuggable with Java debugger. Implies -g.");
323 UsageError("");
324 UsageError(" --native-debuggable: Produce code debuggable with native debugger (like LLDB).");
325 UsageError(" Implies --debuggable.");
326 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700327 UsageError(" --runtime-arg <argument>: used to specify various arguments for the runtime,");
328 UsageError(" such as initial heap size, maximum heap size, and verbose output.");
329 UsageError(" Use a separate --runtime-arg switch for each argument.");
330 UsageError(" Example: --runtime-arg -Xms256m");
Jeff Hao4a200f52014-04-01 14:58:49 -0700331 UsageError("");
Dave Allisond6ed6422014-04-09 23:36:15 +0000332 UsageError(" --profile-file=<filename>: specify profiler output file to use for compilation.");
Calin Juravle998c2162015-12-21 15:39:33 +0200333 UsageError(" Can be specified multiple time, in which case the data from the different");
334 UsageError(" profiles will be aggregated.");
335 UsageError("");
336 UsageError(" --reference-profile-file=<filename>: specify a reference profile file to use when");
337 UsageError(" compiling. The data in this file will be compared with the data in the");
338 UsageError(" associated --profile-file and the compilation will proceed only if there is");
339 UsageError(" a significant difference (--reference-profile-file is paired with");
340 UsageError(" --profile-file in the natural order). If the compilation was attempted then");
341 UsageError(" --profile-file will be merged into --reference-profile-file. Valid only when");
342 UsageError(" specified together with --profile-file.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700343 UsageError("");
Chao-ying Fucd8ce662014-03-11 14:57:19 -0700344 UsageError(" --print-pass-names: print a list of pass names");
345 UsageError("");
346 UsageError(" --disable-passes=<pass-names>: disable one or more passes separated by comma.");
347 UsageError(" Example: --disable-passes=UseCount,BBOptimizations");
348 UsageError("");
Razvan A Lupusorubd25d4b2014-07-02 18:16:51 -0700349 UsageError(" --print-pass-options: print a list of passes that have configurable options along "
350 "with the setting.");
351 UsageError(" Will print default if no overridden setting exists.");
352 UsageError("");
353 UsageError(" --pass-options=Pass1Name:Pass1OptionName:Pass1Option#,"
354 "Pass2Name:Pass2OptionName:Pass2Option#");
355 UsageError(" Used to specify a pass specific option. The setting itself must be integer.");
356 UsageError(" Separator used between options is a comma.");
357 UsageError("");
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800358 UsageError(" --swap-file=<file-name>: specifies a file to use for swap.");
359 UsageError(" Example: --swap-file=/data/tmp/swap.001");
360 UsageError("");
361 UsageError(" --swap-fd=<file-descriptor>: specifies a file to use for swap (by descriptor).");
362 UsageError(" Example: --swap-fd=10");
363 UsageError("");
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700364 UsageError(" --app-image-fd=<file-descriptor>: specify output file descriptor for app image.");
365 UsageError(" Example: --app-image-fd=10");
366 UsageError("");
367 UsageError(" --app-image-file=<file-name>: specify a file name for app image.");
368 UsageError(" Example: --app-image-file=/data/dalvik-cache/system@app@Calculator.apk.art");
369 UsageError("");
Jeff Haodcdc85b2015-12-04 14:06:18 -0800370 UsageError(" --multi-image: specify that separate oat and image files be generated for each "
371 "input dex file.");
372 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700373 std::cerr << "See log for usage error information\n";
374 exit(EXIT_FAILURE);
375}
376
Brian Carlstrom7940e442013-07-12 13:46:57 -0700377// The primary goal of the watchdog is to prevent stuck build servers
378// during development when fatal aborts lead to a cascade of failures
379// that result in a deadlock.
380class WatchDog {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800381// WatchDog defines its own CHECK_PTHREAD_CALL to avoid using LOG which uses locks
Brian Carlstrom7940e442013-07-12 13:46:57 -0700382#undef CHECK_PTHREAD_CALL
383#define CHECK_WATCH_DOG_PTHREAD_CALL(call, args, what) \
384 do { \
385 int rc = call args; \
386 if (rc != 0) { \
387 errno = rc; \
388 std::string message(# call); \
389 message += " failed for "; \
390 message += reason; \
391 Fatal(message); \
392 } \
393 } while (false)
394
395 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -0700396 explicit WatchDog(bool is_watch_dog_enabled) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700397 is_watch_dog_enabled_ = is_watch_dog_enabled;
398 if (!is_watch_dog_enabled_) {
399 return;
400 }
401 shutting_down_ = false;
402 const char* reason = "dex2oat watch dog thread startup";
Kenny Root51316382014-05-13 14:59:37 -0700403 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_init, (&mutex_, nullptr), reason);
404 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_init, (&cond_, nullptr), reason);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700405 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_init, (&attr_), reason);
406 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_create, (&pthread_, &attr_, &CallBack, this), reason);
407 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_destroy, (&attr_), reason);
408 }
409 ~WatchDog() {
410 if (!is_watch_dog_enabled_) {
411 return;
412 }
413 const char* reason = "dex2oat watch dog thread shutdown";
414 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
415 shutting_down_ = true;
416 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_signal, (&cond_), reason);
417 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
418
Kenny Root51316382014-05-13 14:59:37 -0700419 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_join, (pthread_, nullptr), reason);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700420
421 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_destroy, (&cond_), reason);
422 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_destroy, (&mutex_), reason);
423 }
424
425 private:
426 static void* CallBack(void* arg) {
427 WatchDog* self = reinterpret_cast<WatchDog*>(arg);
428 ::art::SetThreadName("dex2oat watch dog");
429 self->Wait();
Kenny Root51316382014-05-13 14:59:37 -0700430 return nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700431 }
432
Andreas Gampe794ad762015-02-23 08:12:24 -0800433 NO_RETURN static void Fatal(const std::string& message) {
Andreas Gamped687e372015-04-28 23:16:03 -0700434 // TODO: When we can guarantee it won't prevent shutdown in error cases, move to LOG. However,
435 // it's rather easy to hang in unwinding.
436 // LogLine also avoids ART logging lock issues, as it's really only a wrapper around
437 // logcat logging or stderr output.
438 LogMessage::LogLine(__FILE__, __LINE__, LogSeverity::FATAL, message.c_str());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700439 exit(1);
440 }
441
442 void Wait() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700443 // TODO: tune the multiplier for GC verification, the following is just to make the timeout
444 // large.
Andreas Gamped687e372015-04-28 23:16:03 -0700445 constexpr int64_t multiplier = kVerifyObjectSupport > kVerifyObjectModeFast ? 100 : 1;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700446 timespec timeout_ts;
447 InitTimeSpec(true, CLOCK_REALTIME, multiplier * kWatchDogTimeoutSeconds * 1000, 0, &timeout_ts);
448 const char* reason = "dex2oat watch dog thread waiting";
449 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
450 while (!shutting_down_) {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800451 int rc = TEMP_FAILURE_RETRY(pthread_cond_timedwait(&cond_, &mutex_, &timeout_ts));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700452 if (rc == ETIMEDOUT) {
Andreas Gamped687e372015-04-28 23:16:03 -0700453 Fatal(StringPrintf("dex2oat did not finish after %" PRId64 " seconds",
454 kWatchDogTimeoutSeconds));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700455 } else if (rc != 0) {
456 std::string message(StringPrintf("pthread_cond_timedwait failed: %s",
457 strerror(errno)));
458 Fatal(message.c_str());
459 }
460 }
461 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
462 }
463
464 // 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 -0700465 // Debug builds are slower so they have larger timeouts.
Andreas Gamped687e372015-04-28 23:16:03 -0700466 static constexpr int64_t kSlowdownFactor = kIsDebugBuild ? 5U : 1U;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800467
Andreas Gampe540138a2015-09-14 15:34:38 -0700468 // 9.5 minutes scaled by kSlowdownFactor. This is slightly smaller than the Package Manager
469 // watchdog (PackageManagerService.WATCHDOG_TIMEOUT, 10 minutes), so that dex2oat will abort
470 // itself before that watchdog would take down the system server.
471 static constexpr int64_t kWatchDogTimeoutSeconds = kSlowdownFactor * (9 * 60 + 30);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700472
473 bool is_watch_dog_enabled_;
474 bool shutting_down_;
475 // TODO: Switch to Mutex when we can guarantee it won't prevent shutdown in error cases.
476 pthread_mutex_t mutex_;
477 pthread_cond_t cond_;
478 pthread_attr_t attr_;
479 pthread_t pthread_;
480};
Brian Carlstrom7940e442013-07-12 13:46:57 -0700481
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800482static constexpr size_t kMinDexFilesForSwap = 2;
483static constexpr size_t kMinDexFileCumulativeSizeForSwap = 20 * MB;
484
485static bool UseSwap(bool is_image, std::vector<const DexFile*>& dex_files) {
486 if (is_image) {
487 // Don't use swap, we know generation should succeed, and we don't want to slow it down.
488 return false;
489 }
490 if (dex_files.size() < kMinDexFilesForSwap) {
491 // If there are less dex files than the threshold, assume it's gonna be fine.
492 return false;
493 }
494 size_t dex_files_size = 0;
495 for (const auto* dex_file : dex_files) {
496 dex_files_size += dex_file->GetHeader().file_size_;
497 }
498 return dex_files_size >= kMinDexFileCumulativeSizeForSwap;
499}
500
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800501class Dex2Oat FINAL {
502 public:
503 explicit Dex2Oat(TimingLogger* timings) :
Nicolas Geoffray409e8092015-10-01 10:32:19 +0100504 compiler_kind_(Compiler::kOptimizing),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800505 instruction_set_(kRuntimeISA),
506 // Take the default set of instruction features from the build.
Andreas Gampe3f30e122015-09-17 14:03:21 -0700507 verification_results_(nullptr),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800508 method_inliner_map_(),
509 runtime_(nullptr),
510 thread_count_(sysconf(_SC_NPROCESSORS_CONF)),
511 start_ns_(NanoTime()),
512 oat_fd_(-1),
513 zip_fd_(-1),
514 image_base_(0U),
515 image_classes_zip_filename_(nullptr),
516 image_classes_filename_(nullptr),
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800517 image_storage_mode_(ImageHeader::kStorageModeUncompressed),
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800518 compiled_classes_zip_filename_(nullptr),
519 compiled_classes_filename_(nullptr),
Andreas Gampe70bef0d2015-04-15 02:37:28 -0700520 compiled_methods_zip_filename_(nullptr),
521 compiled_methods_filename_(nullptr),
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700522 app_image_(false),
523 boot_image_(false),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800524 is_host_(false),
Vladimir Marko10c13562015-11-25 14:33:36 +0000525 image_writer_(nullptr),
Andreas Gampe3f30e122015-09-17 14:03:21 -0700526 driver_(nullptr),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800527 dump_stats_(false),
528 dump_passes_(false),
529 dump_timing_(false),
530 dump_slow_timing_(kIsDebugBuild),
Calin Juravle87000a92015-08-24 15:34:44 +0100531 dump_cfg_append_(false),
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800532 swap_fd_(-1),
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700533 app_image_fd_(kInvalidImageFd),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800534 timings_(timings) {}
535
536 ~Dex2Oat() {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800537 // Free opened dex files before deleting the runtime_, because ~DexFile
538 // uses MemMap, which is shut down by ~Runtime.
539 class_path_files_.clear();
540 opened_dex_files_.clear();
541
542 // Log completion time before deleting the runtime_, because this accesses
543 // the runtime.
544 LogCompletionTime();
545
Vladimir Marko307dac92015-10-20 11:20:09 +0100546 if (!kIsDebugBuild && !(RUNNING_ON_MEMORY_TOOL && kMemoryToolDetectsLeaks)) {
547 // We want to just exit on non-debug builds, not bringing the runtime down
548 // in an orderly fashion. So release the following fields.
549 driver_.release();
550 image_writer_.release();
551 for (std::unique_ptr<const DexFile>& dex_file : opened_dex_files_) {
552 dex_file.release();
553 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800554 for (std::unique_ptr<File>& oat_file : oat_files_) {
555 oat_file.release();
556 }
Vladimir Marko307dac92015-10-20 11:20:09 +0100557 runtime_.release();
558 verification_results_.release();
559 key_value_store_.release();
Vladimir Markof94b7812014-06-05 15:48:04 +0100560 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700561 }
562
Roland Levillain9ec5e222015-08-17 20:18:41 +0100563 struct ParserOptions {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800564 std::vector<const char*> oat_symbols;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800565 std::string boot_image_filename;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800566 bool watch_dog_enabled = true;
Nicolas Geoffray1412dfa2015-03-20 14:48:13 +0000567 bool requested_specific_compiler = false;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800568 std::string error_msg;
Roland Levillain9ec5e222015-08-17 20:18:41 +0100569 };
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800570
Roland Levillain9ec5e222015-08-17 20:18:41 +0100571 void ParseZipFd(const StringPiece& option) {
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000572 ParseUintOption(option, "--zip-fd", &zip_fd_, Usage);
Roland Levillain9ec5e222015-08-17 20:18:41 +0100573 }
574
575 void ParseOatFd(const StringPiece& option) {
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000576 ParseUintOption(option, "--oat-fd", &oat_fd_, Usage);
Roland Levillain9ec5e222015-08-17 20:18:41 +0100577 }
578
579 void ParseJ(const StringPiece& option) {
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000580 ParseUintOption(option, "-j", &thread_count_, Usage, /* is_long_option */ false);
Roland Levillain9ec5e222015-08-17 20:18:41 +0100581 }
582
583 void ParseBase(const StringPiece& option) {
584 DCHECK(option.starts_with("--base="));
585 const char* image_base_str = option.substr(strlen("--base=")).data();
586 char* end;
587 image_base_ = strtoul(image_base_str, &end, 16);
588 if (end == image_base_str || *end != '\0') {
589 Usage("Failed to parse hexadecimal value for option %s", option.data());
590 }
591 }
592
593 void ParseInstructionSet(const StringPiece& option) {
594 DCHECK(option.starts_with("--instruction-set="));
595 StringPiece instruction_set_str = option.substr(strlen("--instruction-set=")).data();
596 // StringPiece is not necessarily zero-terminated, so need to make a copy and ensure it.
597 std::unique_ptr<char[]> buf(new char[instruction_set_str.length() + 1]);
598 strncpy(buf.get(), instruction_set_str.data(), instruction_set_str.length());
599 buf.get()[instruction_set_str.length()] = 0;
600 instruction_set_ = GetInstructionSetFromString(buf.get());
601 // arm actually means thumb2.
602 if (instruction_set_ == InstructionSet::kArm) {
603 instruction_set_ = InstructionSet::kThumb2;
604 }
605 }
606
607 void ParseInstructionSetVariant(const StringPiece& option, ParserOptions* parser_options) {
608 DCHECK(option.starts_with("--instruction-set-variant="));
609 StringPiece str = option.substr(strlen("--instruction-set-variant=")).data();
610 instruction_set_features_.reset(
611 InstructionSetFeatures::FromVariant(
612 instruction_set_, str.as_string(), &parser_options->error_msg));
613 if (instruction_set_features_.get() == nullptr) {
614 Usage("%s", parser_options->error_msg.c_str());
615 }
616 }
617
618 void ParseInstructionSetFeatures(const StringPiece& option, ParserOptions* parser_options) {
619 DCHECK(option.starts_with("--instruction-set-features="));
620 StringPiece str = option.substr(strlen("--instruction-set-features=")).data();
621 if (instruction_set_features_.get() == nullptr) {
622 instruction_set_features_.reset(
623 InstructionSetFeatures::FromVariant(
624 instruction_set_, "default", &parser_options->error_msg));
625 if (instruction_set_features_.get() == nullptr) {
626 Usage("Problem initializing default instruction set features variant: %s",
627 parser_options->error_msg.c_str());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700628 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800629 }
Roland Levillain9ec5e222015-08-17 20:18:41 +0100630 instruction_set_features_.reset(
631 instruction_set_features_->AddFeaturesFromString(str.as_string(),
632 &parser_options->error_msg));
633 if (instruction_set_features_.get() == nullptr) {
634 Usage("Error parsing '%s': %s", option.data(), parser_options->error_msg.c_str());
635 }
636 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800637
Roland Levillain9ec5e222015-08-17 20:18:41 +0100638 void ParseCompilerBackend(const StringPiece& option, ParserOptions* parser_options) {
639 DCHECK(option.starts_with("--compiler-backend="));
640 parser_options->requested_specific_compiler = true;
641 StringPiece backend_str = option.substr(strlen("--compiler-backend=")).data();
642 if (backend_str == "Quick") {
643 compiler_kind_ = Compiler::kQuick;
644 } else if (backend_str == "Optimizing") {
645 compiler_kind_ = Compiler::kOptimizing;
646 } else {
647 Usage("Unknown compiler backend: %s", backend_str.data());
648 }
649 }
650
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800651 void ParseImageFormat(const StringPiece& option) {
652 const StringPiece substr("--image-format=");
653 DCHECK(option.starts_with(substr));
654 const StringPiece format_str = option.substr(substr.length());
655 if (format_str == "lz4") {
656 image_storage_mode_ = ImageHeader::kStorageModeLZ4;
657 } else if (format_str == "uncompressed") {
658 image_storage_mode_ = ImageHeader::kStorageModeUncompressed;
659 } else {
660 Usage("Unknown image format: %s", format_str.data());
661 }
662 }
663
Jeff Haodcdc85b2015-12-04 14:06:18 -0800664 void ProcessOptions(ParserOptions* parser_options, bool multi_image) {
665 boot_image_ = !image_filenames_.empty();
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700666 app_image_ = app_image_fd_ != -1 || !app_image_file_name_.empty();
667
668 if (IsAppImage() && IsBootImage()) {
669 Usage("Can't have both --image and (--app-image-fd or --app-image-file)");
670 }
671
672 if (IsBootImage()) {
Nicolas Geoffray409e8092015-10-01 10:32:19 +0100673 // We need the boot image to always be debuggable.
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000674 compiler_options_->debuggable_ = true;
Nicolas Geoffray1412dfa2015-03-20 14:48:13 +0000675 }
Nicolas Geoffray9bb492a2014-11-25 23:42:00 +0000676
Jeff Haodcdc85b2015-12-04 14:06:18 -0800677 if (oat_filenames_.empty() && oat_fd_ == -1) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800678 Usage("Output must be supplied with either --oat-file or --oat-fd");
679 }
680
Jeff Haodcdc85b2015-12-04 14:06:18 -0800681 if (!oat_filenames_.empty() && oat_fd_ != -1) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800682 Usage("--oat-file should not be used with --oat-fd");
683 }
684
Roland Levillain9ec5e222015-08-17 20:18:41 +0100685 if (!parser_options->oat_symbols.empty() && oat_fd_ != -1) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800686 Usage("--oat-symbols should not be used with --oat-fd");
687 }
688
Roland Levillain9ec5e222015-08-17 20:18:41 +0100689 if (!parser_options->oat_symbols.empty() && is_host_) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800690 Usage("--oat-symbols should not be used with --host");
691 }
692
Jeff Haodcdc85b2015-12-04 14:06:18 -0800693 if (oat_fd_ != -1 && !image_filenames_.empty()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800694 Usage("--oat-fd should not be used with --image");
695 }
696
Jeff Haodcdc85b2015-12-04 14:06:18 -0800697 if (!parser_options->oat_symbols.empty() &&
698 parser_options->oat_symbols.size() != oat_filenames_.size()) {
699 Usage("--oat-file arguments do not match --oat-symbols arguments");
700 }
701
702 if (!image_filenames_.empty() && image_filenames_.size() != oat_filenames_.size()) {
703 Usage("--oat-file arguments do not match --image arguments");
704 }
705
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800706 if (android_root_.empty()) {
707 const char* android_root_env_var = getenv("ANDROID_ROOT");
708 if (android_root_env_var == nullptr) {
709 Usage("--android-root unspecified and ANDROID_ROOT not set");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700710 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800711 android_root_ += android_root_env_var;
712 }
713
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700714 if (!boot_image_ && parser_options->boot_image_filename.empty()) {
Roland Levillain9ec5e222015-08-17 20:18:41 +0100715 parser_options->boot_image_filename += android_root_;
716 parser_options->boot_image_filename += "/framework/boot.art";
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800717 }
Roland Levillain9ec5e222015-08-17 20:18:41 +0100718 if (!parser_options->boot_image_filename.empty()) {
Vladimir Marko49b0f452015-12-10 13:49:19 +0000719 boot_image_filename_ = parser_options->boot_image_filename;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800720 }
721
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700722 if (image_classes_filename_ != nullptr && !IsBootImage()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800723 Usage("--image-classes should only be used with --image");
724 }
725
Vladimir Marko49b0f452015-12-10 13:49:19 +0000726 if (image_classes_filename_ != nullptr && !boot_image_filename_.empty()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800727 Usage("--image-classes should not be used with --boot-image");
728 }
729
730 if (image_classes_zip_filename_ != nullptr && image_classes_filename_ == nullptr) {
731 Usage("--image-classes-zip should be used with --image-classes");
732 }
733
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700734 if (compiled_classes_filename_ != nullptr && !IsBootImage()) {
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800735 Usage("--compiled-classes should only be used with --image");
736 }
737
Vladimir Marko49b0f452015-12-10 13:49:19 +0000738 if (compiled_classes_filename_ != nullptr && !boot_image_filename_.empty()) {
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800739 Usage("--compiled-classes should not be used with --boot-image");
740 }
741
742 if (compiled_classes_zip_filename_ != nullptr && compiled_classes_filename_ == nullptr) {
743 Usage("--compiled-classes-zip should be used with --compiled-classes");
744 }
745
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800746 if (dex_filenames_.empty() && zip_fd_ == -1) {
747 Usage("Input must be supplied with either --dex-file or --zip-fd");
748 }
749
750 if (!dex_filenames_.empty() && zip_fd_ != -1) {
751 Usage("--dex-file should not be used with --zip-fd");
752 }
753
754 if (!dex_filenames_.empty() && !zip_location_.empty()) {
755 Usage("--dex-file should not be used with --zip-location");
756 }
757
758 if (dex_locations_.empty()) {
759 for (const char* dex_file_name : dex_filenames_) {
760 dex_locations_.push_back(dex_file_name);
761 }
762 } else if (dex_locations_.size() != dex_filenames_.size()) {
763 Usage("--dex-location arguments do not match --dex-file arguments");
764 }
765
Jeff Haodcdc85b2015-12-04 14:06:18 -0800766 if (!dex_filenames_.empty() && !oat_filenames_.empty()) {
767 if (oat_filenames_.size() != 1 && oat_filenames_.size() != dex_filenames_.size()) {
768 Usage("--oat-file arguments must be singular or match --dex-file arguments");
769 }
770 }
771
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800772 if (zip_fd_ != -1 && zip_location_.empty()) {
773 Usage("--zip-location should be supplied with --zip-fd");
774 }
775
Vladimir Marko49b0f452015-12-10 13:49:19 +0000776 if (boot_image_filename_.empty()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800777 if (image_base_ == 0) {
778 Usage("Non-zero --base not specified");
779 }
780 }
781
Calin Juravle998c2162015-12-21 15:39:33 +0200782 if (!profile_files_.empty()) {
783 if (!reference_profile_files_.empty() &&
784 (reference_profile_files_.size() != profile_files_.size())) {
785 Usage("If specified, --reference-profile-file should match the number of --profile-file.");
786 }
787 }
788
Roland Levillain9ec5e222015-08-17 20:18:41 +0100789 if (!parser_options->oat_symbols.empty()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800790 oat_unstripped_ = std::move(parser_options->oat_symbols);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800791 }
792
793 // If no instruction set feature was given, use the default one for the target
794 // instruction set.
795 if (instruction_set_features_.get() == nullptr) {
796 instruction_set_features_.reset(
Roland Levillain9ec5e222015-08-17 20:18:41 +0100797 InstructionSetFeatures::FromVariant(
798 instruction_set_, "default", &parser_options->error_msg));
Ian Rogersd582fa42014-11-05 23:46:43 -0800799 if (instruction_set_features_.get() == nullptr) {
800 Usage("Problem initializing default instruction set features variant: %s",
Roland Levillain9ec5e222015-08-17 20:18:41 +0100801 parser_options->error_msg.c_str());
Ian Rogersd582fa42014-11-05 23:46:43 -0800802 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800803 }
804
805 if (instruction_set_ == kRuntimeISA) {
806 std::unique_ptr<const InstructionSetFeatures> runtime_features(
807 InstructionSetFeatures::FromCppDefines());
808 if (!instruction_set_features_->Equals(runtime_features.get())) {
809 LOG(WARNING) << "Mismatch between dex2oat instruction set features ("
810 << *instruction_set_features_ << ") and those of dex2oat executable ("
811 << *runtime_features <<") for the command line:\n"
812 << CommandLine();
813 }
814 }
815
Roland Levillaina215b952015-08-07 11:38:32 +0100816 // It they are not set, use default values for inlining settings.
817 // TODO: We should rethink the compiler filter. We mostly save
818 // time here, which is orthogonal to space.
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000819 if (compiler_options_->inline_depth_limit_ == CompilerOptions::kUnsetInlineDepthLimit) {
820 compiler_options_->inline_depth_limit_ =
821 (compiler_options_->compiler_filter_ == CompilerOptions::kSpace)
Roland Levillaina215b952015-08-07 11:38:32 +0100822 // Implementation of the space filter: limit inlining depth.
823 ? CompilerOptions::kSpaceFilterInlineDepthLimit
824 : CompilerOptions::kDefaultInlineDepthLimit;
825 }
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000826 if (compiler_options_->inline_max_code_units_ == CompilerOptions::kUnsetInlineMaxCodeUnits) {
827 compiler_options_->inline_max_code_units_ =
828 (compiler_options_->compiler_filter_ == CompilerOptions::kSpace)
Roland Levillaina215b952015-08-07 11:38:32 +0100829 // Implementation of the space filter: limit inlining max code units.
830 ? CompilerOptions::kSpaceFilterInlineMaxCodeUnits
831 : CompilerOptions::kDefaultInlineMaxCodeUnits;
832 }
833
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800834 // Checks are all explicit until we know the architecture.
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800835 // Set the compilation target's implicit checks options.
836 switch (instruction_set_) {
837 case kArm:
838 case kThumb2:
839 case kArm64:
840 case kX86:
841 case kX86_64:
Douglas Leung22bb5a22015-07-02 16:42:08 -0700842 case kMips:
843 case kMips64:
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000844 compiler_options_->implicit_null_checks_ = true;
845 compiler_options_->implicit_so_checks_ = true;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800846 break;
847
848 default:
849 // Defaults are correct.
850 break;
851 }
852
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000853 compiler_options_->verbose_methods_ = verbose_methods_.empty() ? nullptr : &verbose_methods_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800854
Jeff Haodcdc85b2015-12-04 14:06:18 -0800855 if (!IsBootImage() && multi_image) {
856 Usage("--multi-image can only be used when creating boot images");
857 }
858 if (IsBootImage() && multi_image && image_filenames_.size() > 1) {
859 Usage("--multi-image cannot be used with multiple image names");
860 }
861
862 // For now, if we're on the host and compile the boot image, *always* use multiple image files.
863 if (!kIsTargetBuild && IsBootImage()) {
864 if (image_filenames_.size() == 1) {
865 multi_image = true;
866 }
867 }
868
869 if (IsBootImage() && multi_image) {
870 // Expand the oat and image filenames.
871 std::string base_oat = oat_filenames_[0];
872 size_t last_oat_slash = base_oat.rfind('/');
873 if (last_oat_slash == std::string::npos) {
874 Usage("--multi-image used with unusable oat filename %s", base_oat.c_str());
875 }
Andreas Gampe8994a042015-12-30 19:03:17 +0000876 // We also need to honor path components that were encoded through '@'. Otherwise the loading
877 // code won't be able to find the images.
878 if (base_oat.find('@', last_oat_slash) != std::string::npos) {
879 last_oat_slash = base_oat.rfind('@');
880 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800881 base_oat = base_oat.substr(0, last_oat_slash + 1);
882
883 std::string base_img = image_filenames_[0];
884 size_t last_img_slash = base_img.rfind('/');
885 if (last_img_slash == std::string::npos) {
886 Usage("--multi-image used with unusable image filename %s", base_img.c_str());
887 }
Andreas Gampe8994a042015-12-30 19:03:17 +0000888 // We also need to honor path components that were encoded through '@'. Otherwise the loading
889 // code won't be able to find the images.
890 if (base_img.find('@', last_img_slash) != std::string::npos) {
891 last_img_slash = base_img.rfind('@');
892 }
893
894 // Get the prefix, which is the primary image name (without path components). Strip the
895 // extension.
896 std::string prefix = base_img.substr(last_img_slash + 1);
897 if (prefix.rfind('.') != std::string::npos) {
898 prefix = prefix.substr(0, prefix.rfind('.'));
899 }
900 if (!prefix.empty()) {
901 prefix = prefix + "-";
902 }
903
Jeff Haodcdc85b2015-12-04 14:06:18 -0800904 base_img = base_img.substr(0, last_img_slash + 1);
905
Jeff Haodcdc85b2015-12-04 14:06:18 -0800906 // Note: we have some special case here for our testing. We have to inject the differentiating
907 // parts for the different core images.
908 std::string infix; // Empty infix by default.
909 {
910 // Check the first name.
911 std::string dex_file = oat_filenames_[0];
912 size_t last_dex_slash = dex_file.rfind('/');
913 if (last_dex_slash != std::string::npos) {
914 dex_file = dex_file.substr(last_dex_slash + 1);
915 }
916 size_t last_dex_dot = dex_file.rfind('.');
917 if (last_dex_dot != std::string::npos) {
918 dex_file = dex_file.substr(0, last_dex_dot);
919 }
920 if (StartsWith(dex_file, "core-")) {
921 infix = dex_file.substr(strlen("core"));
922 }
923 }
Andreas Gampe8994a042015-12-30 19:03:17 +0000924
925 // Now create the other names. Use a counted loop to skip the first one.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800926 for (size_t i = 1; i < dex_locations_.size(); ++i) {
927 // TODO: Make everything properly std::string.
Andreas Gampe8994a042015-12-30 19:03:17 +0000928 std::string image_name = CreateMultiImageName(dex_locations_[i], prefix, infix, ".art");
Jeff Haodcdc85b2015-12-04 14:06:18 -0800929 char_backing_storage_.push_back(base_img + image_name);
930 image_filenames_.push_back((char_backing_storage_.end() - 1)->c_str());
931
Andreas Gampe8994a042015-12-30 19:03:17 +0000932 std::string oat_name = CreateMultiImageName(dex_locations_[i], prefix, infix, ".oat");
Jeff Haodcdc85b2015-12-04 14:06:18 -0800933 char_backing_storage_.push_back(base_oat + oat_name);
934 oat_filenames_.push_back((char_backing_storage_.end() - 1)->c_str());
935 }
936 }
937
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800938 // Done with usage checks, enable watchdog if requested
Roland Levillain9ec5e222015-08-17 20:18:41 +0100939 if (parser_options->watch_dog_enabled) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800940 watchdog_.reset(new WatchDog(true));
941 }
942
943 // Fill some values into the key-value store for the oat header.
944 key_value_store_.reset(new SafeMap<std::string, std::string>());
Roland Levillain9ec5e222015-08-17 20:18:41 +0100945 }
946
Andreas Gampe8994a042015-12-30 19:03:17 +0000947 // Modify the input string in the following way:
948 // 0) Assume input is /a/b/c.d
949 // 1) Strip the path -> c.d
950 // 2) Inject prefix p -> pc.d
951 // 3) Inject infix i -> pci.d
952 // 4) Replace suffix with s if it's "jar" -> d == "jar" -> pci.s
Jeff Haodcdc85b2015-12-04 14:06:18 -0800953 static std::string CreateMultiImageName(std::string in,
Andreas Gampe8994a042015-12-30 19:03:17 +0000954 const std::string& prefix,
Jeff Haodcdc85b2015-12-04 14:06:18 -0800955 const std::string& infix,
Andreas Gampe8994a042015-12-30 19:03:17 +0000956 const char* replace_suffix) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800957 size_t last_dex_slash = in.rfind('/');
958 if (last_dex_slash != std::string::npos) {
959 in = in.substr(last_dex_slash + 1);
960 }
Andreas Gampe8994a042015-12-30 19:03:17 +0000961 if (!prefix.empty()) {
962 in = prefix + in;
963 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800964 if (!infix.empty()) {
965 // Inject infix.
966 size_t last_dot = in.rfind('.');
967 if (last_dot != std::string::npos) {
968 in.insert(last_dot, infix);
969 }
970 }
971 if (EndsWith(in, ".jar")) {
Andreas Gampe8994a042015-12-30 19:03:17 +0000972 in = in.substr(0, in.length() - strlen(".jar")) +
973 (replace_suffix != nullptr ? replace_suffix : "");
Jeff Haodcdc85b2015-12-04 14:06:18 -0800974 }
975 return in;
976 }
977
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000978 void InsertCompileOptions(int argc, char** argv) {
Roland Levillain9ec5e222015-08-17 20:18:41 +0100979 std::ostringstream oss;
980 for (int i = 0; i < argc; ++i) {
981 if (i > 0) {
982 oss << ' ';
983 }
984 oss << argv[i];
985 }
986 key_value_store_->Put(OatHeader::kDex2OatCmdLineKey, oss.str());
987 oss.str(""); // Reset.
988 oss << kRuntimeISA;
989 key_value_store_->Put(OatHeader::kDex2OatHostKey, oss.str());
990 key_value_store_->Put(
991 OatHeader::kPicKey,
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000992 compiler_options_->compile_pic_ ? OatHeader::kTrueValue : OatHeader::kFalseValue);
Roland Levillain9ec5e222015-08-17 20:18:41 +0100993 key_value_store_->Put(
994 OatHeader::kDebuggableKey,
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000995 compiler_options_->debuggable_ ? OatHeader::kTrueValue : OatHeader::kFalseValue);
Roland Levillain9ec5e222015-08-17 20:18:41 +0100996 }
997
998 // Parse the arguments from the command line. In case of an unrecognized option or impossible
999 // values/combinations, a usage error will be displayed and exit() is called. Thus, if the method
1000 // returns, arguments have been successfully parsed.
1001 void ParseArgs(int argc, char** argv) {
1002 original_argc = argc;
1003 original_argv = argv;
1004
1005 InitLogging(argv);
1006
1007 // Skip over argv[0].
1008 argv++;
1009 argc--;
1010
1011 if (argc == 0) {
1012 Usage("No arguments specified");
1013 }
1014
1015 std::unique_ptr<ParserOptions> parser_options(new ParserOptions());
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001016 compiler_options_.reset(new CompilerOptions());
Roland Levillain9ec5e222015-08-17 20:18:41 +01001017
Jeff Haodcdc85b2015-12-04 14:06:18 -08001018 bool multi_image = false;
1019
Roland Levillain9ec5e222015-08-17 20:18:41 +01001020 for (int i = 0; i < argc; i++) {
1021 const StringPiece option(argv[i]);
1022 const bool log_options = false;
1023 if (log_options) {
1024 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
1025 }
1026 if (option.starts_with("--dex-file=")) {
1027 dex_filenames_.push_back(option.substr(strlen("--dex-file=")).data());
1028 } else if (option.starts_with("--dex-location=")) {
1029 dex_locations_.push_back(option.substr(strlen("--dex-location=")).data());
1030 } else if (option.starts_with("--zip-fd=")) {
1031 ParseZipFd(option);
1032 } else if (option.starts_with("--zip-location=")) {
1033 zip_location_ = option.substr(strlen("--zip-location=")).data();
1034 } else if (option.starts_with("--oat-file=")) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001035 oat_filenames_.push_back(option.substr(strlen("--oat-file=")).data());
Roland Levillain9ec5e222015-08-17 20:18:41 +01001036 } else if (option.starts_with("--oat-symbols=")) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001037 parser_options->oat_symbols.push_back(option.substr(strlen("--oat-symbols=")).data());
Roland Levillain9ec5e222015-08-17 20:18:41 +01001038 } else if (option.starts_with("--oat-fd=")) {
1039 ParseOatFd(option);
1040 } else if (option == "--watch-dog") {
1041 parser_options->watch_dog_enabled = true;
1042 } else if (option == "--no-watch-dog") {
1043 parser_options->watch_dog_enabled = false;
1044 } else if (option.starts_with("-j")) {
1045 ParseJ(option);
1046 } else if (option.starts_with("--oat-location=")) {
1047 oat_location_ = option.substr(strlen("--oat-location=")).data();
1048 } else if (option.starts_with("--image=")) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001049 image_filenames_.push_back(option.substr(strlen("--image=")).data());
Roland Levillain9ec5e222015-08-17 20:18:41 +01001050 } else if (option.starts_with("--image-classes=")) {
1051 image_classes_filename_ = option.substr(strlen("--image-classes=")).data();
1052 } else if (option.starts_with("--image-classes-zip=")) {
1053 image_classes_zip_filename_ = option.substr(strlen("--image-classes-zip=")).data();
Mathieu Chartierceb07b32015-12-10 09:33:21 -08001054 } else if (option.starts_with("--image-format=")) {
1055 ParseImageFormat(option);
Roland Levillain9ec5e222015-08-17 20:18:41 +01001056 } else if (option.starts_with("--compiled-classes=")) {
1057 compiled_classes_filename_ = option.substr(strlen("--compiled-classes=")).data();
1058 } else if (option.starts_with("--compiled-classes-zip=")) {
1059 compiled_classes_zip_filename_ = option.substr(strlen("--compiled-classes-zip=")).data();
1060 } else if (option.starts_with("--compiled-methods=")) {
1061 compiled_methods_filename_ = option.substr(strlen("--compiled-methods=")).data();
1062 } else if (option.starts_with("--compiled-methods-zip=")) {
1063 compiled_methods_zip_filename_ = option.substr(strlen("--compiled-methods-zip=")).data();
1064 } else if (option.starts_with("--base=")) {
1065 ParseBase(option);
1066 } else if (option.starts_with("--boot-image=")) {
1067 parser_options->boot_image_filename = option.substr(strlen("--boot-image=")).data();
1068 } else if (option.starts_with("--android-root=")) {
1069 android_root_ = option.substr(strlen("--android-root=")).data();
1070 } else if (option.starts_with("--instruction-set=")) {
1071 ParseInstructionSet(option);
1072 } else if (option.starts_with("--instruction-set-variant=")) {
1073 ParseInstructionSetVariant(option, parser_options.get());
1074 } else if (option.starts_with("--instruction-set-features=")) {
1075 ParseInstructionSetFeatures(option, parser_options.get());
1076 } else if (option.starts_with("--compiler-backend=")) {
1077 ParseCompilerBackend(option, parser_options.get());
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001078 } else if (option.starts_with("--profile-file=")) {
Calin Juravle998c2162015-12-21 15:39:33 +02001079 profile_files_.push_back(option.substr(strlen("--profile-file=")).ToString());
1080 } else if (option.starts_with("--reference-profile-file=")) {
1081 reference_profile_files_.push_back(
1082 option.substr(strlen("--reference-profile-file=")).ToString());
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001083 } else if (option == "--no-profile-file") {
1084 // No profile
Roland Levillain9ec5e222015-08-17 20:18:41 +01001085 } else if (option == "--host") {
1086 is_host_ = true;
1087 } else if (option == "--runtime-arg") {
1088 if (++i >= argc) {
1089 Usage("Missing required argument for --runtime-arg");
1090 }
1091 if (log_options) {
1092 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
1093 }
1094 runtime_args_.push_back(argv[i]);
1095 } else if (option == "--dump-timing") {
1096 dump_timing_ = true;
1097 } else if (option == "--dump-passes") {
1098 dump_passes_ = true;
1099 } else if (option.starts_with("--dump-cfg=")) {
1100 dump_cfg_file_name_ = option.substr(strlen("--dump-cfg=")).data();
Calin Juravle87000a92015-08-24 15:34:44 +01001101 } else if (option.starts_with("--dump-cfg-append")) {
1102 dump_cfg_append_ = true;
Roland Levillain9ec5e222015-08-17 20:18:41 +01001103 } else if (option == "--dump-stats") {
1104 dump_stats_ = true;
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001105 } else if (option.starts_with("--swap-file=")) {
1106 swap_file_name_ = option.substr(strlen("--swap-file=")).data();
1107 } else if (option.starts_with("--swap-fd=")) {
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001108 ParseUintOption(option, "--swap-fd", &swap_fd_, Usage);
1109 } else if (option.starts_with("--app-image-file=")) {
1110 app_image_file_name_ = option.substr(strlen("--app-image-file=")).data();
1111 } else if (option.starts_with("--app-image-fd=")) {
1112 ParseUintOption(option, "--app-image-fd", &app_image_fd_, Usage);
Roland Levillain9ec5e222015-08-17 20:18:41 +01001113 } else if (option.starts_with("--verbose-methods=")) {
1114 // TODO: rather than switch off compiler logging, make all VLOG(compiler) messages
1115 // conditional on having verbost methods.
1116 gLogVerbosity.compiler = false;
1117 Split(option.substr(strlen("--verbose-methods=")).ToString(), ',', &verbose_methods_);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001118 } else if (option == "--multi-image") {
1119 multi_image = true;
1120 } else if (option.starts_with("--no-inline-from=")) {
1121 no_inline_from_string_ = option.substr(strlen("--no-inline-from=")).data();
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001122 } else if (!compiler_options_->ParseCompilerOption(option, Usage)) {
Roland Levillain9ec5e222015-08-17 20:18:41 +01001123 Usage("Unknown argument %s", option.data());
1124 }
1125 }
1126
Jeff Haodcdc85b2015-12-04 14:06:18 -08001127 ProcessOptions(parser_options.get(), multi_image);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001128
1129 // Insert some compiler things.
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +00001130 InsertCompileOptions(argc, argv);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001131 }
1132
Jeff Haodcdc85b2015-12-04 14:06:18 -08001133 // Check whether the oat output files are writable, and open them for later. Also open a swap
1134 // file, if a name is given.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001135 bool OpenFile() {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001136 bool create_file = oat_fd_ == -1; // as opposed to using open file descriptor
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001137 if (create_file) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001138 for (const char* oat_filename : oat_filenames_) {
1139 std::unique_ptr<File> oat_file(OS::CreateEmptyFile(oat_filename));
1140 if (oat_file.get() == nullptr) {
1141 PLOG(ERROR) << "Failed to create oat file: " << oat_filename;
1142 return false;
1143 }
1144 if (create_file && fchmod(oat_file->Fd(), 0644) != 0) {
1145 PLOG(ERROR) << "Failed to make oat file world readable: " << oat_filename;
1146 oat_file->Erase();
1147 return false;
1148 }
1149 oat_files_.push_back(std::move(oat_file));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001150 }
1151 } else {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001152 std::unique_ptr<File> oat_file(new File(oat_fd_, oat_location_, true));
1153 oat_file->DisableAutoClose();
1154 if (oat_file->SetLength(0) != 0) {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001155 PLOG(WARNING) << "Truncating oat file " << oat_location_ << " failed.";
1156 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001157 if (oat_file.get() == nullptr) {
1158 PLOG(ERROR) << "Failed to create oat file: " << oat_location_;
1159 return false;
1160 }
1161 if (create_file && fchmod(oat_file->Fd(), 0644) != 0) {
1162 PLOG(ERROR) << "Failed to make oat file world readable: " << oat_location_;
1163 oat_file->Erase();
1164 return false;
1165 }
1166 oat_filenames_.push_back(oat_location_.c_str());
1167 oat_files_.push_back(std::move(oat_file));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001168 }
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001169
1170 // Swap file handling.
1171 //
1172 // If the swap fd is not -1, we assume this is the file descriptor of an open but unlinked file
1173 // that we can use for swap.
1174 //
1175 // If the swap fd is -1 and we have a swap-file string, open the given file as a swap file. We
1176 // will immediately unlink to satisfy the swap fd assumption.
1177 if (swap_fd_ == -1 && !swap_file_name_.empty()) {
1178 std::unique_ptr<File> swap_file(OS::CreateEmptyFile(swap_file_name_.c_str()));
1179 if (swap_file.get() == nullptr) {
1180 PLOG(ERROR) << "Failed to create swap file: " << swap_file_name_;
1181 return false;
1182 }
1183 swap_fd_ = swap_file->Fd();
1184 swap_file->MarkUnchecked(); // We don't we to track this, it will be unlinked immediately.
1185 swap_file->DisableAutoClose(); // We'll handle it ourselves, the File object will be
1186 // released immediately.
1187 unlink(swap_file_name_.c_str());
1188 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001189 return true;
1190 }
1191
Jeff Haodcdc85b2015-12-04 14:06:18 -08001192 void EraseOatFiles() {
1193 for (size_t i = 0; i < oat_files_.size(); ++i) {
1194 DCHECK(oat_files_[i].get() != nullptr);
1195 oat_files_[i]->Erase();
1196 oat_files_[i].reset();
1197 }
Andreas Gampea650e702014-12-03 14:28:02 -08001198 }
1199
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001200 void Shutdown() {
1201 ScopedObjectAccess soa(Thread::Current());
1202 for (jobject dex_cache : dex_caches_) {
1203 soa.Env()->DeleteLocalRef(dex_cache);
1204 }
1205 dex_caches_.clear();
1206 }
1207
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001208 // Set up the environment for compilation. Includes starting the runtime and loading/opening the
1209 // boot class path.
1210 bool Setup() {
1211 TimingLogger::ScopedTiming t("dex2oat Setup", timings_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001212 art::MemMap::Init(); // For ZipEntry::ExtractToMemMap.
Vladimir Marko49b0f452015-12-10 13:49:19 +00001213
1214 if (!PrepareImageClasses() || !PrepareCompiledClasses() || !PrepareCompiledMethods()) {
1215 return false;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001216 }
Brian Carlstromd76e0832013-08-29 15:17:42 -07001217
Vladimir Marko307dac92015-10-20 11:20:09 +01001218 verification_results_.reset(new VerificationResults(compiler_options_.get()));
Andreas Gampe4585f872015-03-27 23:45:15 -07001219 callbacks_.reset(new QuickCompilerCallbacks(
Vladimir Marko307dac92015-10-20 11:20:09 +01001220 verification_results_.get(),
Andreas Gampe4585f872015-03-27 23:45:15 -07001221 &method_inliner_map_,
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001222 IsBootImage() ?
Andreas Gampe4585f872015-03-27 23:45:15 -07001223 CompilerCallbacks::CallbackMode::kCompileBootImage :
1224 CompilerCallbacks::CallbackMode::kCompileApp));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001225
Vladimir Marko49b0f452015-12-10 13:49:19 +00001226 RuntimeArgumentMap runtime_options;
1227 if (!PrepareRuntimeOptions(&runtime_options)) {
1228 return false;
Andreas Gampe1d00add2015-02-27 19:35:46 -08001229 }
1230
Andreas Gampec7ae55d2015-09-15 20:04:54 -07001231 {
1232 TimingLogger::ScopedTiming t_runtime("Create runtime", timings_);
Vladimir Marko49b0f452015-12-10 13:49:19 +00001233 if (!CreateRuntime(std::move(runtime_options))) {
Andreas Gampec7ae55d2015-09-15 20:04:54 -07001234 return false;
1235 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001236 }
1237
1238 // Runtime::Create acquired the mutator_lock_ that is normally given away when we
1239 // Runtime::Start, give it away now so that we don't starve GC.
1240 Thread* self = Thread::Current();
1241 self->TransitionFromRunnableToSuspended(kNative);
1242 // If we're doing the image, override the compiler filter to force full compilation. Must be
1243 // done ahead of WellKnownClasses::Init that causes verification. Note: doesn't force
1244 // compilation of class initializers.
1245 // Whilst we're in native take the opportunity to initialize well known classes.
1246 WellKnownClasses::Init(self->GetJniEnv());
1247
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001248 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
Vladimir Marko49b0f452015-12-10 13:49:19 +00001249 if (boot_image_filename_.empty()) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001250 dex_files_ = class_linker->GetBootClassPath();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001251 } else {
Andreas Gampec7ae55d2015-09-15 20:04:54 -07001252 TimingLogger::ScopedTiming t_dex("Opening dex files", timings_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001253 if (dex_filenames_.empty()) {
1254 ATRACE_BEGIN("Opening zip archive from file descriptor");
1255 std::string error_msg;
1256 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(zip_fd_,
1257 zip_location_.c_str(),
1258 &error_msg));
1259 if (zip_archive.get() == nullptr) {
1260 LOG(ERROR) << "Failed to open zip from file descriptor for '" << zip_location_ << "': "
1261 << error_msg;
1262 return false;
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001263 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001264 if (!DexFile::OpenFromZip(*zip_archive.get(), zip_location_, &error_msg, &opened_dex_files_)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001265 LOG(ERROR) << "Failed to open dex from file descriptor for zip file '" << zip_location_
1266 << "': " << error_msg;
1267 return false;
1268 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001269 for (auto& dex_file : opened_dex_files_) {
1270 dex_files_.push_back(dex_file.get());
1271 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001272 ATRACE_END();
1273 } else {
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001274 size_t failure_count = OpenDexFiles(dex_filenames_, dex_locations_, &opened_dex_files_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001275 if (failure_count > 0) {
1276 LOG(ERROR) << "Failed to open some dex files: " << failure_count;
1277 return false;
1278 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001279 for (auto& dex_file : opened_dex_files_) {
1280 dex_files_.push_back(dex_file.get());
1281 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001282 }
1283
1284 constexpr bool kSaveDexInput = false;
1285 if (kSaveDexInput) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00001286 SaveDexInput();
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001287 }
1288 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001289 // Ensure opened dex files are writable for dex-to-dex transformations. Also ensure that
1290 // the dex caches stay live since we don't want class unloading to occur during compilation.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001291 for (const auto& dex_file : dex_files_) {
1292 if (!dex_file->EnableWrite()) {
1293 PLOG(ERROR) << "Failed to make .dex file writeable '" << dex_file->GetLocation() << "'\n";
Andreas Gampe7ba64962014-10-23 11:37:40 -07001294 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001295 ScopedObjectAccess soa(self);
1296 dex_caches_.push_back(soa.AddLocalReference<jobject>(
Mathieu Chartierd57d4542015-10-14 10:55:30 -07001297 class_linker->RegisterDexFile(*dex_file, Runtime::Current()->GetLinearAlloc())));
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001298 dex_file->CreateTypeLookupTable();
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001299 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001300
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001301 // If we use a swap file, ensure we are above the threshold to make it necessary.
1302 if (swap_fd_ != -1) {
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001303 if (!UseSwap(IsBootImage(), dex_files_)) {
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001304 close(swap_fd_);
1305 swap_fd_ = -1;
Andreas Gampef99bcd22015-04-24 16:22:18 -07001306 VLOG(compiler) << "Decided to run without swap.";
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001307 } else {
Andreas Gampef99bcd22015-04-24 16:22:18 -07001308 LOG(INFO) << "Large app, accepted running with swap.";
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001309 }
1310 }
1311 // Note that dex2oat won't close the swap_fd_. The compiler driver's swap space will do that.
1312
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001313 /*
1314 * If we're not in interpret-only or verify-none mode, go ahead and compile small applications.
1315 * Don't bother to check if we're doing the image.
1316 */
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001317 if (!IsBootImage() &&
Brian Carlstrom95b033b2014-12-03 22:29:37 -08001318 compiler_options_->IsCompilationEnabled() &&
1319 compiler_kind_ == Compiler::kQuick) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001320 size_t num_methods = 0;
1321 for (size_t i = 0; i != dex_files_.size(); ++i) {
1322 const DexFile* dex_file = dex_files_[i];
1323 CHECK(dex_file != nullptr);
1324 num_methods += dex_file->NumMethodIds();
1325 }
1326 if (num_methods <= compiler_options_->GetNumDexMethodsThreshold()) {
1327 compiler_options_->SetCompilerFilter(CompilerOptions::kSpeed);
1328 VLOG(compiler) << "Below method threshold, compiling anyways";
1329 }
1330 }
1331
Jeff Haodcdc85b2015-12-04 14:06:18 -08001332 // Organize inputs, handling multi-dex and multiple oat file outputs.
1333 CreateDexOatMappings();
1334
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001335 return true;
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001336 }
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001337
Jeff Haodcdc85b2015-12-04 14:06:18 -08001338 void CreateDexOatMappings() {
1339 if (oat_files_.size() > 1) {
Andreas Gampe8994a042015-12-30 19:03:17 +00001340 // TODO: This needs to change, as it is not a stable mapping. If a dex file is missing,
1341 // the images will be out of whack. b/26317072
Jeff Haodcdc85b2015-12-04 14:06:18 -08001342 size_t index = 0;
1343 for (size_t i = 0; i < oat_files_.size(); ++i) {
Andreas Gampe8994a042015-12-30 19:03:17 +00001344 std::vector<const DexFile*> dex_files;
1345 if (index < dex_files_.size()) {
Nicolas Geoffrayde38b792015-12-30 14:50:12 +00001346 dex_files.push_back(dex_files_[index]);
Andreas Gampe8994a042015-12-30 19:03:17 +00001347 dex_file_oat_filename_map_.emplace(dex_files_[index], oat_filenames_[i]);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001348 index++;
Andreas Gampe8994a042015-12-30 19:03:17 +00001349 while (index < dex_files_.size() &&
1350 (dex_files_[index]->GetBaseLocation() == dex_files_[index - 1]->GetBaseLocation())) {
1351 dex_file_oat_filename_map_.emplace(dex_files_[index], oat_filenames_[i]);
1352 dex_files.push_back(dex_files_[index]);
1353 index++;
1354 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001355 }
1356 dex_files_per_oat_file_.push_back(std::move(dex_files));
1357 }
1358 } else {
1359 dex_files_per_oat_file_.push_back(dex_files_);
1360 for (const DexFile* dex_file : dex_files_) {
1361 dex_file_oat_filename_map_.emplace(dex_file, oat_filenames_[0]);
1362 }
1363 }
1364 }
1365
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001366 // Create and invoke the compiler driver. This will compile all the dex files.
1367 void Compile() {
1368 TimingLogger::ScopedTiming t("dex2oat Compile", timings_);
1369 compiler_phases_timings_.reset(new CumulativeLogger("compilation times"));
Vladimir Markof4da6752014-08-01 19:04:18 +01001370
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001371 // Handle and ClassLoader creation needs to come after Runtime::Create
1372 jobject class_loader = nullptr;
Mathieu Chartierd37d3642015-11-19 16:05:58 -08001373 jobject class_path_class_loader = nullptr;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001374 Thread* self = Thread::Current();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001375
Vladimir Marko49b0f452015-12-10 13:49:19 +00001376 if (!boot_image_filename_.empty()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001377 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001378 OpenClassPathFiles(runtime_->GetClassPathString(), dex_files_, &class_path_files_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001379 ScopedObjectAccess soa(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07001380
1381 // Classpath: first the class-path given.
Vladimir Marko49b0f452015-12-10 13:49:19 +00001382 std::vector<const DexFile*> class_path_files = MakeNonOwningPointerVector(class_path_files_);
Andreas Gampe7848da42015-04-09 11:15:04 -07001383
1384 // Store the classpath we have right now.
1385 key_value_store_->Put(OatHeader::kClassPathKey,
1386 OatFile::EncodeDexFileDependencies(class_path_files));
1387
Mathieu Chartierd37d3642015-11-19 16:05:58 -08001388 class_path_class_loader = class_linker->CreatePathClassLoader(self,
1389 class_path_files,
1390 nullptr);
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001391
Mathieu Chartierd37d3642015-11-19 16:05:58 -08001392 // Class path loader as parent so that we'll resolve there first.
1393 class_loader = class_linker->CreatePathClassLoader(self, dex_files_, class_path_class_loader);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001394 }
1395
Jeff Haodcdc85b2015-12-04 14:06:18 -08001396 // Find the dex file we should not inline from.
1397
1398 // For now, on the host always have core-oj removed.
1399 if (!kIsTargetBuild && no_inline_from_string_.empty()) {
1400 no_inline_from_string_ = "core-oj";
1401 }
1402
1403 if (!no_inline_from_string_.empty()) {
1404 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1405 std::vector<const DexFile*> class_path_files = MakeNonOwningPointerVector(class_path_files_);
1406 std::vector<const std::vector<const DexFile*>*> dex_file_vectors = {
1407 &class_linker->GetBootClassPath(),
1408 &class_path_files,
1409 &dex_files_
1410 };
1411 for (const std::vector<const DexFile*>* dex_file_vector : dex_file_vectors) {
1412 if (dex_file_vector == nullptr) {
1413 continue;
1414 }
1415
1416 bool found = false;
1417
1418 for (const DexFile* dex_file : *dex_file_vector) {
1419 // Try the complete location first.
1420 found = no_inline_from_string_ == dex_file->GetLocation();
1421 // The try just the name.
1422 if (!found) {
1423 size_t last_slash = dex_file->GetLocation().rfind('/');
1424 if (last_slash != std::string::npos) {
1425 found = StartsWith(dex_file->GetLocation().substr(last_slash + 1),
1426 no_inline_from_string_.c_str());
1427 }
1428 }
1429
1430 if (found) {
1431 VLOG(compiler) << "Disabling inlining from " << dex_file->GetLocation();
1432 compiler_options_->no_inline_from_ = dex_file;
1433 break;
1434 }
1435 }
1436
1437 if (found) {
1438 break;
1439 }
1440 }
1441 }
1442
1443 if (IsBootImage() && image_filenames_.size() > 1) {
1444 // If we're compiling the boot image, store the boot classpath into the Key-Value store. If
Andreas Gampe8994a042015-12-30 19:03:17 +00001445 // the image filename was adapted (e.g., for our tests), we need to change this here, too, but
1446 // need to strip all path components (they will be re-established when loading).
1447 // We need this for the multi-image case.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001448 std::ostringstream bootcp_oss;
1449 bool first_bootcp = true;
1450 for (size_t i = 0; i < dex_locations_.size(); ++i) {
1451 if (!first_bootcp) {
1452 bootcp_oss << ":";
1453 }
1454
1455 std::string dex_loc = dex_locations_[i];
1456 std::string image_filename = image_filenames_[i];
1457
Andreas Gampe8994a042015-12-30 19:03:17 +00001458 // Use the dex_loc path, but the image_filename name (without path elements).
Jeff Haodcdc85b2015-12-04 14:06:18 -08001459 size_t dex_last_slash = dex_loc.rfind('/');
Andreas Gampe8994a042015-12-30 19:03:17 +00001460
1461 // npos is max(size_t). That makes this a bit ugly.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001462 size_t image_last_slash = image_filename.rfind('/');
Andreas Gampe8994a042015-12-30 19:03:17 +00001463 size_t image_last_at = image_filename.rfind('@');
1464 size_t image_last_sep = (image_last_slash == std::string::npos)
1465 ? image_last_at
1466 : (image_last_at == std::string::npos)
1467 ? std::string::npos
1468 : std::max(image_last_slash, image_last_at);
1469 // Note: whenever image_last_sep == npos, +1 overflow means using the full string.
1470
Jeff Haodcdc85b2015-12-04 14:06:18 -08001471 if (dex_last_slash == std::string::npos) {
Andreas Gampe8994a042015-12-30 19:03:17 +00001472 dex_loc = image_filename.substr(image_last_sep + 1);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001473 } else {
1474 dex_loc = dex_loc.substr(0, dex_last_slash + 1) +
Andreas Gampe8994a042015-12-30 19:03:17 +00001475 image_filename.substr(image_last_sep + 1);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001476 }
1477
1478 // Image filenames already end with .art, no need to replace.
1479
1480 bootcp_oss << dex_loc;
1481 first_bootcp = false;
1482 }
1483 key_value_store_->Put(OatHeader::kBootClassPath, bootcp_oss.str());
1484 }
1485
Vladimir Marko307dac92015-10-20 11:20:09 +01001486 driver_.reset(new CompilerDriver(compiler_options_.get(),
1487 verification_results_.get(),
1488 &method_inliner_map_,
1489 compiler_kind_,
1490 instruction_set_,
1491 instruction_set_features_.get(),
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001492 IsBootImage(),
Vladimir Marko307dac92015-10-20 11:20:09 +01001493 image_classes_.release(),
1494 compiled_classes_.release(),
1495 nullptr,
1496 thread_count_,
1497 dump_stats_,
1498 dump_passes_,
1499 dump_cfg_file_name_,
1500 dump_cfg_append_,
1501 compiler_phases_timings_.get(),
1502 swap_fd_,
Calin Juravle998c2162015-12-21 15:39:33 +02001503 &dex_file_oat_filename_map_,
1504 profile_compilation_info_.get()));
Vladimir Markod1eaf0d2015-10-29 12:18:29 +00001505 driver_->SetDexFilesForOatFile(dex_files_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001506 driver_->CompileAll(class_loader, dex_files_, timings_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001507 }
1508
Jeff Haodcdc85b2015-12-04 14:06:18 -08001509 // TODO: Update comments about how this works for multi image. b/26317072
Brian Carlstrom7940e442013-07-12 13:46:57 -07001510 // Notes on the interleaving of creating the image and oat file to
1511 // ensure the references between the two are correct.
1512 //
1513 // Currently we have a memory layout that looks something like this:
1514 //
1515 // +--------------+
1516 // | image |
1517 // +--------------+
1518 // | boot oat |
1519 // +--------------+
1520 // | alloc spaces |
1521 // +--------------+
1522 //
Brian Carlstrom45602482013-07-21 22:07:55 -07001523 // There are several constraints on the loading of the image and boot.oat.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001524 //
1525 // 1. The image is expected to be loaded at an absolute address and
1526 // contains Objects with absolute pointers within the image.
1527 //
1528 // 2. There are absolute pointers from Methods in the image to their
1529 // code in the oat.
1530 //
1531 // 3. There are absolute pointers from the code in the oat to Methods
1532 // in the image.
1533 //
1534 // 4. There are absolute pointers from code in the oat to other code
1535 // in the oat.
1536 //
1537 // To get this all correct, we go through several steps.
1538 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001539 // 1. We prepare offsets for all data in the oat file and calculate
1540 // the oat data size and code size. During this stage, we also set
1541 // oat code offsets in methods for use by the image writer.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001542 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001543 // 2. We prepare offsets for the objects in the image and calculate
1544 // the image size.
1545 //
1546 // 3. We create the oat file. Originally this was just our own proprietary
1547 // file but now it is contained within an ELF dynamic object (aka an .so
1548 // file). Since we know the image size and oat data size and code size we
1549 // can prepare the ELF headers and we then know the ELF memory segment
1550 // layout and we can now resolve all references. The compiler provides
1551 // LinkerPatch information in each CompiledMethod and we resolve these,
1552 // using the layout information and image object locations provided by
1553 // image writer, as we're writing the method code.
1554 //
1555 // 4. We create the image file. It needs to know where the oat file
Brian Carlstrom7940e442013-07-12 13:46:57 -07001556 // will be loaded after itself. Originally when oat file was simply
1557 // memory mapped so we could predict where its contents were based
1558 // on the file size. Now that it is an ELF file, we need to inspect
1559 // the ELF file to understand the in memory segment layout including
Vladimir Markof4da6752014-08-01 19:04:18 +01001560 // where the oat header is located within.
1561 // TODO: We could just remember this information from step 3.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001562 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001563 // 5. We fixup the ELF program headers so that dlopen will try to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001564 // load the .so at the desired location at runtime by offsetting the
1565 // Elf32_Phdr.p_vaddr values by the desired base address.
Vladimir Markof4da6752014-08-01 19:04:18 +01001566 // TODO: Do this in step 3. We already know the layout there.
1567 //
1568 // Steps 1.-3. are done by the CreateOatFile() above, steps 4.-5.
1569 // are done by the CreateImageFile() below.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001570
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001571 // Write out the generated code part. Calls the OatWriter and ElfBuilder. Also prepares the
1572 // ImageWriter, if necessary.
Andreas Gampe10e477d2014-11-19 12:57:42 -08001573 // Note: Flushing (and closing) the file is the caller's responsibility, except for the failure
1574 // case (when the file will be explicitly erased).
Jeff Haodcdc85b2015-12-04 14:06:18 -08001575 bool CreateOatFiles() {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001576 CHECK(key_value_store_.get() != nullptr);
1577
1578 TimingLogger::ScopedTiming t("dex2oat Oat", timings_);
1579
Jeff Haodcdc85b2015-12-04 14:06:18 -08001580 std::vector<std::unique_ptr<OatWriter>> oat_writers;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001581 {
1582 TimingLogger::ScopedTiming t2("dex2oat OatWriter", timings_);
1583 std::string image_file_location;
1584 uint32_t image_file_location_oat_checksum = 0;
1585 uintptr_t image_file_location_oat_data_begin = 0;
1586 int32_t image_patch_delta = 0;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001587
1588 if (app_image_ && image_base_ == 0) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001589 std::vector<gc::space::ImageSpace*> image_spaces =
1590 Runtime::Current()->GetHeap()->GetBootImageSpaces();
1591 for (gc::space::ImageSpace* image_space : image_spaces) {
1592 // TODO: IS THIS IN ORDER? JUST TAKE THE LAST ONE?
1593 image_base_ = std::max(image_base_, RoundUp(
1594 reinterpret_cast<uintptr_t>(image_space->GetImageHeader().GetOatFileEnd()),
1595 kPageSize));
1596 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001597 VLOG(compiler) << "App image base=" << reinterpret_cast<void*>(image_base_);
1598 }
1599
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001600 if (IsImage()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001601 PrepareImageWriter(image_base_);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001602 }
1603
1604 if (!IsBootImage()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001605 TimingLogger::ScopedTiming t3("Loading image checksum", timings_);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001606 std::vector<gc::space::ImageSpace*> image_spaces =
1607 Runtime::Current()->GetHeap()->GetBootImageSpaces();
1608 image_file_location_oat_checksum = image_spaces[0]->GetImageHeader().GetOatChecksum();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001609 image_file_location_oat_data_begin =
Jeff Haodcdc85b2015-12-04 14:06:18 -08001610 reinterpret_cast<uintptr_t>(image_spaces[0]->GetImageHeader().GetOatDataBegin());
1611 image_patch_delta = image_spaces[0]->GetImageHeader().GetPatchDelta();
1612 std::vector<std::string> image_filenames;
1613 for (const gc::space::ImageSpace* image_space : image_spaces) {
1614 image_filenames.push_back(image_space->GetImageFilename());
1615 }
1616 image_file_location = Join(image_filenames, ':');
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001617 }
1618
1619 if (!image_file_location.empty()) {
1620 key_value_store_->Put(OatHeader::kImageLocationKey, image_file_location);
1621 }
1622
Jeff Haodcdc85b2015-12-04 14:06:18 -08001623 for (size_t i = 0; i < oat_files_.size(); ++i) {
1624 std::vector<const DexFile*>& dex_files = dex_files_per_oat_file_[i];
1625 std::unique_ptr<OatWriter> oat_writer(new OatWriter(dex_files,
1626 image_file_location_oat_checksum,
1627 image_file_location_oat_data_begin,
1628 image_patch_delta,
1629 driver_.get(),
1630 image_writer_.get(),
1631 IsBootImage(),
1632 timings_,
1633 key_value_store_.get()));
1634 oat_writers.push_back(std::move(oat_writer));
1635 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001636 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001637
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001638 if (IsImage()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001639 // The OatWriter constructor has already updated offsets in methods and we need to
1640 // prepare method offsets in the image address space for direct method patching.
1641 TimingLogger::ScopedTiming t2("dex2oat Prepare image address space", timings_);
1642 if (!image_writer_->PrepareImageAddressSpace()) {
1643 LOG(ERROR) << "Failed to prepare image address space.";
1644 return false;
1645 }
1646 }
1647
1648 {
1649 TimingLogger::ScopedTiming t2("dex2oat Write ELF", timings_);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001650 for (size_t i = 0; i < oat_files_.size(); ++i) {
1651 std::unique_ptr<File>& oat_file = oat_files_[i];
1652 std::unique_ptr<OatWriter>& oat_writer = oat_writers[i];
1653 std::unique_ptr<ElfWriter> elf_writer =
1654 CreateElfWriterQuick(instruction_set_, compiler_options_.get(), oat_file.get());
Vladimir Marko10c13562015-11-25 14:33:36 +00001655
Jeff Haodcdc85b2015-12-04 14:06:18 -08001656 elf_writer->Start();
Vladimir Marko10c13562015-11-25 14:33:36 +00001657
Jeff Haodcdc85b2015-12-04 14:06:18 -08001658 OutputStream* rodata = elf_writer->StartRoData();
1659 if (!oat_writer->WriteRodata(rodata)) {
1660 LOG(ERROR) << "Failed to write .rodata section to the ELF file " << oat_file->GetPath();
1661 return false;
1662 }
1663 elf_writer->EndRoData(rodata);
Vladimir Marko10c13562015-11-25 14:33:36 +00001664
Jeff Haodcdc85b2015-12-04 14:06:18 -08001665 OutputStream* text = elf_writer->StartText();
1666 if (!oat_writer->WriteCode(text)) {
1667 LOG(ERROR) << "Failed to write .text section to the ELF file " << oat_file->GetPath();
1668 return false;
1669 }
1670 elf_writer->EndText(text);
Vladimir Marko10c13562015-11-25 14:33:36 +00001671
Jeff Haodcdc85b2015-12-04 14:06:18 -08001672 elf_writer->SetBssSize(oat_writer->GetBssSize());
1673 elf_writer->WriteDynamicSection();
1674 elf_writer->WriteDebugInfo(oat_writer->GetMethodDebugInfo());
1675 elf_writer->WritePatchLocations(oat_writer->GetAbsolutePatchLocations());
Vladimir Marko10c13562015-11-25 14:33:36 +00001676
Jeff Haodcdc85b2015-12-04 14:06:18 -08001677 if (!elf_writer->End()) {
1678 LOG(ERROR) << "Failed to write ELF file " << oat_file->GetPath();
1679 return false;
1680 }
1681
1682 // Flush the oat file.
1683 if (oat_files_[i] != nullptr) {
1684 if (oat_files_[i]->Flush() != 0) {
1685 PLOG(ERROR) << "Failed to flush oat file: " << oat_filenames_[i];
1686 oat_files_[i]->Erase();
1687 return false;
1688 }
1689 }
1690
1691 if (IsImage()) {
1692 // Update oat estimates.
1693 UpdateImageWriter(i);
1694 }
1695
1696 VLOG(compiler) << "Oat file written successfully: " << oat_filenames_[i];
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001697 }
1698 }
1699
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001700 return true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001701 }
1702
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001703 // If we are compiling an image, invoke the image creation routine. Else just skip.
1704 bool HandleImage() {
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001705 if (IsImage()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001706 TimingLogger::ScopedTiming t("dex2oat ImageWriter", timings_);
1707 if (!CreateImageFile()) {
1708 return false;
1709 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001710 VLOG(compiler) << "Images written successfully";
Brian Carlstrom45602482013-07-21 22:07:55 -07001711 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001712 return true;
1713 }
1714
Jeff Haodcdc85b2015-12-04 14:06:18 -08001715 // Create a copy from stripped to unstripped.
1716 bool CopyStrippedToUnstripped() {
1717 for (size_t i = 0; i < oat_unstripped_.size(); ++i) {
1718 // If we don't want to strip in place, copy from stripped location to unstripped location.
1719 // We need to strip after image creation because FixupElf needs to use .strtab.
1720 if (strcmp(oat_unstripped_[i], oat_filenames_[i]) != 0) {
1721 // If the oat file is still open, flush it.
1722 if (oat_files_[i].get() != nullptr && oat_files_[i]->IsOpened()) {
1723 if (!FlushCloseOatFile(i)) {
1724 return false;
1725 }
1726 }
1727
1728 TimingLogger::ScopedTiming t("dex2oat OatFile copy", timings_);
1729 std::unique_ptr<File> in(OS::OpenFileForReading(oat_filenames_[i]));
1730 std::unique_ptr<File> out(OS::CreateEmptyFile(oat_unstripped_[i]));
1731 size_t buffer_size = 8192;
1732 std::unique_ptr<uint8_t[]> buffer(new uint8_t[buffer_size]);
1733 while (true) {
1734 int bytes_read = TEMP_FAILURE_RETRY(read(in->Fd(), buffer.get(), buffer_size));
1735 if (bytes_read <= 0) {
1736 break;
1737 }
1738 bool write_ok = out->WriteFully(buffer.get(), bytes_read);
1739 CHECK(write_ok);
1740 }
1741 if (out->FlushCloseOrErase() != 0) {
1742 PLOG(ERROR) << "Failed to flush and close copied oat file: " << oat_unstripped_[i];
1743 return false;
1744 }
1745 VLOG(compiler) << "Oat file copied successfully (unstripped): " << oat_unstripped_[i];
1746 }
1747 }
1748 return true;
1749 }
1750
1751 bool FlushOatFiles() {
1752 TimingLogger::ScopedTiming t2("dex2oat Flush ELF", timings_);
1753 for (size_t i = 0; i < oat_files_.size(); ++i) {
1754 if (oat_files_[i].get() != nullptr) {
1755 if (oat_files_[i]->Flush() != 0) {
1756 PLOG(ERROR) << "Failed to flush oat file: " << oat_filenames_[i];
1757 oat_files_[i]->Erase();
Andreas Gampe10e477d2014-11-19 12:57:42 -08001758 return false;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001759 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001760 }
Nicolas Geoffrayea3fa0b2014-02-10 11:59:41 +00001761 }
Andreas Gampe10e477d2014-11-19 12:57:42 -08001762 return true;
1763 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001764
Jeff Haodcdc85b2015-12-04 14:06:18 -08001765 bool FlushCloseOatFile(size_t i) {
1766 if (oat_files_[i].get() != nullptr) {
1767 std::unique_ptr<File> tmp(oat_files_[i].release());
Andreas Gampe10e477d2014-11-19 12:57:42 -08001768 if (tmp->FlushCloseOrErase() != 0) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001769 PLOG(ERROR) << "Failed to flush and close oat file: " << oat_filenames_[i];
Andreas Gampe10e477d2014-11-19 12:57:42 -08001770 return false;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001771 }
1772 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001773 return true;
1774 }
1775
Jeff Haodcdc85b2015-12-04 14:06:18 -08001776 bool FlushCloseOatFiles() {
1777 bool result = true;
1778 for (size_t i = 0; i < oat_files_.size(); ++i) {
1779 result &= FlushCloseOatFile(i);
1780 }
1781 return result;
1782 }
1783
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001784 void DumpTiming() {
1785 if (dump_timing_ || (dump_slow_timing_ && timings_->GetTotalNs() > MsToNs(1000))) {
1786 LOG(INFO) << Dumpable<TimingLogger>(*timings_);
1787 }
1788 if (dump_passes_) {
1789 LOG(INFO) << Dumpable<CumulativeLogger>(*driver_->GetTimingsLogger());
1790 }
1791 }
1792
1793 CompilerOptions* GetCompilerOptions() const {
1794 return compiler_options_.get();
1795 }
1796
Andreas Gampe10e477d2014-11-19 12:57:42 -08001797 bool IsImage() const {
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001798 return IsAppImage() || IsBootImage();
1799 }
1800
1801 bool IsAppImage() const {
1802 return app_image_;
1803 }
1804
1805 bool IsBootImage() const {
1806 return boot_image_;
Andreas Gampe10e477d2014-11-19 12:57:42 -08001807 }
1808
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001809 bool IsHost() const {
1810 return is_host_;
1811 }
1812
Calin Juravle998c2162015-12-21 15:39:33 +02001813 bool UseProfileGuidedCompilation() const {
1814 return !profile_files_.empty();
1815 }
1816
1817 bool ProcessProfiles() {
1818 DCHECK(UseProfileGuidedCompilation());
1819 ProfileCompilationInfo* info = nullptr;
1820 if (ProfileAssistant::ProcessProfiles(profile_files_, reference_profile_files_, &info)) {
1821 profile_compilation_info_.reset(info);
1822 return true;
1823 }
1824 return false;
1825 }
1826
1827 bool ShouldCompileBasedOnProfiles() const {
1828 DCHECK(UseProfileGuidedCompilation());
1829 // If we are given profiles, compile only if we have new information.
1830 return profile_compilation_info_ != nullptr;
1831 }
1832
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001833 private:
Vladimir Marko49b0f452015-12-10 13:49:19 +00001834 template <typename T>
1835 static std::vector<T*> MakeNonOwningPointerVector(const std::vector<std::unique_ptr<T>>& src) {
1836 std::vector<T*> result;
1837 result.reserve(src.size());
1838 for (const std::unique_ptr<T>& t : src) {
1839 result.push_back(t.get());
1840 }
1841 return result;
1842 }
1843
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001844 static size_t OpenDexFiles(const std::vector<const char*>& dex_filenames,
1845 const std::vector<const char*>& dex_locations,
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001846 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001847 DCHECK(dex_files != nullptr) << "OpenDexFiles out-param is nullptr";
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001848 size_t failure_count = 0;
1849 for (size_t i = 0; i < dex_filenames.size(); i++) {
1850 const char* dex_filename = dex_filenames[i];
1851 const char* dex_location = dex_locations[i];
1852 ATRACE_BEGIN(StringPrintf("Opening dex file '%s'", dex_filenames[i]).c_str());
1853 std::string error_msg;
1854 if (!OS::FileExists(dex_filename)) {
1855 LOG(WARNING) << "Skipping non-existent dex file '" << dex_filename << "'";
1856 continue;
1857 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001858 if (!DexFile::Open(dex_filename, dex_location, &error_msg, dex_files)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001859 LOG(WARNING) << "Failed to open .dex from file '" << dex_filename << "': " << error_msg;
1860 ++failure_count;
1861 }
1862 ATRACE_END();
1863 }
1864 return failure_count;
1865 }
1866
Andreas Gampee3712d02015-04-09 14:46:31 -07001867 // Returns true if dex_files has a dex with the named location. We compare canonical locations,
1868 // so that relative and absolute paths will match. Not caching for the dex_files isn't very
1869 // efficient, but under normal circumstances the list is neither large nor is this part too
1870 // sensitive.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001871 static bool DexFilesContains(const std::vector<const DexFile*>& dex_files,
1872 const std::string& location) {
Andreas Gampee3712d02015-04-09 14:46:31 -07001873 std::string canonical_location(DexFile::GetDexCanonicalLocation(location.c_str()));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001874 for (size_t i = 0; i < dex_files.size(); ++i) {
Andreas Gampee3712d02015-04-09 14:46:31 -07001875 if (DexFile::GetDexCanonicalLocation(dex_files[i]->GetLocation().c_str()) ==
1876 canonical_location) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001877 return true;
1878 }
1879 }
1880 return false;
1881 }
1882
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001883 // Appends to opened_dex_files any elements of class_path that dex_files
1884 // doesn't already contain. This will open those dex files as necessary.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001885 static void OpenClassPathFiles(const std::string& class_path,
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001886 std::vector<const DexFile*> dex_files,
1887 std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001888 DCHECK(opened_dex_files != nullptr) << "OpenClassPathFiles out-param is nullptr";
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001889 std::vector<std::string> parsed;
1890 Split(class_path, ':', &parsed);
1891 // Take Locks::mutator_lock_ so that lock ordering on the ClassLinker::dex_lock_ is maintained.
1892 ScopedObjectAccess soa(Thread::Current());
1893 for (size_t i = 0; i < parsed.size(); ++i) {
1894 if (DexFilesContains(dex_files, parsed[i])) {
1895 continue;
1896 }
1897 std::string error_msg;
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001898 if (!DexFile::Open(parsed[i].c_str(), parsed[i].c_str(), &error_msg, opened_dex_files)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001899 LOG(WARNING) << "Failed to open dex file '" << parsed[i] << "': " << error_msg;
1900 }
1901 }
1902 }
1903
Vladimir Marko49b0f452015-12-10 13:49:19 +00001904 bool PrepareImageClasses() {
1905 // If --image-classes was specified, calculate the full list of classes to include in the image.
1906 if (image_classes_filename_ != nullptr) {
1907 image_classes_ =
1908 ReadClasses(image_classes_zip_filename_, image_classes_filename_, "image");
1909 if (image_classes_ == nullptr) {
1910 return false;
1911 }
1912 } else if (IsBootImage()) {
1913 image_classes_.reset(new std::unordered_set<std::string>);
1914 }
1915 return true;
1916 }
1917
1918 bool PrepareCompiledClasses() {
1919 // If --compiled-classes was specified, calculate the full list of classes to compile in the
1920 // image.
1921 if (compiled_classes_filename_ != nullptr) {
1922 compiled_classes_ =
1923 ReadClasses(compiled_classes_zip_filename_, compiled_classes_filename_, "compiled");
1924 if (compiled_classes_ == nullptr) {
1925 return false;
1926 }
1927 } else {
1928 compiled_classes_.reset(nullptr); // By default compile everything.
1929 }
1930 return true;
1931 }
1932
1933 static std::unique_ptr<std::unordered_set<std::string>> ReadClasses(const char* zip_filename,
1934 const char* classes_filename,
1935 const char* tag) {
1936 std::unique_ptr<std::unordered_set<std::string>> classes;
1937 std::string error_msg;
1938 if (zip_filename != nullptr) {
1939 classes.reset(ReadImageClassesFromZip(zip_filename, classes_filename, &error_msg));
1940 } else {
1941 classes.reset(ReadImageClassesFromFile(classes_filename));
1942 }
1943 if (classes == nullptr) {
1944 LOG(ERROR) << "Failed to create list of " << tag << " classes from '"
1945 << classes_filename << "': " << error_msg;
1946 }
1947 return classes;
1948 }
1949
1950 bool PrepareCompiledMethods() {
1951 // If --compiled-methods was specified, read the methods to compile from the given file(s).
1952 if (compiled_methods_filename_ != nullptr) {
1953 std::string error_msg;
1954 if (compiled_methods_zip_filename_ != nullptr) {
1955 compiled_methods_.reset(ReadCommentedInputFromZip(compiled_methods_zip_filename_,
1956 compiled_methods_filename_,
1957 nullptr, // No post-processing.
1958 &error_msg));
1959 } else {
1960 compiled_methods_.reset(ReadCommentedInputFromFile(compiled_methods_filename_,
1961 nullptr)); // No post-processing.
1962 }
1963 if (compiled_methods_.get() == nullptr) {
1964 LOG(ERROR) << "Failed to create list of compiled methods from '"
1965 << compiled_methods_filename_ << "': " << error_msg;
1966 return false;
1967 }
1968 } else {
1969 compiled_methods_.reset(nullptr); // By default compile everything.
1970 }
1971 return true;
1972 }
1973
1974 void SaveDexInput() {
1975 for (size_t i = 0; i < dex_files_.size(); ++i) {
1976 const DexFile* dex_file = dex_files_[i];
1977 std::string tmp_file_name(StringPrintf("/data/local/tmp/dex2oat.%d.%zd.dex",
1978 getpid(), i));
1979 std::unique_ptr<File> tmp_file(OS::CreateEmptyFile(tmp_file_name.c_str()));
1980 if (tmp_file.get() == nullptr) {
1981 PLOG(ERROR) << "Failed to open file " << tmp_file_name
1982 << ". Try: adb shell chmod 777 /data/local/tmp";
1983 continue;
1984 }
1985 // This is just dumping files for debugging. Ignore errors, and leave remnants.
1986 UNUSED(tmp_file->WriteFully(dex_file->Begin(), dex_file->Size()));
1987 UNUSED(tmp_file->Flush());
1988 UNUSED(tmp_file->Close());
1989 LOG(INFO) << "Wrote input to " << tmp_file_name;
1990 }
1991 }
1992
1993 bool PrepareRuntimeOptions(RuntimeArgumentMap* runtime_options) {
1994 RuntimeOptions raw_options;
1995 if (boot_image_filename_.empty()) {
1996 std::string boot_class_path = "-Xbootclasspath:";
1997 boot_class_path += Join(dex_filenames_, ':');
1998 raw_options.push_back(std::make_pair(boot_class_path, nullptr));
1999 std::string boot_class_path_locations = "-Xbootclasspath-locations:";
2000 boot_class_path_locations += Join(dex_locations_, ':');
2001 raw_options.push_back(std::make_pair(boot_class_path_locations, nullptr));
2002 } else {
2003 std::string boot_image_option = "-Ximage:";
2004 boot_image_option += boot_image_filename_;
2005 raw_options.push_back(std::make_pair(boot_image_option, nullptr));
2006 }
2007 for (size_t i = 0; i < runtime_args_.size(); i++) {
2008 raw_options.push_back(std::make_pair(runtime_args_[i], nullptr));
2009 }
2010
2011 raw_options.push_back(std::make_pair("compilercallbacks", callbacks_.get()));
2012 raw_options.push_back(
2013 std::make_pair("imageinstructionset", GetInstructionSetString(instruction_set_)));
2014
2015 // Only allow no boot image for the runtime if we're compiling one. When we compile an app,
2016 // we don't want fallback mode, it will abort as we do not push a boot classpath (it might
2017 // have been stripped in preopting, anyways).
2018 if (!IsBootImage()) {
2019 raw_options.push_back(std::make_pair("-Xno-dex-file-fallback", nullptr));
2020 }
2021 // Disable libsigchain. We don't don't need it during compilation and it prevents us
2022 // from getting a statically linked version of dex2oat (because of dlsym and RTLD_NEXT).
2023 raw_options.push_back(std::make_pair("-Xno-sig-chain", nullptr));
2024
2025 if (!Runtime::ParseOptions(raw_options, false, runtime_options)) {
2026 LOG(ERROR) << "Failed to parse runtime options";
2027 return false;
2028 }
2029 return true;
2030 }
2031
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002032 // Create a runtime necessary for compilation.
Vladimir Marko49b0f452015-12-10 13:49:19 +00002033 bool CreateRuntime(RuntimeArgumentMap&& runtime_options)
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002034 SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_) {
Vladimir Marko49b0f452015-12-10 13:49:19 +00002035 if (!Runtime::Create(std::move(runtime_options))) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002036 LOG(ERROR) << "Failed to create runtime";
2037 return false;
2038 }
Vladimir Marko307dac92015-10-20 11:20:09 +01002039 runtime_.reset(Runtime::Current());
2040 runtime_->SetInstructionSet(instruction_set_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002041 for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
2042 Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i);
Vladimir Marko307dac92015-10-20 11:20:09 +01002043 if (!runtime_->HasCalleeSaveMethod(type)) {
2044 runtime_->SetCalleeSaveMethod(runtime_->CreateCalleeSaveMethod(), type);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002045 }
2046 }
Vladimir Marko307dac92015-10-20 11:20:09 +01002047 runtime_->GetClassLinker()->FixupDexCaches(runtime_->GetResolutionMethod());
Andreas Gampe2969bcd2015-03-09 12:57:41 -07002048
2049 // Initialize maps for unstarted runtime. This needs to be here, as running clinits needs this
2050 // set up.
Andreas Gampe799681b2015-05-15 19:24:12 -07002051 interpreter::UnstartedRuntime::Initialize();
Andreas Gampe2969bcd2015-03-09 12:57:41 -07002052
Vladimir Marko307dac92015-10-20 11:20:09 +01002053 runtime_->GetClassLinker()->RunRootClinits();
Andreas Gampe2969bcd2015-03-09 12:57:41 -07002054
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002055 return true;
2056 }
2057
2058 void PrepareImageWriter(uintptr_t image_base) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002059 DCHECK(IsImage());
2060 image_writer_.reset(new ImageWriter(*driver_,
2061 image_base,
2062 compiler_options_->GetCompilePic(),
Mathieu Chartierceb07b32015-12-10 09:33:21 -08002063 IsAppImage(),
Jeff Haodcdc85b2015-12-04 14:06:18 -08002064 image_storage_mode_,
2065 oat_filenames_,
2066 dex_file_oat_filename_map_));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002067 }
2068
Jeff Haodcdc85b2015-12-04 14:06:18 -08002069 // 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 -08002070 bool CreateImageFile()
Mathieu Chartier90443472015-07-16 20:32:27 -07002071 REQUIRES(!Locks::mutator_lock_) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002072 CHECK(image_writer_ != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002073 if (!IsBootImage()) {
2074 image_filenames_.push_back(app_image_file_name_.c_str());
2075 }
2076 if (!image_writer_->Write(app_image_fd_, image_filenames_, oat_filenames_)) {
2077 LOG(ERROR) << "Failure during image file creation";
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002078 return false;
2079 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002080
Jeff Haodcdc85b2015-12-04 14:06:18 -08002081 // We need the OatDataBegin entries.
2082 std::map<const char*, uintptr_t> oat_data_begins;
2083 for (const char* oat_filename : oat_filenames_) {
2084 oat_data_begins.emplace(oat_filename, image_writer_->GetOatDataBegin(oat_filename));
2085 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002086 // Destroy ImageWriter before doing FixupElf.
2087 image_writer_.reset();
2088
Jeff Haodcdc85b2015-12-04 14:06:18 -08002089 for (const char* oat_filename : oat_filenames_) {
2090 // Do not fix up the ELF file if we are --compile-pic or compiling the app image
2091 if (!compiler_options_->GetCompilePic() && IsBootImage()) {
2092 std::unique_ptr<File> oat_file(OS::OpenFileReadWrite(oat_filename));
2093 if (oat_file.get() == nullptr) {
2094 PLOG(ERROR) << "Failed to open ELF file: " << oat_filename;
2095 return false;
2096 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08002097
Jeff Haodcdc85b2015-12-04 14:06:18 -08002098 uintptr_t oat_data_begin = oat_data_begins.find(oat_filename)->second;
Andreas Gampe4303ba92014-11-06 01:00:46 -08002099
Jeff Haodcdc85b2015-12-04 14:06:18 -08002100 if (!ElfWriter::Fixup(oat_file.get(), oat_data_begin)) {
2101 oat_file->Erase();
2102 LOG(ERROR) << "Failed to fixup ELF file " << oat_file->GetPath();
2103 return false;
2104 }
2105
2106 if (oat_file->FlushCloseOrErase()) {
2107 PLOG(ERROR) << "Failed to flush and close fixed ELF file " << oat_file->GetPath();
2108 return false;
2109 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08002110 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002111 }
2112
2113 return true;
2114 }
2115
2116 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
Andreas Gampeb1fcead2015-04-20 18:53:51 -07002117 static std::unordered_set<std::string>* ReadImageClassesFromFile(
2118 const char* image_classes_filename) {
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002119 std::function<std::string(const char*)> process = DotToDescriptor;
2120 return ReadCommentedInputFromFile(image_classes_filename, &process);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002121 }
2122
2123 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
Andreas Gampeb1fcead2015-04-20 18:53:51 -07002124 static std::unordered_set<std::string>* ReadImageClassesFromZip(
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002125 const char* zip_filename,
2126 const char* image_classes_filename,
2127 std::string* error_msg) {
2128 std::function<std::string(const char*)> process = DotToDescriptor;
2129 return ReadCommentedInputFromZip(zip_filename, image_classes_filename, &process, error_msg);
2130 }
2131
2132 // Read lines from the given file, dropping comments and empty lines. Post-process each line with
2133 // the given function.
2134 static std::unordered_set<std::string>* ReadCommentedInputFromFile(
2135 const char* input_filename, std::function<std::string(const char*)>* process) {
2136 std::unique_ptr<std::ifstream> input_file(new std::ifstream(input_filename, std::ifstream::in));
2137 if (input_file.get() == nullptr) {
2138 LOG(ERROR) << "Failed to open input file " << input_filename;
2139 return nullptr;
2140 }
2141 std::unique_ptr<std::unordered_set<std::string>> result(
2142 ReadCommentedInputStream(*input_file, process));
2143 input_file->close();
2144 return result.release();
2145 }
2146
2147 // Read lines from the given file from the given zip file, dropping comments and empty lines.
2148 // Post-process each line with the given function.
2149 static std::unordered_set<std::string>* ReadCommentedInputFromZip(
Andreas Gampeb1fcead2015-04-20 18:53:51 -07002150 const char* zip_filename,
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002151 const char* input_filename,
2152 std::function<std::string(const char*)>* process,
Andreas Gampeb1fcead2015-04-20 18:53:51 -07002153 std::string* error_msg) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002154 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::Open(zip_filename, error_msg));
2155 if (zip_archive.get() == nullptr) {
2156 return nullptr;
2157 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002158 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(input_filename, error_msg));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002159 if (zip_entry.get() == nullptr) {
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002160 *error_msg = StringPrintf("Failed to find '%s' within '%s': %s", input_filename,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002161 zip_filename, error_msg->c_str());
2162 return nullptr;
2163 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002164 std::unique_ptr<MemMap> input_file(zip_entry->ExtractToMemMap(zip_filename,
2165 input_filename,
2166 error_msg));
2167 if (input_file.get() == nullptr) {
2168 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", input_filename,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002169 zip_filename, error_msg->c_str());
2170 return nullptr;
2171 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002172 const std::string input_string(reinterpret_cast<char*>(input_file->Begin()),
2173 input_file->Size());
2174 std::istringstream input_stream(input_string);
2175 return ReadCommentedInputStream(input_stream, process);
2176 }
2177
2178 // Read lines from the given stream, dropping comments and empty lines. Post-process each line
2179 // with the given function.
2180 static std::unordered_set<std::string>* ReadCommentedInputStream(
2181 std::istream& in_stream,
2182 std::function<std::string(const char*)>* process) {
2183 std::unique_ptr<std::unordered_set<std::string>> image_classes(
2184 new std::unordered_set<std::string>);
2185 while (in_stream.good()) {
2186 std::string dot;
2187 std::getline(in_stream, dot);
2188 if (StartsWith(dot, "#") || dot.empty()) {
2189 continue;
2190 }
2191 if (process != nullptr) {
2192 std::string descriptor((*process)(dot.c_str()));
2193 image_classes->insert(descriptor);
2194 } else {
2195 image_classes->insert(dot);
2196 }
2197 }
2198 return image_classes.release();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002199 }
2200
Mathieu Chartier49285c52014-12-02 15:43:48 -08002201 void LogCompletionTime() {
Andreas Gampe1d00add2015-02-27 19:35:46 -08002202 // Note: when creation of a runtime fails, e.g., when trying to compile an app but when there
2203 // is no image, there won't be a Runtime::Current().
Brian Carlstroma11a34c2015-03-06 08:44:45 -08002204 // Note: driver creation can fail when loading an invalid dex file.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002205 LOG(INFO) << "dex2oat took " << PrettyDuration(NanoTime() - start_ns_)
Mathieu Chartierab972ef2014-12-03 17:38:22 -08002206 << " (threads: " << thread_count_ << ") "
Andreas Gampe3f30e122015-09-17 14:03:21 -07002207 << ((Runtime::Current() != nullptr && driver_ != nullptr) ?
Andreas Gampe1d00add2015-02-27 19:35:46 -08002208 driver_->GetMemoryUsageString(kIsDebugBuild || VLOG_IS_ON(compiler)) :
2209 "");
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002210 }
2211
Jeff Haodcdc85b2015-12-04 14:06:18 -08002212 std::string StripIsaFrom(const char* image_filename, InstructionSet isa) {
2213 std::string res(image_filename);
2214 size_t last_slash = res.rfind('/');
2215 if (last_slash == std::string::npos || last_slash == 0) {
2216 return res;
2217 }
2218 size_t penultimate_slash = res.rfind('/', last_slash - 1);
2219 if (penultimate_slash == std::string::npos) {
2220 return res;
2221 }
2222 // Check that the string in-between is the expected one.
2223 if (res.substr(penultimate_slash + 1, last_slash - penultimate_slash - 1) !=
2224 GetInstructionSetString(isa)) {
2225 LOG(WARNING) << "Unexpected string when trying to strip isa: " << res;
2226 return res;
2227 }
2228 return res.substr(0, penultimate_slash) + res.substr(last_slash);
2229 }
2230
2231 // Update the estimate for the oat file with the given index.
2232 void UpdateImageWriter(size_t index) {
2233 DCHECK(image_writer_ != nullptr);
2234 DCHECK_LT(index, oat_filenames_.size());
2235
2236 image_writer_->UpdateOatFile(oat_filenames_[index]);
2237 }
2238
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002239 std::unique_ptr<CompilerOptions> compiler_options_;
2240 Compiler::Kind compiler_kind_;
2241
2242 InstructionSet instruction_set_;
2243 std::unique_ptr<const InstructionSetFeatures> instruction_set_features_;
2244
2245 std::unique_ptr<SafeMap<std::string, std::string> > key_value_store_;
2246
Vladimir Marko307dac92015-10-20 11:20:09 +01002247 std::unique_ptr<VerificationResults> verification_results_;
Andreas Gampe3f30e122015-09-17 14:03:21 -07002248
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002249 DexFileToMethodInlinerMap method_inliner_map_;
2250 std::unique_ptr<QuickCompilerCallbacks> callbacks_;
2251
Richard Uhlerfbef44d2014-12-23 09:48:51 -08002252 // Ownership for the class path files.
2253 std::vector<std::unique_ptr<const DexFile>> class_path_files_;
2254
Vladimir Marko307dac92015-10-20 11:20:09 +01002255 std::unique_ptr<Runtime> runtime_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002256
2257 size_t thread_count_;
2258 uint64_t start_ns_;
2259 std::unique_ptr<WatchDog> watchdog_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002260 std::vector<std::unique_ptr<File>> oat_files_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002261 std::string oat_location_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002262 std::vector<const char*> oat_filenames_;
2263 std::vector<const char*> oat_unstripped_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002264 int oat_fd_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002265 std::vector<const char*> dex_filenames_;
2266 std::vector<const char*> dex_locations_;
2267 int zip_fd_;
2268 std::string zip_location_;
Vladimir Marko49b0f452015-12-10 13:49:19 +00002269 std::string boot_image_filename_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002270 std::vector<const char*> runtime_args_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002271 std::vector<const char*> image_filenames_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002272 uintptr_t image_base_;
2273 const char* image_classes_zip_filename_;
2274 const char* image_classes_filename_;
Mathieu Chartierceb07b32015-12-10 09:33:21 -08002275 ImageHeader::StorageMode image_storage_mode_;
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08002276 const char* compiled_classes_zip_filename_;
2277 const char* compiled_classes_filename_;
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002278 const char* compiled_methods_zip_filename_;
2279 const char* compiled_methods_filename_;
Andreas Gampeb1fcead2015-04-20 18:53:51 -07002280 std::unique_ptr<std::unordered_set<std::string>> image_classes_;
2281 std::unique_ptr<std::unordered_set<std::string>> compiled_classes_;
Andreas Gampe70bef0d2015-04-15 02:37:28 -07002282 std::unique_ptr<std::unordered_set<std::string>> compiled_methods_;
Mathieu Chartiera90c7722015-10-29 15:41:36 -07002283 bool app_image_;
2284 bool boot_image_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002285 bool is_host_;
2286 std::string android_root_;
2287 std::vector<const DexFile*> dex_files_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002288 std::string no_inline_from_string_;
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002289 std::vector<jobject> dex_caches_;
Richard Uhlerfbef44d2014-12-23 09:48:51 -08002290 std::vector<std::unique_ptr<const DexFile>> opened_dex_files_;
Andreas Gampe3f30e122015-09-17 14:03:21 -07002291
Vladimir Marko307dac92015-10-20 11:20:09 +01002292 std::unique_ptr<ImageWriter> image_writer_;
2293 std::unique_ptr<CompilerDriver> driver_;
Andreas Gampe3f30e122015-09-17 14:03:21 -07002294
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002295 std::vector<std::string> verbose_methods_;
2296 bool dump_stats_;
2297 bool dump_passes_;
2298 bool dump_timing_;
2299 bool dump_slow_timing_;
David Brazdil866c0312015-01-13 21:21:31 +00002300 std::string dump_cfg_file_name_;
Calin Juravle87000a92015-08-24 15:34:44 +01002301 bool dump_cfg_append_;
Andreas Gampee21dc3d2014-12-08 16:59:43 -08002302 std::string swap_file_name_;
2303 int swap_fd_;
Mathieu Chartiera90c7722015-10-29 15:41:36 -07002304 std::string app_image_file_name_;
2305 int app_image_fd_;
Calin Juravle998c2162015-12-21 15:39:33 +02002306 std::vector<std::string> profile_files_;
2307 std::vector<std::string> reference_profile_files_;
2308 std::unique_ptr<ProfileCompilationInfo> profile_compilation_info_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002309 TimingLogger* timings_;
2310 std::unique_ptr<CumulativeLogger> compiler_phases_timings_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002311 std::vector<std::vector<const DexFile*>> dex_files_per_oat_file_;
2312 std::unordered_map<const DexFile*, const char*> dex_file_oat_filename_map_;
2313
2314 // Backing storage.
2315 std::vector<std::string> char_backing_storage_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002316
2317 DISALLOW_IMPLICIT_CONSTRUCTORS(Dex2Oat);
2318};
2319
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002320static void b13564922() {
2321#if defined(__linux__) && defined(__arm__)
2322 int major, minor;
2323 struct utsname uts;
2324 if (uname(&uts) != -1 &&
2325 sscanf(uts.release, "%d.%d", &major, &minor) == 2 &&
2326 ((major < 3) || ((major == 3) && (minor < 4)))) {
2327 // Kernels before 3.4 don't handle the ASLR well and we can run out of address
2328 // space (http://b/13564922). Work around the issue by inhibiting further mmap() randomization.
2329 int old_personality = personality(0xffffffff);
2330 if ((old_personality & ADDR_NO_RANDOMIZE) == 0) {
2331 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
2332 if (new_personality == -1) {
2333 LOG(WARNING) << "personality(. | ADDR_NO_RANDOMIZE) failed.";
2334 }
2335 }
2336 }
2337#endif
2338}
2339
Andreas Gampe10e477d2014-11-19 12:57:42 -08002340static int CompileImage(Dex2Oat& dex2oat) {
2341 dex2oat.Compile();
2342
Jeff Haodcdc85b2015-12-04 14:06:18 -08002343 if (!dex2oat.CreateOatFiles()) {
2344 dex2oat.EraseOatFiles();
Andreas Gampe10e477d2014-11-19 12:57:42 -08002345 return EXIT_FAILURE;
2346 }
2347
Jeff Haodcdc85b2015-12-04 14:06:18 -08002348 // Close the image oat files. We always expect the output file by name, and it will be
2349 // re-opened from the unstripped name. Note: it's easier to *flush* and close...
2350 if (!dex2oat.FlushCloseOatFiles()) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08002351 return EXIT_FAILURE;
2352 }
2353
Jeff Haodcdc85b2015-12-04 14:06:18 -08002354 // Creates the boot.art and patches the oat files.
Andreas Gampe10e477d2014-11-19 12:57:42 -08002355 if (!dex2oat.HandleImage()) {
2356 return EXIT_FAILURE;
2357 }
2358
2359 // When given --host, finish early without stripping.
2360 if (dex2oat.IsHost()) {
2361 dex2oat.DumpTiming();
2362 return EXIT_SUCCESS;
2363 }
2364
Jeff Haodcdc85b2015-12-04 14:06:18 -08002365 // Copy stripped to unstripped location, if necessary.
2366 if (!dex2oat.CopyStrippedToUnstripped()) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08002367 return EXIT_FAILURE;
2368 }
2369
Jeff Haodcdc85b2015-12-04 14:06:18 -08002370 // FlushClose again, as stripping might have re-opened the oat files.
2371 if (!dex2oat.FlushCloseOatFiles()) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08002372 return EXIT_FAILURE;
2373 }
2374
2375 dex2oat.DumpTiming();
2376 return EXIT_SUCCESS;
2377}
2378
2379static int CompileApp(Dex2Oat& dex2oat) {
2380 dex2oat.Compile();
2381
Jeff Haodcdc85b2015-12-04 14:06:18 -08002382 if (!dex2oat.CreateOatFiles()) {
2383 dex2oat.EraseOatFiles();
Andreas Gampe10e477d2014-11-19 12:57:42 -08002384 return EXIT_FAILURE;
2385 }
2386
Jeff Haodcdc85b2015-12-04 14:06:18 -08002387 // Do not close the oat files here. We might have gotten the output file by file descriptor,
Andreas Gampe10e477d2014-11-19 12:57:42 -08002388 // which we would lose.
Andreas Gampe10e477d2014-11-19 12:57:42 -08002389
2390 // When given --host, finish early without stripping.
2391 if (dex2oat.IsHost()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002392 if (!dex2oat.FlushCloseOatFiles()) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08002393 return EXIT_FAILURE;
2394 }
2395
2396 dex2oat.DumpTiming();
2397 return EXIT_SUCCESS;
2398 }
2399
Jeff Haodcdc85b2015-12-04 14:06:18 -08002400 // Copy stripped to unstripped location, if necessary. This will implicitly flush & close the
2401 // stripped versions. If this is given, we expect to be able to open writable files by name.
2402 if (!dex2oat.CopyStrippedToUnstripped()) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08002403 return EXIT_FAILURE;
2404 }
2405
Jeff Haodcdc85b2015-12-04 14:06:18 -08002406 // Flush and close the files.
2407 if (!dex2oat.FlushCloseOatFiles()) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08002408 return EXIT_FAILURE;
2409 }
2410
2411 dex2oat.DumpTiming();
2412 return EXIT_SUCCESS;
2413}
2414
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002415static int dex2oat(int argc, char** argv) {
2416 b13564922();
2417
2418 TimingLogger timings("compiler", false, false);
2419
2420 Dex2Oat dex2oat(&timings);
2421
2422 // Parse arguments. Argument mistakes will lead to exit(EXIT_FAILURE) in UsageError.
2423 dex2oat.ParseArgs(argc, argv);
2424
Calin Juravle998c2162015-12-21 15:39:33 +02002425 // Process profile information and assess if we need to do a profile guided compilation.
2426 // This operation involves I/O.
2427 if (dex2oat.UseProfileGuidedCompilation()) {
2428 if (dex2oat.ProcessProfiles()) {
2429 if (!dex2oat.ShouldCompileBasedOnProfiles()) {
2430 LOG(INFO) << "Skipped compilation because of insignificant profile delta";
2431 return EXIT_SUCCESS;
2432 }
2433 } else {
2434 LOG(WARNING) << "Failed to process profile files";
2435 return EXIT_FAILURE;
2436 }
2437 }
2438
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002439 // Check early that the result of compilation can be written
2440 if (!dex2oat.OpenFile()) {
2441 return EXIT_FAILURE;
2442 }
2443
Andreas Gampe046c7062015-05-18 23:22:54 -07002444 // Print the complete line when any of the following is true:
2445 // 1) Debug build
2446 // 2) Compiling an image
2447 // 3) Compiling with --host
2448 // 4) Compiling on the host (not a target build)
2449 // Otherwise, print a stripped command line.
Mathieu Chartiera90c7722015-10-29 15:41:36 -07002450 if (kIsDebugBuild || dex2oat.IsBootImage() || dex2oat.IsHost() || !kIsTargetBuild) {
Andreas Gampe046c7062015-05-18 23:22:54 -07002451 LOG(INFO) << CommandLine();
2452 } else {
2453 LOG(INFO) << StrippedCommandLine();
2454 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002455
2456 if (!dex2oat.Setup()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002457 dex2oat.EraseOatFiles();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002458 return EXIT_FAILURE;
2459 }
2460
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002461 bool result;
Andreas Gampe10e477d2014-11-19 12:57:42 -08002462 if (dex2oat.IsImage()) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002463 result = CompileImage(dex2oat);
Andreas Gampe10e477d2014-11-19 12:57:42 -08002464 } else {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002465 result = CompileApp(dex2oat);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002466 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002467
2468 dex2oat.Shutdown();
2469 return result;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002470}
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002471} // namespace art
Brian Carlstrom7940e442013-07-12 13:46:57 -07002472
2473int main(int argc, char** argv) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002474 int result = art::dex2oat(argc, argv);
2475 // Everything was done, do an explicit exit here to avoid running Runtime destructors that take
2476 // time (bug 10645725) unless we're a debug build or running on valgrind. Note: The Dex2Oat class
2477 // should not destruct the runtime in this case.
Evgenii Stepanov1e133742015-05-20 12:30:59 -07002478 if (!art::kIsDebugBuild && (RUNNING_ON_MEMORY_TOOL == 0)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002479 exit(result);
2480 }
2481 return result;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002482}