blob: 77211ce05941e09e4f6cf591969673f8063266cb [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"
Brian Carlstrom7940e442013-07-12 13:46:57 -070066#include "leb128.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070067#include "mirror/class-inl.h"
68#include "mirror/class_loader.h"
69#include "mirror/object-inl.h"
70#include "mirror/object_array-inl.h"
71#include "oat_writer.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070072#include "os.h"
73#include "runtime.h"
74#include "ScopedLocalRef.h"
75#include "scoped_thread_state_change.h"
Alex Light53cb16b2014-06-12 11:26:29 -070076#include "utils.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070077#include "vector_output_stream.h"
78#include "well_known_classes.h"
79#include "zip_archive.h"
80
81namespace art {
82
Brian Carlstrom6449c622014-02-10 23:48:36 -080083static int original_argc;
84static char** original_argv;
85
86static std::string CommandLine() {
87 std::vector<std::string> command;
88 for (int i = 0; i < original_argc; ++i) {
89 command.push_back(original_argv[i]);
90 }
91 return Join(command, ' ');
92}
93
Andreas Gampe046c7062015-05-18 23:22:54 -070094// A stripped version. Remove some less essential parameters. If we see a "--zip-fd=" parameter, be
95// even more aggressive. There won't be much reasonable data here for us in that case anyways (the
96// locations are all staged).
97static std::string StrippedCommandLine() {
98 std::vector<std::string> command;
99
100 // Do a pre-pass to look for zip-fd.
101 bool saw_zip_fd = false;
102 for (int i = 0; i < original_argc; ++i) {
103 if (StartsWith(original_argv[i], "--zip-fd=")) {
104 saw_zip_fd = true;
105 break;
106 }
107 }
108
109 // Now filter out things.
110 for (int i = 0; i < original_argc; ++i) {
111 // All runtime-arg parameters are dropped.
112 if (strcmp(original_argv[i], "--runtime-arg") == 0) {
113 i++; // Drop the next part, too.
114 continue;
115 }
116
117 // Any instruction-setXXX is dropped.
118 if (StartsWith(original_argv[i], "--instruction-set")) {
119 continue;
120 }
121
122 // The boot image is dropped.
123 if (StartsWith(original_argv[i], "--boot-image=")) {
124 continue;
125 }
126
127 // This should leave any dex-file and oat-file options, describing what we compiled.
128
129 // However, we prefer to drop this when we saw --zip-fd.
130 if (saw_zip_fd) {
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700131 // Drop anything --zip-X, --dex-X, --oat-X, --swap-X, or --app-image-X
Andreas Gampe046c7062015-05-18 23:22:54 -0700132 if (StartsWith(original_argv[i], "--zip-") ||
133 StartsWith(original_argv[i], "--dex-") ||
134 StartsWith(original_argv[i], "--oat-") ||
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700135 StartsWith(original_argv[i], "--swap-") ||
136 StartsWith(original_argv[i], "--app-image-")) {
Andreas Gampe046c7062015-05-18 23:22:54 -0700137 continue;
138 }
139 }
140
141 command.push_back(original_argv[i]);
142 }
143
144 // Construct the final output.
145 if (command.size() <= 1U) {
146 // It seems only "/system/bin/dex2oat" is left, or not even that. Use a pretty line.
147 return "Starting dex2oat.";
148 }
149 return Join(command, ' ');
150}
151
Brian Carlstrom7940e442013-07-12 13:46:57 -0700152static void UsageErrorV(const char* fmt, va_list ap) {
153 std::string error;
154 StringAppendV(&error, fmt, ap);
155 LOG(ERROR) << error;
156}
157
158static void UsageError(const char* fmt, ...) {
159 va_list ap;
160 va_start(ap, fmt);
161 UsageErrorV(fmt, ap);
162 va_end(ap);
163}
164
Andreas Gampe794ad762015-02-23 08:12:24 -0800165NO_RETURN static void Usage(const char* fmt, ...) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700166 va_list ap;
167 va_start(ap, fmt);
168 UsageErrorV(fmt, ap);
169 va_end(ap);
170
Brian Carlstrom6449c622014-02-10 23:48:36 -0800171 UsageError("Command: %s", CommandLine().c_str());
172
Brian Carlstrom7940e442013-07-12 13:46:57 -0700173 UsageError("Usage: dex2oat [options]...");
174 UsageError("");
Jean-Philippe Halimi3d329d72015-03-23 14:09:48 +0100175 UsageError(" -j<number>: specifies the number of threads used for compilation.");
176 UsageError(" Default is the number of detected hardware threads available on the");
177 UsageError(" host system.");
178 UsageError(" Example: -j12");
179 UsageError("");
Richard Uhlere934df22015-03-17 11:26:16 -0700180 UsageError(" --dex-file=<dex-file>: specifies a .dex, .jar, or .apk file to compile.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700181 UsageError(" Example: --dex-file=/system/framework/core.jar");
182 UsageError("");
Richard Uhlere934df22015-03-17 11:26:16 -0700183 UsageError(" --dex-location=<dex-location>: specifies an alternative dex location to");
184 UsageError(" encode in the oat file for the corresponding --dex-file argument.");
185 UsageError(" Example: --dex-file=/home/build/out/system/framework/core.jar");
186 UsageError(" --dex-location=/system/framework/core.jar");
187 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700188 UsageError(" --zip-fd=<file-descriptor>: specifies a file descriptor of a zip file");
189 UsageError(" containing a classes.dex file to compile.");
190 UsageError(" Example: --zip-fd=5");
191 UsageError("");
Brian Carlstrom45602482013-07-21 22:07:55 -0700192 UsageError(" --zip-location=<zip-location>: specifies a symbolic name for the file");
193 UsageError(" corresponding to the file descriptor specified by --zip-fd.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700194 UsageError(" Example: --zip-location=/system/app/Calculator.apk");
195 UsageError("");
196 UsageError(" --oat-file=<file.oat>: specifies the oat output destination via a filename.");
197 UsageError(" Example: --oat-file=/system/framework/boot.oat");
198 UsageError("");
199 UsageError(" --oat-fd=<number>: specifies the oat output destination via a file descriptor.");
Wonil Kim9cb554a2014-04-28 11:26:55 +0900200 UsageError(" Example: --oat-fd=6");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700201 UsageError("");
202 UsageError(" --oat-location=<oat-name>: specifies a symbolic name for the file corresponding");
203 UsageError(" to the file descriptor specified by --oat-fd.");
204 UsageError(" Example: --oat-location=/data/dalvik-cache/system@app@Calculator.apk.oat");
205 UsageError("");
206 UsageError(" --oat-symbols=<file.oat>: specifies the oat output destination with full symbols.");
207 UsageError(" Example: --oat-symbols=/symbols/system/framework/boot.oat");
208 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700209 UsageError(" --image=<file.art>: specifies the output image filename.");
210 UsageError(" Example: --image=/system/framework/boot.art");
211 UsageError("");
212 UsageError(" --image-classes=<classname-file>: specifies classes to include in an image.");
213 UsageError(" Example: --image=frameworks/base/preloaded-classes");
214 UsageError("");
215 UsageError(" --base=<hex-address>: specifies the base address when creating a boot image.");
216 UsageError(" Example: --base=0x50000000");
217 UsageError("");
218 UsageError(" --boot-image=<file.art>: provide the image file for the boot class path.");
219 UsageError(" Example: --boot-image=/system/framework/boot.art");
Nicolas Geoffray9583fbc2014-02-28 15:21:07 +0000220 UsageError(" Default: $ANDROID_ROOT/system/framework/boot.art");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700221 UsageError("");
222 UsageError(" --android-root=<path>: used to locate libraries for portable linking.");
223 UsageError(" Example: --android-root=out/host/linux-x86");
224 UsageError(" Default: $ANDROID_ROOT");
225 UsageError("");
Andreas Gampe57b34292015-01-14 15:45:59 -0800226 UsageError(" --instruction-set=(arm|arm64|mips|mips64|x86|x86_64): compile for a particular");
Alex Light53cb16b2014-06-12 11:26:29 -0700227 UsageError(" instruction set.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700228 UsageError(" Example: --instruction-set=x86");
229 UsageError(" Default: arm");
230 UsageError("");
Dave Allison70202782013-10-22 17:52:19 -0700231 UsageError(" --instruction-set-features=...,: Specify instruction set features");
232 UsageError(" Example: --instruction-set-features=div");
233 UsageError(" Default: default");
234 UsageError("");
Igor Murashkin46774762014-10-22 11:37:02 -0700235 UsageError(" --compile-pic: Force indirect use of code, methods, and classes");
236 UsageError(" Default: disabled");
237 UsageError("");
Elliott Hughes956af0f2014-12-11 14:34:28 -0800238 UsageError(" --compiler-backend=(Quick|Optimizing): select compiler backend");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700239 UsageError(" set.");
Elliott Hughes956af0f2014-12-11 14:34:28 -0800240 UsageError(" Example: --compiler-backend=Optimizing");
Nicolas Geoffray409e8092015-10-01 10:32:19 +0100241 UsageError(" Default: Optimizing");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700242 UsageError("");
Nicolas Geoffray88157ef2014-09-12 10:29:53 +0100243 UsageError(" --compiler-filter="
244 "(verify-none"
245 "|interpret-only"
246 "|space"
247 "|balanced"
248 "|speed"
249 "|everything"
250 "|time):");
Jeff Hao4a200f52014-04-01 14:58:49 -0700251 UsageError(" select compiler filter.");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800252 UsageError(" Example: --compiler-filter=everything");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800253 UsageError(" Default: speed");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800254 UsageError("");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800255 UsageError(" --huge-method-max=<method-instruction-count>: threshold size for a huge");
256 UsageError(" method for compiler filter tuning.");
257 UsageError(" Example: --huge-method-max=%d", CompilerOptions::kDefaultHugeMethodThreshold);
258 UsageError(" Default: %d", CompilerOptions::kDefaultHugeMethodThreshold);
259 UsageError("");
260 UsageError(" --large-method-max=<method-instruction-count>: threshold size for a large");
261 UsageError(" method for compiler filter tuning.");
262 UsageError(" Example: --large-method-max=%d", CompilerOptions::kDefaultLargeMethodThreshold);
263 UsageError(" Default: %d", CompilerOptions::kDefaultLargeMethodThreshold);
264 UsageError("");
265 UsageError(" --small-method-max=<method-instruction-count>: threshold size for a small");
266 UsageError(" method for compiler filter tuning.");
267 UsageError(" Example: --small-method-max=%d", CompilerOptions::kDefaultSmallMethodThreshold);
268 UsageError(" Default: %d", CompilerOptions::kDefaultSmallMethodThreshold);
269 UsageError("");
270 UsageError(" --tiny-method-max=<method-instruction-count>: threshold size for a tiny");
271 UsageError(" method for compiler filter tuning.");
272 UsageError(" Example: --tiny-method-max=%d", CompilerOptions::kDefaultTinyMethodThreshold);
273 UsageError(" Default: %d", CompilerOptions::kDefaultTinyMethodThreshold);
274 UsageError("");
275 UsageError(" --num-dex-methods=<method-count>: threshold size for a small dex file for");
276 UsageError(" compiler filter tuning. If the input has fewer than this many methods");
Jeff Hao4a200f52014-04-01 14:58:49 -0700277 UsageError(" and the filter is not interpret-only or verify-none, overrides the");
278 UsageError(" filter to use speed");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800279 UsageError(" Example: --num-dex-method=%d", CompilerOptions::kDefaultNumDexMethodsThreshold);
280 UsageError(" Default: %d", CompilerOptions::kDefaultNumDexMethodsThreshold);
281 UsageError("");
Calin Juravleec748352015-07-29 13:52:12 +0100282 UsageError(" --inline-depth-limit=<depth-limit>: the depth limit of inlining for fine tuning");
283 UsageError(" the compiler. A zero value will disable inlining. Honored only by Optimizing.");
Roland Levillaina215b952015-08-07 11:38:32 +0100284 UsageError(" Has priority over the --compiler-filter option. Intended for ");
285 UsageError(" development/experimental use.");
Calin Juravleec748352015-07-29 13:52:12 +0100286 UsageError(" Example: --inline-depth-limit=%d", CompilerOptions::kDefaultInlineDepthLimit);
287 UsageError(" Default: %d", CompilerOptions::kDefaultInlineDepthLimit);
288 UsageError("");
289 UsageError(" --inline-max-code-units=<code-units-count>: the maximum code units that a method");
290 UsageError(" can have to be considered for inlining. A zero value will disable inlining.");
Roland Levillaina215b952015-08-07 11:38:32 +0100291 UsageError(" Honored only by Optimizing. Has priority over the --compiler-filter option.");
292 UsageError(" Intended for development/experimental use.");
Calin Juravleec748352015-07-29 13:52:12 +0100293 UsageError(" Example: --inline-max-code-units=%d",
294 CompilerOptions::kDefaultInlineMaxCodeUnits);
295 UsageError(" Default: %d", CompilerOptions::kDefaultInlineMaxCodeUnits);
296 UsageError("");
Ian Rogers46398602013-08-20 07:50:36 -0700297 UsageError(" --dump-timing: display a breakdown of where time was spent");
298 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700299 UsageError(" --include-patch-information: Include patching information so the generated code");
300 UsageError(" can have its base address moved without full recompilation.");
301 UsageError("");
302 UsageError(" --no-include-patch-information: Do not include patching information.");
303 UsageError("");
David Srbecky8363c772015-05-28 16:12:43 +0100304 UsageError(" -g");
305 UsageError(" --generate-debug-info: Generate debug information for native debugging,");
306 UsageError(" such as stack unwinding information, ELF symbols and DWARF sections.");
307 UsageError(" This generates all the available information. Unneeded parts can be");
308 UsageError(" stripped using standard command line tools such as strip or objcopy.");
309 UsageError(" (enabled by default in debug builds, disabled by default otherwise)");
Alex Light78382fa2014-06-06 15:45:32 -0700310 UsageError("");
Roland Levillainb2872da2015-09-02 09:35:25 +0100311 UsageError(" --debuggable: Produce debuggable code. Implies --generate-debug-info.");
312 UsageError("");
David Srbecky8363c772015-05-28 16:12:43 +0100313 UsageError(" --no-generate-debug-info: Do not generate debug information for native debugging.");
David Srbecky8dc73242015-04-12 11:40:39 +0100314 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700315 UsageError(" --runtime-arg <argument>: used to specify various arguments for the runtime,");
316 UsageError(" such as initial heap size, maximum heap size, and verbose output.");
317 UsageError(" Use a separate --runtime-arg switch for each argument.");
318 UsageError(" Example: --runtime-arg -Xms256m");
Jeff Hao4a200f52014-04-01 14:58:49 -0700319 UsageError("");
Dave Allisond6ed6422014-04-09 23:36:15 +0000320 UsageError(" --profile-file=<filename>: specify profiler output file to use for compilation.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700321 UsageError("");
Chao-ying Fucd8ce662014-03-11 14:57:19 -0700322 UsageError(" --print-pass-names: print a list of pass names");
323 UsageError("");
324 UsageError(" --disable-passes=<pass-names>: disable one or more passes separated by comma.");
325 UsageError(" Example: --disable-passes=UseCount,BBOptimizations");
326 UsageError("");
Razvan A Lupusorubd25d4b2014-07-02 18:16:51 -0700327 UsageError(" --print-pass-options: print a list of passes that have configurable options along "
328 "with the setting.");
329 UsageError(" Will print default if no overridden setting exists.");
330 UsageError("");
331 UsageError(" --pass-options=Pass1Name:Pass1OptionName:Pass1Option#,"
332 "Pass2Name:Pass2OptionName:Pass2Option#");
333 UsageError(" Used to specify a pass specific option. The setting itself must be integer.");
334 UsageError(" Separator used between options is a comma.");
335 UsageError("");
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800336 UsageError(" --swap-file=<file-name>: specifies a file to use for swap.");
337 UsageError(" Example: --swap-file=/data/tmp/swap.001");
338 UsageError("");
339 UsageError(" --swap-fd=<file-descriptor>: specifies a file to use for swap (by descriptor).");
340 UsageError(" Example: --swap-fd=10");
341 UsageError("");
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700342 UsageError(" --app-image-fd=<file-descriptor>: specify output file descriptor for app image.");
343 UsageError(" Example: --app-image-fd=10");
344 UsageError("");
345 UsageError(" --app-image-file=<file-name>: specify a file name for app image.");
346 UsageError(" Example: --app-image-file=/data/dalvik-cache/system@app@Calculator.apk.art");
347 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700348 std::cerr << "See log for usage error information\n";
349 exit(EXIT_FAILURE);
350}
351
Brian Carlstrom7940e442013-07-12 13:46:57 -0700352// The primary goal of the watchdog is to prevent stuck build servers
353// during development when fatal aborts lead to a cascade of failures
354// that result in a deadlock.
355class WatchDog {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800356// WatchDog defines its own CHECK_PTHREAD_CALL to avoid using LOG which uses locks
Brian Carlstrom7940e442013-07-12 13:46:57 -0700357#undef CHECK_PTHREAD_CALL
358#define CHECK_WATCH_DOG_PTHREAD_CALL(call, args, what) \
359 do { \
360 int rc = call args; \
361 if (rc != 0) { \
362 errno = rc; \
363 std::string message(# call); \
364 message += " failed for "; \
365 message += reason; \
366 Fatal(message); \
367 } \
368 } while (false)
369
370 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -0700371 explicit WatchDog(bool is_watch_dog_enabled) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700372 is_watch_dog_enabled_ = is_watch_dog_enabled;
373 if (!is_watch_dog_enabled_) {
374 return;
375 }
376 shutting_down_ = false;
377 const char* reason = "dex2oat watch dog thread startup";
Kenny Root51316382014-05-13 14:59:37 -0700378 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_init, (&mutex_, nullptr), reason);
379 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_init, (&cond_, nullptr), reason);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700380 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_init, (&attr_), reason);
381 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_create, (&pthread_, &attr_, &CallBack, this), reason);
382 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_destroy, (&attr_), reason);
383 }
384 ~WatchDog() {
385 if (!is_watch_dog_enabled_) {
386 return;
387 }
388 const char* reason = "dex2oat watch dog thread shutdown";
389 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
390 shutting_down_ = true;
391 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_signal, (&cond_), reason);
392 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
393
Kenny Root51316382014-05-13 14:59:37 -0700394 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_join, (pthread_, nullptr), reason);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700395
396 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_destroy, (&cond_), reason);
397 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_destroy, (&mutex_), reason);
398 }
399
400 private:
401 static void* CallBack(void* arg) {
402 WatchDog* self = reinterpret_cast<WatchDog*>(arg);
403 ::art::SetThreadName("dex2oat watch dog");
404 self->Wait();
Kenny Root51316382014-05-13 14:59:37 -0700405 return nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700406 }
407
Andreas Gampe794ad762015-02-23 08:12:24 -0800408 NO_RETURN static void Fatal(const std::string& message) {
Andreas Gamped687e372015-04-28 23:16:03 -0700409 // TODO: When we can guarantee it won't prevent shutdown in error cases, move to LOG. However,
410 // it's rather easy to hang in unwinding.
411 // LogLine also avoids ART logging lock issues, as it's really only a wrapper around
412 // logcat logging or stderr output.
413 LogMessage::LogLine(__FILE__, __LINE__, LogSeverity::FATAL, message.c_str());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700414 exit(1);
415 }
416
417 void Wait() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700418 // TODO: tune the multiplier for GC verification, the following is just to make the timeout
419 // large.
Andreas Gamped687e372015-04-28 23:16:03 -0700420 constexpr int64_t multiplier = kVerifyObjectSupport > kVerifyObjectModeFast ? 100 : 1;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700421 timespec timeout_ts;
422 InitTimeSpec(true, CLOCK_REALTIME, multiplier * kWatchDogTimeoutSeconds * 1000, 0, &timeout_ts);
423 const char* reason = "dex2oat watch dog thread waiting";
424 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
425 while (!shutting_down_) {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800426 int rc = TEMP_FAILURE_RETRY(pthread_cond_timedwait(&cond_, &mutex_, &timeout_ts));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700427 if (rc == ETIMEDOUT) {
Andreas Gamped687e372015-04-28 23:16:03 -0700428 Fatal(StringPrintf("dex2oat did not finish after %" PRId64 " seconds",
429 kWatchDogTimeoutSeconds));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700430 } else if (rc != 0) {
431 std::string message(StringPrintf("pthread_cond_timedwait failed: %s",
432 strerror(errno)));
433 Fatal(message.c_str());
434 }
435 }
436 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
437 }
438
439 // 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 -0700440 // Debug builds are slower so they have larger timeouts.
Andreas Gamped687e372015-04-28 23:16:03 -0700441 static constexpr int64_t kSlowdownFactor = kIsDebugBuild ? 5U : 1U;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800442
Andreas Gampe540138a2015-09-14 15:34:38 -0700443 // 9.5 minutes scaled by kSlowdownFactor. This is slightly smaller than the Package Manager
444 // watchdog (PackageManagerService.WATCHDOG_TIMEOUT, 10 minutes), so that dex2oat will abort
445 // itself before that watchdog would take down the system server.
446 static constexpr int64_t kWatchDogTimeoutSeconds = kSlowdownFactor * (9 * 60 + 30);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700447
448 bool is_watch_dog_enabled_;
449 bool shutting_down_;
450 // TODO: Switch to Mutex when we can guarantee it won't prevent shutdown in error cases.
451 pthread_mutex_t mutex_;
452 pthread_cond_t cond_;
453 pthread_attr_t attr_;
454 pthread_t pthread_;
455};
Brian Carlstrom7940e442013-07-12 13:46:57 -0700456
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800457static constexpr size_t kMinDexFilesForSwap = 2;
458static constexpr size_t kMinDexFileCumulativeSizeForSwap = 20 * MB;
459
460static bool UseSwap(bool is_image, std::vector<const DexFile*>& dex_files) {
461 if (is_image) {
462 // Don't use swap, we know generation should succeed, and we don't want to slow it down.
463 return false;
464 }
465 if (dex_files.size() < kMinDexFilesForSwap) {
466 // If there are less dex files than the threshold, assume it's gonna be fine.
467 return false;
468 }
469 size_t dex_files_size = 0;
470 for (const auto* dex_file : dex_files) {
471 dex_files_size += dex_file->GetHeader().file_size_;
472 }
473 return dex_files_size >= kMinDexFileCumulativeSizeForSwap;
474}
475
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800476class Dex2Oat FINAL {
477 public:
478 explicit Dex2Oat(TimingLogger* timings) :
Nicolas Geoffray409e8092015-10-01 10:32:19 +0100479 compiler_kind_(Compiler::kOptimizing),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800480 instruction_set_(kRuntimeISA),
481 // Take the default set of instruction features from the build.
Andreas Gampe3f30e122015-09-17 14:03:21 -0700482 verification_results_(nullptr),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800483 method_inliner_map_(),
484 runtime_(nullptr),
485 thread_count_(sysconf(_SC_NPROCESSORS_CONF)),
486 start_ns_(NanoTime()),
487 oat_fd_(-1),
488 zip_fd_(-1),
489 image_base_(0U),
490 image_classes_zip_filename_(nullptr),
491 image_classes_filename_(nullptr),
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800492 compiled_classes_zip_filename_(nullptr),
493 compiled_classes_filename_(nullptr),
Andreas Gampe70bef0d2015-04-15 02:37:28 -0700494 compiled_methods_zip_filename_(nullptr),
495 compiled_methods_filename_(nullptr),
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700496 app_image_(false),
497 boot_image_(false),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800498 is_host_(false),
Vladimir Marko10c13562015-11-25 14:33:36 +0000499 image_writer_(nullptr),
Andreas Gampe3f30e122015-09-17 14:03:21 -0700500 driver_(nullptr),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800501 dump_stats_(false),
502 dump_passes_(false),
503 dump_timing_(false),
504 dump_slow_timing_(kIsDebugBuild),
Calin Juravle87000a92015-08-24 15:34:44 +0100505 dump_cfg_append_(false),
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800506 swap_fd_(-1),
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700507 app_image_fd_(kInvalidImageFd),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800508 timings_(timings) {}
509
510 ~Dex2Oat() {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800511 // Free opened dex files before deleting the runtime_, because ~DexFile
512 // uses MemMap, which is shut down by ~Runtime.
513 class_path_files_.clear();
514 opened_dex_files_.clear();
515
516 // Log completion time before deleting the runtime_, because this accesses
517 // the runtime.
518 LogCompletionTime();
519
Vladimir Marko307dac92015-10-20 11:20:09 +0100520 if (!kIsDebugBuild && !(RUNNING_ON_MEMORY_TOOL && kMemoryToolDetectsLeaks)) {
521 // We want to just exit on non-debug builds, not bringing the runtime down
522 // in an orderly fashion. So release the following fields.
523 driver_.release();
524 image_writer_.release();
525 for (std::unique_ptr<const DexFile>& dex_file : opened_dex_files_) {
526 dex_file.release();
527 }
528 oat_file_.release();
529 runtime_.release();
530 verification_results_.release();
531 key_value_store_.release();
Vladimir Markof94b7812014-06-05 15:48:04 +0100532 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700533 }
534
Roland Levillain9ec5e222015-08-17 20:18:41 +0100535 struct ParserOptions {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800536 std::string oat_symbols;
537 std::string boot_image_filename;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800538 bool watch_dog_enabled = true;
Nicolas Geoffray1412dfa2015-03-20 14:48:13 +0000539 bool requested_specific_compiler = false;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800540 std::string error_msg;
Roland Levillain9ec5e222015-08-17 20:18:41 +0100541 };
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800542
Roland Levillain9ec5e222015-08-17 20:18:41 +0100543 void ParseZipFd(const StringPiece& option) {
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000544 ParseUintOption(option, "--zip-fd", &zip_fd_, Usage);
Roland Levillain9ec5e222015-08-17 20:18:41 +0100545 }
546
547 void ParseOatFd(const StringPiece& option) {
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000548 ParseUintOption(option, "--oat-fd", &oat_fd_, Usage);
Roland Levillain9ec5e222015-08-17 20:18:41 +0100549 }
550
551 void ParseJ(const StringPiece& option) {
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000552 ParseUintOption(option, "-j", &thread_count_, Usage, /* is_long_option */ false);
Roland Levillain9ec5e222015-08-17 20:18:41 +0100553 }
554
555 void ParseBase(const StringPiece& option) {
556 DCHECK(option.starts_with("--base="));
557 const char* image_base_str = option.substr(strlen("--base=")).data();
558 char* end;
559 image_base_ = strtoul(image_base_str, &end, 16);
560 if (end == image_base_str || *end != '\0') {
561 Usage("Failed to parse hexadecimal value for option %s", option.data());
562 }
563 }
564
565 void ParseInstructionSet(const StringPiece& option) {
566 DCHECK(option.starts_with("--instruction-set="));
567 StringPiece instruction_set_str = option.substr(strlen("--instruction-set=")).data();
568 // StringPiece is not necessarily zero-terminated, so need to make a copy and ensure it.
569 std::unique_ptr<char[]> buf(new char[instruction_set_str.length() + 1]);
570 strncpy(buf.get(), instruction_set_str.data(), instruction_set_str.length());
571 buf.get()[instruction_set_str.length()] = 0;
572 instruction_set_ = GetInstructionSetFromString(buf.get());
573 // arm actually means thumb2.
574 if (instruction_set_ == InstructionSet::kArm) {
575 instruction_set_ = InstructionSet::kThumb2;
576 }
577 }
578
579 void ParseInstructionSetVariant(const StringPiece& option, ParserOptions* parser_options) {
580 DCHECK(option.starts_with("--instruction-set-variant="));
581 StringPiece str = option.substr(strlen("--instruction-set-variant=")).data();
582 instruction_set_features_.reset(
583 InstructionSetFeatures::FromVariant(
584 instruction_set_, str.as_string(), &parser_options->error_msg));
585 if (instruction_set_features_.get() == nullptr) {
586 Usage("%s", parser_options->error_msg.c_str());
587 }
588 }
589
590 void ParseInstructionSetFeatures(const StringPiece& option, ParserOptions* parser_options) {
591 DCHECK(option.starts_with("--instruction-set-features="));
592 StringPiece str = option.substr(strlen("--instruction-set-features=")).data();
593 if (instruction_set_features_.get() == nullptr) {
594 instruction_set_features_.reset(
595 InstructionSetFeatures::FromVariant(
596 instruction_set_, "default", &parser_options->error_msg));
597 if (instruction_set_features_.get() == nullptr) {
598 Usage("Problem initializing default instruction set features variant: %s",
599 parser_options->error_msg.c_str());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700600 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800601 }
Roland Levillain9ec5e222015-08-17 20:18:41 +0100602 instruction_set_features_.reset(
603 instruction_set_features_->AddFeaturesFromString(str.as_string(),
604 &parser_options->error_msg));
605 if (instruction_set_features_.get() == nullptr) {
606 Usage("Error parsing '%s': %s", option.data(), parser_options->error_msg.c_str());
607 }
608 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800609
Roland Levillain9ec5e222015-08-17 20:18:41 +0100610 void ParseCompilerBackend(const StringPiece& option, ParserOptions* parser_options) {
611 DCHECK(option.starts_with("--compiler-backend="));
612 parser_options->requested_specific_compiler = true;
613 StringPiece backend_str = option.substr(strlen("--compiler-backend=")).data();
614 if (backend_str == "Quick") {
615 compiler_kind_ = Compiler::kQuick;
616 } else if (backend_str == "Optimizing") {
617 compiler_kind_ = Compiler::kOptimizing;
618 } else {
619 Usage("Unknown compiler backend: %s", backend_str.data());
620 }
621 }
622
Roland Levillain9ec5e222015-08-17 20:18:41 +0100623 void ProcessOptions(ParserOptions* parser_options) {
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700624 boot_image_ = !image_filename_.empty();
625 app_image_ = app_image_fd_ != -1 || !app_image_file_name_.empty();
626
627 if (IsAppImage() && IsBootImage()) {
628 Usage("Can't have both --image and (--app-image-fd or --app-image-file)");
629 }
630
631 if (IsBootImage()) {
Nicolas Geoffray409e8092015-10-01 10:32:19 +0100632 // We need the boot image to always be debuggable.
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000633 compiler_options_->debuggable_ = true;
Nicolas Geoffray1412dfa2015-03-20 14:48:13 +0000634 }
Nicolas Geoffray9bb492a2014-11-25 23:42:00 +0000635
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800636 if (oat_filename_.empty() && oat_fd_ == -1) {
637 Usage("Output must be supplied with either --oat-file or --oat-fd");
638 }
639
640 if (!oat_filename_.empty() && oat_fd_ != -1) {
641 Usage("--oat-file should not be used with --oat-fd");
642 }
643
Roland Levillain9ec5e222015-08-17 20:18:41 +0100644 if (!parser_options->oat_symbols.empty() && oat_fd_ != -1) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800645 Usage("--oat-symbols should not be used with --oat-fd");
646 }
647
Roland Levillain9ec5e222015-08-17 20:18:41 +0100648 if (!parser_options->oat_symbols.empty() && is_host_) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800649 Usage("--oat-symbols should not be used with --host");
650 }
651
652 if (oat_fd_ != -1 && !image_filename_.empty()) {
653 Usage("--oat-fd should not be used with --image");
654 }
655
656 if (android_root_.empty()) {
657 const char* android_root_env_var = getenv("ANDROID_ROOT");
658 if (android_root_env_var == nullptr) {
659 Usage("--android-root unspecified and ANDROID_ROOT not set");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700660 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800661 android_root_ += android_root_env_var;
662 }
663
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700664 if (!boot_image_ && parser_options->boot_image_filename.empty()) {
Roland Levillain9ec5e222015-08-17 20:18:41 +0100665 parser_options->boot_image_filename += android_root_;
666 parser_options->boot_image_filename += "/framework/boot.art";
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800667 }
Roland Levillain9ec5e222015-08-17 20:18:41 +0100668 if (!parser_options->boot_image_filename.empty()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800669 boot_image_option_ += "-Ximage:";
Roland Levillain9ec5e222015-08-17 20:18:41 +0100670 boot_image_option_ += parser_options->boot_image_filename;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800671 }
672
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700673 if (image_classes_filename_ != nullptr && !IsBootImage()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800674 Usage("--image-classes should only be used with --image");
675 }
676
677 if (image_classes_filename_ != nullptr && !boot_image_option_.empty()) {
678 Usage("--image-classes should not be used with --boot-image");
679 }
680
681 if (image_classes_zip_filename_ != nullptr && image_classes_filename_ == nullptr) {
682 Usage("--image-classes-zip should be used with --image-classes");
683 }
684
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700685 if (compiled_classes_filename_ != nullptr && !IsBootImage()) {
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800686 Usage("--compiled-classes should only be used with --image");
687 }
688
689 if (compiled_classes_filename_ != nullptr && !boot_image_option_.empty()) {
690 Usage("--compiled-classes should not be used with --boot-image");
691 }
692
693 if (compiled_classes_zip_filename_ != nullptr && compiled_classes_filename_ == nullptr) {
694 Usage("--compiled-classes-zip should be used with --compiled-classes");
695 }
696
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800697 if (dex_filenames_.empty() && zip_fd_ == -1) {
698 Usage("Input must be supplied with either --dex-file or --zip-fd");
699 }
700
701 if (!dex_filenames_.empty() && zip_fd_ != -1) {
702 Usage("--dex-file should not be used with --zip-fd");
703 }
704
705 if (!dex_filenames_.empty() && !zip_location_.empty()) {
706 Usage("--dex-file should not be used with --zip-location");
707 }
708
709 if (dex_locations_.empty()) {
710 for (const char* dex_file_name : dex_filenames_) {
711 dex_locations_.push_back(dex_file_name);
712 }
713 } else if (dex_locations_.size() != dex_filenames_.size()) {
714 Usage("--dex-location arguments do not match --dex-file arguments");
715 }
716
717 if (zip_fd_ != -1 && zip_location_.empty()) {
718 Usage("--zip-location should be supplied with --zip-fd");
719 }
720
721 if (boot_image_option_.empty()) {
722 if (image_base_ == 0) {
723 Usage("Non-zero --base not specified");
724 }
725 }
726
727 oat_stripped_ = oat_filename_;
Roland Levillain9ec5e222015-08-17 20:18:41 +0100728 if (!parser_options->oat_symbols.empty()) {
729 oat_unstripped_ = parser_options->oat_symbols;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700730 } else {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800731 oat_unstripped_ = oat_filename_;
732 }
733
734 // If no instruction set feature was given, use the default one for the target
735 // instruction set.
736 if (instruction_set_features_.get() == nullptr) {
737 instruction_set_features_.reset(
Roland Levillain9ec5e222015-08-17 20:18:41 +0100738 InstructionSetFeatures::FromVariant(
739 instruction_set_, "default", &parser_options->error_msg));
Ian Rogersd582fa42014-11-05 23:46:43 -0800740 if (instruction_set_features_.get() == nullptr) {
741 Usage("Problem initializing default instruction set features variant: %s",
Roland Levillain9ec5e222015-08-17 20:18:41 +0100742 parser_options->error_msg.c_str());
Ian Rogersd582fa42014-11-05 23:46:43 -0800743 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800744 }
745
746 if (instruction_set_ == kRuntimeISA) {
747 std::unique_ptr<const InstructionSetFeatures> runtime_features(
748 InstructionSetFeatures::FromCppDefines());
749 if (!instruction_set_features_->Equals(runtime_features.get())) {
750 LOG(WARNING) << "Mismatch between dex2oat instruction set features ("
751 << *instruction_set_features_ << ") and those of dex2oat executable ("
752 << *runtime_features <<") for the command line:\n"
753 << CommandLine();
754 }
755 }
756
Roland Levillaina215b952015-08-07 11:38:32 +0100757 // It they are not set, use default values for inlining settings.
758 // TODO: We should rethink the compiler filter. We mostly save
759 // time here, which is orthogonal to space.
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000760 if (compiler_options_->inline_depth_limit_ == CompilerOptions::kUnsetInlineDepthLimit) {
761 compiler_options_->inline_depth_limit_ =
762 (compiler_options_->compiler_filter_ == CompilerOptions::kSpace)
Roland Levillaina215b952015-08-07 11:38:32 +0100763 // Implementation of the space filter: limit inlining depth.
764 ? CompilerOptions::kSpaceFilterInlineDepthLimit
765 : CompilerOptions::kDefaultInlineDepthLimit;
766 }
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000767 if (compiler_options_->inline_max_code_units_ == CompilerOptions::kUnsetInlineMaxCodeUnits) {
768 compiler_options_->inline_max_code_units_ =
769 (compiler_options_->compiler_filter_ == CompilerOptions::kSpace)
Roland Levillaina215b952015-08-07 11:38:32 +0100770 // Implementation of the space filter: limit inlining max code units.
771 ? CompilerOptions::kSpaceFilterInlineMaxCodeUnits
772 : CompilerOptions::kDefaultInlineMaxCodeUnits;
773 }
774
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800775 // Checks are all explicit until we know the architecture.
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800776 // Set the compilation target's implicit checks options.
777 switch (instruction_set_) {
778 case kArm:
779 case kThumb2:
780 case kArm64:
781 case kX86:
782 case kX86_64:
Douglas Leung22bb5a22015-07-02 16:42:08 -0700783 case kMips:
784 case kMips64:
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000785 compiler_options_->implicit_null_checks_ = true;
786 compiler_options_->implicit_so_checks_ = true;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800787 break;
788
789 default:
790 // Defaults are correct.
791 break;
792 }
793
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000794 compiler_options_->verbose_methods_ = verbose_methods_.empty() ? nullptr : &verbose_methods_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800795
796 // Done with usage checks, enable watchdog if requested
Roland Levillain9ec5e222015-08-17 20:18:41 +0100797 if (parser_options->watch_dog_enabled) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800798 watchdog_.reset(new WatchDog(true));
799 }
800
801 // Fill some values into the key-value store for the oat header.
802 key_value_store_.reset(new SafeMap<std::string, std::string>());
Roland Levillain9ec5e222015-08-17 20:18:41 +0100803 }
804
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000805 void InsertCompileOptions(int argc, char** argv) {
Roland Levillain9ec5e222015-08-17 20:18:41 +0100806 std::ostringstream oss;
807 for (int i = 0; i < argc; ++i) {
808 if (i > 0) {
809 oss << ' ';
810 }
811 oss << argv[i];
812 }
813 key_value_store_->Put(OatHeader::kDex2OatCmdLineKey, oss.str());
814 oss.str(""); // Reset.
815 oss << kRuntimeISA;
816 key_value_store_->Put(OatHeader::kDex2OatHostKey, oss.str());
817 key_value_store_->Put(
818 OatHeader::kPicKey,
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000819 compiler_options_->compile_pic_ ? OatHeader::kTrueValue : OatHeader::kFalseValue);
Roland Levillain9ec5e222015-08-17 20:18:41 +0100820 key_value_store_->Put(
821 OatHeader::kDebuggableKey,
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000822 compiler_options_->debuggable_ ? OatHeader::kTrueValue : OatHeader::kFalseValue);
Roland Levillain9ec5e222015-08-17 20:18:41 +0100823 }
824
825 // Parse the arguments from the command line. In case of an unrecognized option or impossible
826 // values/combinations, a usage error will be displayed and exit() is called. Thus, if the method
827 // returns, arguments have been successfully parsed.
828 void ParseArgs(int argc, char** argv) {
829 original_argc = argc;
830 original_argv = argv;
831
832 InitLogging(argv);
833
834 // Skip over argv[0].
835 argv++;
836 argc--;
837
838 if (argc == 0) {
839 Usage("No arguments specified");
840 }
841
842 std::unique_ptr<ParserOptions> parser_options(new ParserOptions());
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000843 compiler_options_.reset(new CompilerOptions());
Roland Levillain9ec5e222015-08-17 20:18:41 +0100844
845 for (int i = 0; i < argc; i++) {
846 const StringPiece option(argv[i]);
847 const bool log_options = false;
848 if (log_options) {
849 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
850 }
851 if (option.starts_with("--dex-file=")) {
852 dex_filenames_.push_back(option.substr(strlen("--dex-file=")).data());
853 } else if (option.starts_with("--dex-location=")) {
854 dex_locations_.push_back(option.substr(strlen("--dex-location=")).data());
855 } else if (option.starts_with("--zip-fd=")) {
856 ParseZipFd(option);
857 } else if (option.starts_with("--zip-location=")) {
858 zip_location_ = option.substr(strlen("--zip-location=")).data();
859 } else if (option.starts_with("--oat-file=")) {
860 oat_filename_ = option.substr(strlen("--oat-file=")).data();
861 } else if (option.starts_with("--oat-symbols=")) {
862 parser_options->oat_symbols = option.substr(strlen("--oat-symbols=")).data();
863 } else if (option.starts_with("--oat-fd=")) {
864 ParseOatFd(option);
865 } else if (option == "--watch-dog") {
866 parser_options->watch_dog_enabled = true;
867 } else if (option == "--no-watch-dog") {
868 parser_options->watch_dog_enabled = false;
869 } else if (option.starts_with("-j")) {
870 ParseJ(option);
871 } else if (option.starts_with("--oat-location=")) {
872 oat_location_ = option.substr(strlen("--oat-location=")).data();
873 } else if (option.starts_with("--image=")) {
874 image_filename_ = option.substr(strlen("--image=")).data();
875 } else if (option.starts_with("--image-classes=")) {
876 image_classes_filename_ = option.substr(strlen("--image-classes=")).data();
877 } else if (option.starts_with("--image-classes-zip=")) {
878 image_classes_zip_filename_ = option.substr(strlen("--image-classes-zip=")).data();
879 } else if (option.starts_with("--compiled-classes=")) {
880 compiled_classes_filename_ = option.substr(strlen("--compiled-classes=")).data();
881 } else if (option.starts_with("--compiled-classes-zip=")) {
882 compiled_classes_zip_filename_ = option.substr(strlen("--compiled-classes-zip=")).data();
883 } else if (option.starts_with("--compiled-methods=")) {
884 compiled_methods_filename_ = option.substr(strlen("--compiled-methods=")).data();
885 } else if (option.starts_with("--compiled-methods-zip=")) {
886 compiled_methods_zip_filename_ = option.substr(strlen("--compiled-methods-zip=")).data();
887 } else if (option.starts_with("--base=")) {
888 ParseBase(option);
889 } else if (option.starts_with("--boot-image=")) {
890 parser_options->boot_image_filename = option.substr(strlen("--boot-image=")).data();
891 } else if (option.starts_with("--android-root=")) {
892 android_root_ = option.substr(strlen("--android-root=")).data();
893 } else if (option.starts_with("--instruction-set=")) {
894 ParseInstructionSet(option);
895 } else if (option.starts_with("--instruction-set-variant=")) {
896 ParseInstructionSetVariant(option, parser_options.get());
897 } else if (option.starts_with("--instruction-set-features=")) {
898 ParseInstructionSetFeatures(option, parser_options.get());
899 } else if (option.starts_with("--compiler-backend=")) {
900 ParseCompilerBackend(option, parser_options.get());
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000901 } else if (option.starts_with("--profile-file=")) {
902 profile_file_ = option.substr(strlen("--profile-file=")).data();
903 VLOG(compiler) << "dex2oat: profile file is " << profile_file_;
904 } else if (option == "--no-profile-file") {
905 // No profile
Roland Levillain9ec5e222015-08-17 20:18:41 +0100906 } else if (option == "--host") {
907 is_host_ = true;
908 } else if (option == "--runtime-arg") {
909 if (++i >= argc) {
910 Usage("Missing required argument for --runtime-arg");
911 }
912 if (log_options) {
913 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
914 }
915 runtime_args_.push_back(argv[i]);
916 } else if (option == "--dump-timing") {
917 dump_timing_ = true;
918 } else if (option == "--dump-passes") {
919 dump_passes_ = true;
920 } else if (option.starts_with("--dump-cfg=")) {
921 dump_cfg_file_name_ = option.substr(strlen("--dump-cfg=")).data();
Calin Juravle87000a92015-08-24 15:34:44 +0100922 } else if (option.starts_with("--dump-cfg-append")) {
923 dump_cfg_append_ = true;
Roland Levillain9ec5e222015-08-17 20:18:41 +0100924 } else if (option == "--dump-stats") {
925 dump_stats_ = true;
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000926 } else if (option.starts_with("--swap-file=")) {
927 swap_file_name_ = option.substr(strlen("--swap-file=")).data();
928 } else if (option.starts_with("--swap-fd=")) {
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700929 ParseUintOption(option, "--swap-fd", &swap_fd_, Usage);
930 } else if (option.starts_with("--app-image-file=")) {
931 app_image_file_name_ = option.substr(strlen("--app-image-file=")).data();
932 } else if (option.starts_with("--app-image-fd=")) {
933 ParseUintOption(option, "--app-image-fd", &app_image_fd_, Usage);
Roland Levillain9ec5e222015-08-17 20:18:41 +0100934 } else if (option.starts_with("--verbose-methods=")) {
935 // TODO: rather than switch off compiler logging, make all VLOG(compiler) messages
936 // conditional on having verbost methods.
937 gLogVerbosity.compiler = false;
938 Split(option.substr(strlen("--verbose-methods=")).ToString(), ',', &verbose_methods_);
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000939 } else if (!compiler_options_->ParseCompilerOption(option, Usage)) {
Roland Levillain9ec5e222015-08-17 20:18:41 +0100940 Usage("Unknown argument %s", option.data());
941 }
942 }
943
944 ProcessOptions(parser_options.get());
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800945
946 // Insert some compiler things.
Nicolas Geoffrayabbb0f72015-10-29 18:55:58 +0000947 InsertCompileOptions(argc, argv);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800948 }
949
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800950 // Check whether the oat output file is writable, and open it for later. Also open a swap file,
951 // if a name is given.
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800952 bool OpenFile() {
953 bool create_file = !oat_unstripped_.empty(); // as opposed to using open file descriptor
954 if (create_file) {
955 oat_file_.reset(OS::CreateEmptyFile(oat_unstripped_.c_str()));
956 if (oat_location_.empty()) {
957 oat_location_ = oat_filename_;
958 }
959 } else {
Andreas Gampe4303ba92014-11-06 01:00:46 -0800960 oat_file_.reset(new File(oat_fd_, oat_location_, true));
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800961 oat_file_->DisableAutoClose();
Andreas Gampe4303ba92014-11-06 01:00:46 -0800962 if (oat_file_->SetLength(0) != 0) {
963 PLOG(WARNING) << "Truncating oat file " << oat_location_ << " failed.";
964 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800965 }
966 if (oat_file_.get() == nullptr) {
967 PLOG(ERROR) << "Failed to create oat file: " << oat_location_;
968 return false;
969 }
970 if (create_file && fchmod(oat_file_->Fd(), 0644) != 0) {
971 PLOG(ERROR) << "Failed to make oat file world readable: " << oat_location_;
Andreas Gampe4303ba92014-11-06 01:00:46 -0800972 oat_file_->Erase();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800973 return false;
974 }
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800975
976 // Swap file handling.
977 //
978 // If the swap fd is not -1, we assume this is the file descriptor of an open but unlinked file
979 // that we can use for swap.
980 //
981 // If the swap fd is -1 and we have a swap-file string, open the given file as a swap file. We
982 // will immediately unlink to satisfy the swap fd assumption.
983 if (swap_fd_ == -1 && !swap_file_name_.empty()) {
984 std::unique_ptr<File> swap_file(OS::CreateEmptyFile(swap_file_name_.c_str()));
985 if (swap_file.get() == nullptr) {
986 PLOG(ERROR) << "Failed to create swap file: " << swap_file_name_;
987 return false;
988 }
989 swap_fd_ = swap_file->Fd();
990 swap_file->MarkUnchecked(); // We don't we to track this, it will be unlinked immediately.
991 swap_file->DisableAutoClose(); // We'll handle it ourselves, the File object will be
992 // released immediately.
993 unlink(swap_file_name_.c_str());
994 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800995 return true;
996 }
997
Andreas Gampea650e702014-12-03 14:28:02 -0800998 void EraseOatFile() {
999 DCHECK(oat_file_.get() != nullptr);
1000 oat_file_->Erase();
1001 oat_file_.reset();
1002 }
1003
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001004 void Shutdown() {
1005 ScopedObjectAccess soa(Thread::Current());
1006 for (jobject dex_cache : dex_caches_) {
1007 soa.Env()->DeleteLocalRef(dex_cache);
1008 }
1009 dex_caches_.clear();
1010 }
1011
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001012 // Set up the environment for compilation. Includes starting the runtime and loading/opening the
1013 // boot class path.
1014 bool Setup() {
1015 TimingLogger::ScopedTiming t("dex2oat Setup", timings_);
1016 RuntimeOptions runtime_options;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001017 art::MemMap::Init(); // For ZipEntry::ExtractToMemMap.
1018 if (boot_image_option_.empty()) {
Richard Uhlerc2752592015-01-02 13:28:22 -08001019 std::string boot_class_path = "-Xbootclasspath:";
1020 boot_class_path += Join(dex_filenames_, ':');
1021 runtime_options.push_back(std::make_pair(boot_class_path, nullptr));
1022 std::string boot_class_path_locations = "-Xbootclasspath-locations:";
1023 boot_class_path_locations += Join(dex_locations_, ':');
1024 runtime_options.push_back(std::make_pair(boot_class_path_locations, nullptr));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001025 } else {
Richard Uhlerc2752592015-01-02 13:28:22 -08001026 runtime_options.push_back(std::make_pair(boot_image_option_, nullptr));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001027 }
1028 for (size_t i = 0; i < runtime_args_.size(); i++) {
1029 runtime_options.push_back(std::make_pair(runtime_args_[i], nullptr));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001030 }
Brian Carlstromd76e0832013-08-29 15:17:42 -07001031
Vladimir Marko307dac92015-10-20 11:20:09 +01001032 verification_results_.reset(new VerificationResults(compiler_options_.get()));
Andreas Gampe4585f872015-03-27 23:45:15 -07001033 callbacks_.reset(new QuickCompilerCallbacks(
Vladimir Marko307dac92015-10-20 11:20:09 +01001034 verification_results_.get(),
Andreas Gampe4585f872015-03-27 23:45:15 -07001035 &method_inliner_map_,
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001036 IsBootImage() ?
Andreas Gampe4585f872015-03-27 23:45:15 -07001037 CompilerCallbacks::CallbackMode::kCompileBootImage :
1038 CompilerCallbacks::CallbackMode::kCompileApp));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001039 runtime_options.push_back(std::make_pair("compilercallbacks", callbacks_.get()));
1040 runtime_options.push_back(
1041 std::make_pair("imageinstructionset", GetInstructionSetString(instruction_set_)));
1042
Andreas Gampe1d00add2015-02-27 19:35:46 -08001043 // Only allow no boot image for the runtime if we're compiling one. When we compile an app,
1044 // we don't want fallback mode, it will abort as we do not push a boot classpath (it might
1045 // have been stripped in preopting, anyways).
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001046 if (!IsBootImage()) {
Andreas Gampe1d00add2015-02-27 19:35:46 -08001047 runtime_options.push_back(std::make_pair("-Xno-dex-file-fallback", nullptr));
1048 }
Calin Juravle01aaf6e2015-06-19 22:05:39 +01001049 // Disable libsigchain. We don't don't need it during compilation and it prevents us
1050 // from getting a statically linked version of dex2oat (because of dlsym and RTLD_NEXT).
1051 runtime_options.push_back(std::make_pair("-Xno-sig-chain", nullptr));
Andreas Gampe1d00add2015-02-27 19:35:46 -08001052
Andreas Gampec7ae55d2015-09-15 20:04:54 -07001053 {
1054 TimingLogger::ScopedTiming t_runtime("Create runtime", timings_);
1055 if (!CreateRuntime(runtime_options)) {
1056 return false;
1057 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001058 }
1059
1060 // Runtime::Create acquired the mutator_lock_ that is normally given away when we
1061 // Runtime::Start, give it away now so that we don't starve GC.
1062 Thread* self = Thread::Current();
1063 self->TransitionFromRunnableToSuspended(kNative);
1064 // If we're doing the image, override the compiler filter to force full compilation. Must be
1065 // done ahead of WellKnownClasses::Init that causes verification. Note: doesn't force
1066 // compilation of class initializers.
1067 // Whilst we're in native take the opportunity to initialize well known classes.
1068 WellKnownClasses::Init(self->GetJniEnv());
1069
1070 // If --image-classes was specified, calculate the full list of classes to include in the image
1071 if (image_classes_filename_ != nullptr) {
1072 std::string error_msg;
1073 if (image_classes_zip_filename_ != nullptr) {
1074 image_classes_.reset(ReadImageClassesFromZip(image_classes_zip_filename_,
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001075 image_classes_filename_,
1076 &error_msg));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001077 } else {
1078 image_classes_.reset(ReadImageClassesFromFile(image_classes_filename_));
1079 }
1080 if (image_classes_.get() == nullptr) {
1081 LOG(ERROR) << "Failed to create list of image classes from '" << image_classes_filename_ <<
1082 "': " << error_msg;
1083 return false;
1084 }
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001085 } else if (IsBootImage()) {
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001086 image_classes_.reset(new std::unordered_set<std::string>);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001087 }
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001088 // If --compiled-classes was specified, calculate the full list of classes to compile in the
1089 // image.
1090 if (compiled_classes_filename_ != nullptr) {
1091 std::string error_msg;
1092 if (compiled_classes_zip_filename_ != nullptr) {
1093 compiled_classes_.reset(ReadImageClassesFromZip(compiled_classes_zip_filename_,
1094 compiled_classes_filename_,
1095 &error_msg));
1096 } else {
1097 compiled_classes_.reset(ReadImageClassesFromFile(compiled_classes_filename_));
1098 }
1099 if (compiled_classes_.get() == nullptr) {
1100 LOG(ERROR) << "Failed to create list of compiled classes from '"
1101 << compiled_classes_filename_ << "': " << error_msg;
1102 return false;
1103 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001104 } else {
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001105 compiled_classes_.reset(nullptr); // By default compile everything.
1106 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001107 // If --compiled-methods was specified, read the methods to compile from the given file(s).
1108 if (compiled_methods_filename_ != nullptr) {
1109 std::string error_msg;
1110 if (compiled_methods_zip_filename_ != nullptr) {
1111 compiled_methods_.reset(ReadCommentedInputFromZip(compiled_methods_zip_filename_,
1112 compiled_methods_filename_,
1113 nullptr, // No post-processing.
1114 &error_msg));
1115 } else {
1116 compiled_methods_.reset(ReadCommentedInputFromFile(compiled_methods_filename_,
1117 nullptr)); // No post-processing.
1118 }
1119 if (compiled_methods_.get() == nullptr) {
1120 LOG(ERROR) << "Failed to create list of compiled methods from '"
1121 << compiled_methods_filename_ << "': " << error_msg;
1122 return false;
1123 }
1124 } else {
1125 compiled_methods_.reset(nullptr); // By default compile everything.
1126 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001127
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001128 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001129 if (boot_image_option_.empty()) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001130 dex_files_ = class_linker->GetBootClassPath();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001131 } else {
Andreas Gampec7ae55d2015-09-15 20:04:54 -07001132 TimingLogger::ScopedTiming t_dex("Opening dex files", timings_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001133 if (dex_filenames_.empty()) {
1134 ATRACE_BEGIN("Opening zip archive from file descriptor");
1135 std::string error_msg;
1136 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(zip_fd_,
1137 zip_location_.c_str(),
1138 &error_msg));
1139 if (zip_archive.get() == nullptr) {
1140 LOG(ERROR) << "Failed to open zip from file descriptor for '" << zip_location_ << "': "
1141 << error_msg;
1142 return false;
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001143 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001144 if (!DexFile::OpenFromZip(*zip_archive.get(), zip_location_, &error_msg, &opened_dex_files_)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001145 LOG(ERROR) << "Failed to open dex from file descriptor for zip file '" << zip_location_
1146 << "': " << error_msg;
1147 return false;
1148 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001149 for (auto& dex_file : opened_dex_files_) {
1150 dex_files_.push_back(dex_file.get());
1151 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001152 ATRACE_END();
1153 } else {
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001154 size_t failure_count = OpenDexFiles(dex_filenames_, dex_locations_, &opened_dex_files_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001155 if (failure_count > 0) {
1156 LOG(ERROR) << "Failed to open some dex files: " << failure_count;
1157 return false;
1158 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001159 for (auto& dex_file : opened_dex_files_) {
1160 dex_files_.push_back(dex_file.get());
1161 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001162 }
1163
1164 constexpr bool kSaveDexInput = false;
1165 if (kSaveDexInput) {
1166 for (size_t i = 0; i < dex_files_.size(); ++i) {
1167 const DexFile* dex_file = dex_files_[i];
Brian Carlstrom95b033b2014-12-03 22:29:37 -08001168 std::string tmp_file_name(StringPrintf("/data/local/tmp/dex2oat.%d.%zd.dex",
1169 getpid(), i));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001170 std::unique_ptr<File> tmp_file(OS::CreateEmptyFile(tmp_file_name.c_str()));
1171 if (tmp_file.get() == nullptr) {
1172 PLOG(ERROR) << "Failed to open file " << tmp_file_name
1173 << ". Try: adb shell chmod 777 /data/local/tmp";
1174 continue;
1175 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001176 // This is just dumping files for debugging. Ignore errors, and leave remnants.
1177 UNUSED(tmp_file->WriteFully(dex_file->Begin(), dex_file->Size()));
1178 UNUSED(tmp_file->Flush());
1179 UNUSED(tmp_file->Close());
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001180 LOG(INFO) << "Wrote input to " << tmp_file_name;
1181 }
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001182 }
1183 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001184 // Ensure opened dex files are writable for dex-to-dex transformations. Also ensure that
1185 // the dex caches stay live since we don't want class unloading to occur during compilation.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001186 for (const auto& dex_file : dex_files_) {
1187 if (!dex_file->EnableWrite()) {
1188 PLOG(ERROR) << "Failed to make .dex file writeable '" << dex_file->GetLocation() << "'\n";
Andreas Gampe7ba64962014-10-23 11:37:40 -07001189 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001190 ScopedObjectAccess soa(self);
1191 dex_caches_.push_back(soa.AddLocalReference<jobject>(
Mathieu Chartierd57d4542015-10-14 10:55:30 -07001192 class_linker->RegisterDexFile(*dex_file, Runtime::Current()->GetLinearAlloc())));
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001193 dex_file->CreateTypeLookupTable();
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001194 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001195
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001196 // If we use a swap file, ensure we are above the threshold to make it necessary.
1197 if (swap_fd_ != -1) {
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001198 if (!UseSwap(IsBootImage(), dex_files_)) {
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001199 close(swap_fd_);
1200 swap_fd_ = -1;
Andreas Gampef99bcd22015-04-24 16:22:18 -07001201 VLOG(compiler) << "Decided to run without swap.";
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001202 } else {
Andreas Gampef99bcd22015-04-24 16:22:18 -07001203 LOG(INFO) << "Large app, accepted running with swap.";
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001204 }
1205 }
1206 // Note that dex2oat won't close the swap_fd_. The compiler driver's swap space will do that.
1207
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001208 /*
1209 * If we're not in interpret-only or verify-none mode, go ahead and compile small applications.
1210 * Don't bother to check if we're doing the image.
1211 */
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001212 if (!IsBootImage() &&
Brian Carlstrom95b033b2014-12-03 22:29:37 -08001213 compiler_options_->IsCompilationEnabled() &&
1214 compiler_kind_ == Compiler::kQuick) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001215 size_t num_methods = 0;
1216 for (size_t i = 0; i != dex_files_.size(); ++i) {
1217 const DexFile* dex_file = dex_files_[i];
1218 CHECK(dex_file != nullptr);
1219 num_methods += dex_file->NumMethodIds();
1220 }
1221 if (num_methods <= compiler_options_->GetNumDexMethodsThreshold()) {
1222 compiler_options_->SetCompilerFilter(CompilerOptions::kSpeed);
1223 VLOG(compiler) << "Below method threshold, compiling anyways";
1224 }
1225 }
1226
1227 return true;
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001228 }
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001229
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001230 // Create and invoke the compiler driver. This will compile all the dex files.
1231 void Compile() {
1232 TimingLogger::ScopedTiming t("dex2oat Compile", timings_);
1233 compiler_phases_timings_.reset(new CumulativeLogger("compilation times"));
Vladimir Markof4da6752014-08-01 19:04:18 +01001234
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001235 // Handle and ClassLoader creation needs to come after Runtime::Create
1236 jobject class_loader = nullptr;
Mathieu Chartierd37d3642015-11-19 16:05:58 -08001237 jobject class_path_class_loader = nullptr;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001238 Thread* self = Thread::Current();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001239
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001240 if (!boot_image_option_.empty()) {
1241 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001242 OpenClassPathFiles(runtime_->GetClassPathString(), dex_files_, &class_path_files_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001243 ScopedObjectAccess soa(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07001244
1245 // Classpath: first the class-path given.
1246 std::vector<const DexFile*> class_path_files;
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001247 for (auto& class_path_file : class_path_files_) {
1248 class_path_files.push_back(class_path_file.get());
1249 }
Andreas Gampe7848da42015-04-09 11:15:04 -07001250
1251 // Store the classpath we have right now.
1252 key_value_store_->Put(OatHeader::kClassPathKey,
1253 OatFile::EncodeDexFileDependencies(class_path_files));
1254
Mathieu Chartierd37d3642015-11-19 16:05:58 -08001255 class_path_class_loader = class_linker->CreatePathClassLoader(self,
1256 class_path_files,
1257 nullptr);
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001258
Mathieu Chartierd37d3642015-11-19 16:05:58 -08001259 // Class path loader as parent so that we'll resolve there first.
1260 class_loader = class_linker->CreatePathClassLoader(self, dex_files_, class_path_class_loader);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001261 }
1262
Vladimir Marko307dac92015-10-20 11:20:09 +01001263 driver_.reset(new CompilerDriver(compiler_options_.get(),
1264 verification_results_.get(),
1265 &method_inliner_map_,
1266 compiler_kind_,
1267 instruction_set_,
1268 instruction_set_features_.get(),
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001269 IsBootImage(),
Vladimir Marko307dac92015-10-20 11:20:09 +01001270 image_classes_.release(),
1271 compiled_classes_.release(),
1272 nullptr,
1273 thread_count_,
1274 dump_stats_,
1275 dump_passes_,
1276 dump_cfg_file_name_,
1277 dump_cfg_append_,
1278 compiler_phases_timings_.get(),
1279 swap_fd_,
1280 profile_file_));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001281
Vladimir Markod1eaf0d2015-10-29 12:18:29 +00001282 driver_->SetDexFilesForOatFile(dex_files_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001283 driver_->CompileAll(class_loader, dex_files_, timings_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001284 }
1285
Brian Carlstrom7940e442013-07-12 13:46:57 -07001286 // Notes on the interleaving of creating the image and oat file to
1287 // ensure the references between the two are correct.
1288 //
1289 // Currently we have a memory layout that looks something like this:
1290 //
1291 // +--------------+
1292 // | image |
1293 // +--------------+
1294 // | boot oat |
1295 // +--------------+
1296 // | alloc spaces |
1297 // +--------------+
1298 //
Brian Carlstrom45602482013-07-21 22:07:55 -07001299 // There are several constraints on the loading of the image and boot.oat.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001300 //
1301 // 1. The image is expected to be loaded at an absolute address and
1302 // contains Objects with absolute pointers within the image.
1303 //
1304 // 2. There are absolute pointers from Methods in the image to their
1305 // code in the oat.
1306 //
1307 // 3. There are absolute pointers from the code in the oat to Methods
1308 // in the image.
1309 //
1310 // 4. There are absolute pointers from code in the oat to other code
1311 // in the oat.
1312 //
1313 // To get this all correct, we go through several steps.
1314 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001315 // 1. We prepare offsets for all data in the oat file and calculate
1316 // the oat data size and code size. During this stage, we also set
1317 // oat code offsets in methods for use by the image writer.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001318 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001319 // 2. We prepare offsets for the objects in the image and calculate
1320 // the image size.
1321 //
1322 // 3. We create the oat file. Originally this was just our own proprietary
1323 // file but now it is contained within an ELF dynamic object (aka an .so
1324 // file). Since we know the image size and oat data size and code size we
1325 // can prepare the ELF headers and we then know the ELF memory segment
1326 // layout and we can now resolve all references. The compiler provides
1327 // LinkerPatch information in each CompiledMethod and we resolve these,
1328 // using the layout information and image object locations provided by
1329 // image writer, as we're writing the method code.
1330 //
1331 // 4. We create the image file. It needs to know where the oat file
Brian Carlstrom7940e442013-07-12 13:46:57 -07001332 // will be loaded after itself. Originally when oat file was simply
1333 // memory mapped so we could predict where its contents were based
1334 // on the file size. Now that it is an ELF file, we need to inspect
1335 // the ELF file to understand the in memory segment layout including
Vladimir Markof4da6752014-08-01 19:04:18 +01001336 // where the oat header is located within.
1337 // TODO: We could just remember this information from step 3.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001338 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001339 // 5. We fixup the ELF program headers so that dlopen will try to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001340 // load the .so at the desired location at runtime by offsetting the
1341 // Elf32_Phdr.p_vaddr values by the desired base address.
Vladimir Markof4da6752014-08-01 19:04:18 +01001342 // TODO: Do this in step 3. We already know the layout there.
1343 //
1344 // Steps 1.-3. are done by the CreateOatFile() above, steps 4.-5.
1345 // are done by the CreateImageFile() below.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001346
1347
1348 // Write out the generated code part. Calls the OatWriter and ElfBuilder. Also prepares the
1349 // ImageWriter, if necessary.
Andreas Gampe10e477d2014-11-19 12:57:42 -08001350 // Note: Flushing (and closing) the file is the caller's responsibility, except for the failure
1351 // case (when the file will be explicitly erased).
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001352 bool CreateOatFile() {
1353 CHECK(key_value_store_.get() != nullptr);
1354
1355 TimingLogger::ScopedTiming t("dex2oat Oat", timings_);
1356
1357 std::unique_ptr<OatWriter> oat_writer;
1358 {
1359 TimingLogger::ScopedTiming t2("dex2oat OatWriter", timings_);
1360 std::string image_file_location;
1361 uint32_t image_file_location_oat_checksum = 0;
1362 uintptr_t image_file_location_oat_data_begin = 0;
1363 int32_t image_patch_delta = 0;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001364
1365 if (app_image_ && image_base_ == 0) {
Mathieu Chartier073b16c2015-11-10 14:13:23 -08001366 gc::space::ImageSpace* image_space = Runtime::Current()->GetHeap()->GetBootImageSpace();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001367 image_base_ = RoundUp(
1368 reinterpret_cast<uintptr_t>(image_space->GetImageHeader().GetOatFileEnd()),
1369 kPageSize);
1370 VLOG(compiler) << "App image base=" << reinterpret_cast<void*>(image_base_);
1371 }
1372
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001373 if (IsImage()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001374 PrepareImageWriter(image_base_);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001375 }
1376
1377 if (!IsBootImage()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001378 TimingLogger::ScopedTiming t3("Loading image checksum", timings_);
Mathieu Chartier073b16c2015-11-10 14:13:23 -08001379 gc::space::ImageSpace* image_space = Runtime::Current()->GetHeap()->GetBootImageSpace();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001380 image_file_location_oat_checksum = image_space->GetImageHeader().GetOatChecksum();
1381 image_file_location_oat_data_begin =
1382 reinterpret_cast<uintptr_t>(image_space->GetImageHeader().GetOatDataBegin());
1383 image_file_location = image_space->GetImageFilename();
1384 image_patch_delta = image_space->GetImageHeader().GetPatchDelta();
1385 }
1386
1387 if (!image_file_location.empty()) {
1388 key_value_store_->Put(OatHeader::kImageLocationKey, image_file_location);
1389 }
1390
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001391 oat_writer.reset(new OatWriter(dex_files_,
1392 image_file_location_oat_checksum,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001393 image_file_location_oat_data_begin,
1394 image_patch_delta,
Vladimir Marko307dac92015-10-20 11:20:09 +01001395 driver_.get(),
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001396 image_writer_.get(),
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001397 IsBootImage(),
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001398 timings_,
1399 key_value_store_.get()));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001400 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001401
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001402 if (IsImage()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001403 // The OatWriter constructor has already updated offsets in methods and we need to
1404 // prepare method offsets in the image address space for direct method patching.
1405 TimingLogger::ScopedTiming t2("dex2oat Prepare image address space", timings_);
1406 if (!image_writer_->PrepareImageAddressSpace()) {
1407 LOG(ERROR) << "Failed to prepare image address space.";
1408 return false;
1409 }
1410 }
1411
1412 {
1413 TimingLogger::ScopedTiming t2("dex2oat Write ELF", timings_);
Vladimir Marko10c13562015-11-25 14:33:36 +00001414 std::unique_ptr<ElfWriter> elf_writer =
1415 CreateElfWriterQuick(instruction_set_, compiler_options_.get(), oat_file_.get());
1416
1417 elf_writer->Start();
1418
1419 OutputStream* rodata = elf_writer->StartRoData();
1420 if (!oat_writer->WriteRodata(rodata)) {
1421 LOG(ERROR) << "Failed to write .rodata section to the ELF file " << oat_file_->GetPath();
1422 return false;
1423 }
1424 elf_writer->EndRoData(rodata);
1425
1426 OutputStream* text = elf_writer->StartText();
1427 if (!oat_writer->WriteCode(text)) {
1428 LOG(ERROR) << "Failed to write .text section to the ELF file " << oat_file_->GetPath();
1429 return false;
1430 }
1431 elf_writer->EndText(text);
1432
1433 elf_writer->SetBssSize(oat_writer->GetBssSize());
1434
1435 elf_writer->WriteDynamicSection();
1436
1437 ArrayRef<const dwarf::MethodDebugInfo> method_infos(oat_writer->GetMethodDebugInfo());
1438 elf_writer->WriteDebugInfo(method_infos);
1439
1440 ArrayRef<const uintptr_t> patch_locations(oat_writer->GetAbsolutePatchLocations());
1441 elf_writer->WritePatchLocations(patch_locations);
1442
1443 if (!elf_writer->End()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001444 LOG(ERROR) << "Failed to write ELF file " << oat_file_->GetPath();
1445 return false;
1446 }
1447 }
1448
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001449 VLOG(compiler) << "Oat file written successfully (unstripped): " << oat_location_;
1450 return true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001451 }
1452
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001453 // If we are compiling an image, invoke the image creation routine. Else just skip.
1454 bool HandleImage() {
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001455 if (IsImage()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001456 TimingLogger::ScopedTiming t("dex2oat ImageWriter", timings_);
1457 if (!CreateImageFile()) {
1458 return false;
1459 }
1460 VLOG(compiler) << "Image written successfully: " << image_filename_;
Brian Carlstrom45602482013-07-21 22:07:55 -07001461 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001462 return true;
1463 }
1464
Andreas Gampe10e477d2014-11-19 12:57:42 -08001465 // Create a copy from unstripped to stripped.
1466 bool CopyUnstrippedToStripped() {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001467 // If we don't want to strip in place, copy from unstripped location to stripped location.
1468 // We need to strip after image creation because FixupElf needs to use .strtab.
1469 if (oat_unstripped_ != oat_stripped_) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08001470 // If the oat file is still open, flush it.
1471 if (oat_file_.get() != nullptr && oat_file_->IsOpened()) {
1472 if (!FlushCloseOatFile()) {
1473 return false;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001474 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001475 }
Andreas Gampe10e477d2014-11-19 12:57:42 -08001476
1477 TimingLogger::ScopedTiming t("dex2oat OatFile copy", timings_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001478 std::unique_ptr<File> in(OS::OpenFileForReading(oat_unstripped_.c_str()));
1479 std::unique_ptr<File> out(OS::CreateEmptyFile(oat_stripped_.c_str()));
1480 size_t buffer_size = 8192;
Dan Albert6fc59ab2014-12-11 14:09:51 -08001481 std::unique_ptr<uint8_t[]> buffer(new uint8_t[buffer_size]);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001482 while (true) {
1483 int bytes_read = TEMP_FAILURE_RETRY(read(in->Fd(), buffer.get(), buffer_size));
1484 if (bytes_read <= 0) {
1485 break;
1486 }
1487 bool write_ok = out->WriteFully(buffer.get(), bytes_read);
1488 CHECK(write_ok);
1489 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08001490 if (out->FlushCloseOrErase() != 0) {
1491 PLOG(ERROR) << "Failed to flush and close copied oat file: " << oat_stripped_;
1492 return false;
Andreas Gampe10e477d2014-11-19 12:57:42 -08001493 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001494 VLOG(compiler) << "Oat file copied successfully (stripped): " << oat_stripped_;
Nicolas Geoffrayea3fa0b2014-02-10 11:59:41 +00001495 }
Andreas Gampe10e477d2014-11-19 12:57:42 -08001496 return true;
1497 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001498
Andreas Gampe10e477d2014-11-19 12:57:42 -08001499 bool FlushOatFile() {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001500 if (oat_file_.get() != nullptr) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08001501 TimingLogger::ScopedTiming t2("dex2oat Flush ELF", timings_);
1502 if (oat_file_->Flush() != 0) {
1503 PLOG(ERROR) << "Failed to flush oat file: " << oat_location_ << " / "
1504 << oat_filename_;
1505 oat_file_->Erase();
1506 return false;
1507 }
1508 }
1509 return true;
1510 }
1511
1512 bool FlushCloseOatFile() {
1513 if (oat_file_.get() != nullptr) {
1514 std::unique_ptr<File> tmp(oat_file_.release());
1515 if (tmp->FlushCloseOrErase() != 0) {
1516 PLOG(ERROR) << "Failed to flush and close oat file: " << oat_location_ << " / "
1517 << oat_filename_;
1518 return false;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001519 }
1520 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001521 return true;
1522 }
1523
1524 void DumpTiming() {
1525 if (dump_timing_ || (dump_slow_timing_ && timings_->GetTotalNs() > MsToNs(1000))) {
1526 LOG(INFO) << Dumpable<TimingLogger>(*timings_);
1527 }
1528 if (dump_passes_) {
1529 LOG(INFO) << Dumpable<CumulativeLogger>(*driver_->GetTimingsLogger());
1530 }
1531 }
1532
1533 CompilerOptions* GetCompilerOptions() const {
1534 return compiler_options_.get();
1535 }
1536
Andreas Gampe10e477d2014-11-19 12:57:42 -08001537 bool IsImage() const {
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001538 return IsAppImage() || IsBootImage();
1539 }
1540
1541 bool IsAppImage() const {
1542 return app_image_;
1543 }
1544
1545 bool IsBootImage() const {
1546 return boot_image_;
Andreas Gampe10e477d2014-11-19 12:57:42 -08001547 }
1548
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001549 bool IsHost() const {
1550 return is_host_;
1551 }
1552
1553 private:
1554 static size_t OpenDexFiles(const std::vector<const char*>& dex_filenames,
1555 const std::vector<const char*>& dex_locations,
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001556 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001557 DCHECK(dex_files != nullptr) << "OpenDexFiles out-param is nullptr";
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001558 size_t failure_count = 0;
1559 for (size_t i = 0; i < dex_filenames.size(); i++) {
1560 const char* dex_filename = dex_filenames[i];
1561 const char* dex_location = dex_locations[i];
1562 ATRACE_BEGIN(StringPrintf("Opening dex file '%s'", dex_filenames[i]).c_str());
1563 std::string error_msg;
1564 if (!OS::FileExists(dex_filename)) {
1565 LOG(WARNING) << "Skipping non-existent dex file '" << dex_filename << "'";
1566 continue;
1567 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001568 if (!DexFile::Open(dex_filename, dex_location, &error_msg, dex_files)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001569 LOG(WARNING) << "Failed to open .dex from file '" << dex_filename << "': " << error_msg;
1570 ++failure_count;
1571 }
1572 ATRACE_END();
1573 }
1574 return failure_count;
1575 }
1576
Andreas Gampee3712d02015-04-09 14:46:31 -07001577 // Returns true if dex_files has a dex with the named location. We compare canonical locations,
1578 // so that relative and absolute paths will match. Not caching for the dex_files isn't very
1579 // efficient, but under normal circumstances the list is neither large nor is this part too
1580 // sensitive.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001581 static bool DexFilesContains(const std::vector<const DexFile*>& dex_files,
1582 const std::string& location) {
Andreas Gampee3712d02015-04-09 14:46:31 -07001583 std::string canonical_location(DexFile::GetDexCanonicalLocation(location.c_str()));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001584 for (size_t i = 0; i < dex_files.size(); ++i) {
Andreas Gampee3712d02015-04-09 14:46:31 -07001585 if (DexFile::GetDexCanonicalLocation(dex_files[i]->GetLocation().c_str()) ==
1586 canonical_location) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001587 return true;
1588 }
1589 }
1590 return false;
1591 }
1592
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001593 // Appends to opened_dex_files any elements of class_path that dex_files
1594 // doesn't already contain. This will open those dex files as necessary.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001595 static void OpenClassPathFiles(const std::string& class_path,
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001596 std::vector<const DexFile*> dex_files,
1597 std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001598 DCHECK(opened_dex_files != nullptr) << "OpenClassPathFiles out-param is nullptr";
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001599 std::vector<std::string> parsed;
1600 Split(class_path, ':', &parsed);
1601 // Take Locks::mutator_lock_ so that lock ordering on the ClassLinker::dex_lock_ is maintained.
1602 ScopedObjectAccess soa(Thread::Current());
1603 for (size_t i = 0; i < parsed.size(); ++i) {
1604 if (DexFilesContains(dex_files, parsed[i])) {
1605 continue;
1606 }
1607 std::string error_msg;
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001608 if (!DexFile::Open(parsed[i].c_str(), parsed[i].c_str(), &error_msg, opened_dex_files)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001609 LOG(WARNING) << "Failed to open dex file '" << parsed[i] << "': " << error_msg;
1610 }
1611 }
1612 }
1613
1614 // Create a runtime necessary for compilation.
1615 bool CreateRuntime(const RuntimeOptions& runtime_options)
1616 SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_) {
1617 if (!Runtime::Create(runtime_options, false)) {
1618 LOG(ERROR) << "Failed to create runtime";
1619 return false;
1620 }
Vladimir Marko307dac92015-10-20 11:20:09 +01001621 runtime_.reset(Runtime::Current());
1622 runtime_->SetInstructionSet(instruction_set_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001623 for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
1624 Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i);
Vladimir Marko307dac92015-10-20 11:20:09 +01001625 if (!runtime_->HasCalleeSaveMethod(type)) {
1626 runtime_->SetCalleeSaveMethod(runtime_->CreateCalleeSaveMethod(), type);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001627 }
1628 }
Vladimir Marko307dac92015-10-20 11:20:09 +01001629 runtime_->GetClassLinker()->FixupDexCaches(runtime_->GetResolutionMethod());
Andreas Gampe2969bcd2015-03-09 12:57:41 -07001630
1631 // Initialize maps for unstarted runtime. This needs to be here, as running clinits needs this
1632 // set up.
Andreas Gampe799681b2015-05-15 19:24:12 -07001633 interpreter::UnstartedRuntime::Initialize();
Andreas Gampe2969bcd2015-03-09 12:57:41 -07001634
Vladimir Marko307dac92015-10-20 11:20:09 +01001635 runtime_->GetClassLinker()->RunRootClinits();
Andreas Gampe2969bcd2015-03-09 12:57:41 -07001636
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001637 return true;
1638 }
1639
1640 void PrepareImageWriter(uintptr_t image_base) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001641 DCHECK(IsImage());
1642 image_writer_.reset(new ImageWriter(*driver_,
1643 image_base,
1644 compiler_options_->GetCompilePic(),
1645 IsAppImage()));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001646 }
1647
1648 // Let the ImageWriter write the image file. If we do not compile PIC, also fix up the oat file.
1649 bool CreateImageFile()
Mathieu Chartier90443472015-07-16 20:32:27 -07001650 REQUIRES(!Locks::mutator_lock_) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001651 CHECK(image_writer_ != nullptr);
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001652 if (!image_writer_->Write(app_image_fd_,
1653 IsBootImage() ? image_filename_ : app_image_file_name_,
1654 oat_unstripped_,
1655 oat_location_)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001656 LOG(ERROR) << "Failed to create image file " << image_filename_;
1657 return false;
1658 }
1659 uintptr_t oat_data_begin = image_writer_->GetOatDataBegin();
1660
1661 // Destroy ImageWriter before doing FixupElf.
1662 image_writer_.reset();
1663
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001664 // Do not fix up the ELF file if we are --compile-pic or compiing the app image
1665 if (!compiler_options_->GetCompilePic() && IsBootImage()) {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001666 std::unique_ptr<File> oat_file(OS::OpenFileReadWrite(oat_unstripped_.c_str()));
1667 if (oat_file.get() == nullptr) {
1668 PLOG(ERROR) << "Failed to open ELF file: " << oat_unstripped_;
1669 return false;
1670 }
1671
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001672 if (!ElfWriter::Fixup(oat_file.get(), oat_data_begin)) {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001673 oat_file->Erase();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001674 LOG(ERROR) << "Failed to fixup ELF file " << oat_file->GetPath();
1675 return false;
1676 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001677
1678 if (oat_file->FlushCloseOrErase()) {
1679 PLOG(ERROR) << "Failed to flush and close fixed ELF file " << oat_file->GetPath();
1680 return false;
1681 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001682 }
1683
1684 return true;
1685 }
1686
1687 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001688 static std::unordered_set<std::string>* ReadImageClassesFromFile(
1689 const char* image_classes_filename) {
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001690 std::function<std::string(const char*)> process = DotToDescriptor;
1691 return ReadCommentedInputFromFile(image_classes_filename, &process);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001692 }
1693
1694 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001695 static std::unordered_set<std::string>* ReadImageClassesFromZip(
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001696 const char* zip_filename,
1697 const char* image_classes_filename,
1698 std::string* error_msg) {
1699 std::function<std::string(const char*)> process = DotToDescriptor;
1700 return ReadCommentedInputFromZip(zip_filename, image_classes_filename, &process, error_msg);
1701 }
1702
1703 // Read lines from the given file, dropping comments and empty lines. Post-process each line with
1704 // the given function.
1705 static std::unordered_set<std::string>* ReadCommentedInputFromFile(
1706 const char* input_filename, std::function<std::string(const char*)>* process) {
1707 std::unique_ptr<std::ifstream> input_file(new std::ifstream(input_filename, std::ifstream::in));
1708 if (input_file.get() == nullptr) {
1709 LOG(ERROR) << "Failed to open input file " << input_filename;
1710 return nullptr;
1711 }
1712 std::unique_ptr<std::unordered_set<std::string>> result(
1713 ReadCommentedInputStream(*input_file, process));
1714 input_file->close();
1715 return result.release();
1716 }
1717
1718 // Read lines from the given file from the given zip file, dropping comments and empty lines.
1719 // Post-process each line with the given function.
1720 static std::unordered_set<std::string>* ReadCommentedInputFromZip(
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001721 const char* zip_filename,
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001722 const char* input_filename,
1723 std::function<std::string(const char*)>* process,
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001724 std::string* error_msg) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001725 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::Open(zip_filename, error_msg));
1726 if (zip_archive.get() == nullptr) {
1727 return nullptr;
1728 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001729 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(input_filename, error_msg));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001730 if (zip_entry.get() == nullptr) {
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001731 *error_msg = StringPrintf("Failed to find '%s' within '%s': %s", input_filename,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001732 zip_filename, error_msg->c_str());
1733 return nullptr;
1734 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001735 std::unique_ptr<MemMap> input_file(zip_entry->ExtractToMemMap(zip_filename,
1736 input_filename,
1737 error_msg));
1738 if (input_file.get() == nullptr) {
1739 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", input_filename,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001740 zip_filename, error_msg->c_str());
1741 return nullptr;
1742 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001743 const std::string input_string(reinterpret_cast<char*>(input_file->Begin()),
1744 input_file->Size());
1745 std::istringstream input_stream(input_string);
1746 return ReadCommentedInputStream(input_stream, process);
1747 }
1748
1749 // Read lines from the given stream, dropping comments and empty lines. Post-process each line
1750 // with the given function.
1751 static std::unordered_set<std::string>* ReadCommentedInputStream(
1752 std::istream& in_stream,
1753 std::function<std::string(const char*)>* process) {
1754 std::unique_ptr<std::unordered_set<std::string>> image_classes(
1755 new std::unordered_set<std::string>);
1756 while (in_stream.good()) {
1757 std::string dot;
1758 std::getline(in_stream, dot);
1759 if (StartsWith(dot, "#") || dot.empty()) {
1760 continue;
1761 }
1762 if (process != nullptr) {
1763 std::string descriptor((*process)(dot.c_str()));
1764 image_classes->insert(descriptor);
1765 } else {
1766 image_classes->insert(dot);
1767 }
1768 }
1769 return image_classes.release();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001770 }
1771
Mathieu Chartier49285c52014-12-02 15:43:48 -08001772 void LogCompletionTime() {
Andreas Gampe1d00add2015-02-27 19:35:46 -08001773 // Note: when creation of a runtime fails, e.g., when trying to compile an app but when there
1774 // is no image, there won't be a Runtime::Current().
Brian Carlstroma11a34c2015-03-06 08:44:45 -08001775 // Note: driver creation can fail when loading an invalid dex file.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001776 LOG(INFO) << "dex2oat took " << PrettyDuration(NanoTime() - start_ns_)
Mathieu Chartierab972ef2014-12-03 17:38:22 -08001777 << " (threads: " << thread_count_ << ") "
Andreas Gampe3f30e122015-09-17 14:03:21 -07001778 << ((Runtime::Current() != nullptr && driver_ != nullptr) ?
Andreas Gampe1d00add2015-02-27 19:35:46 -08001779 driver_->GetMemoryUsageString(kIsDebugBuild || VLOG_IS_ON(compiler)) :
1780 "");
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001781 }
1782
1783 std::unique_ptr<CompilerOptions> compiler_options_;
1784 Compiler::Kind compiler_kind_;
1785
1786 InstructionSet instruction_set_;
1787 std::unique_ptr<const InstructionSetFeatures> instruction_set_features_;
1788
1789 std::unique_ptr<SafeMap<std::string, std::string> > key_value_store_;
1790
Vladimir Marko307dac92015-10-20 11:20:09 +01001791 std::unique_ptr<VerificationResults> verification_results_;
Andreas Gampe3f30e122015-09-17 14:03:21 -07001792
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001793 DexFileToMethodInlinerMap method_inliner_map_;
1794 std::unique_ptr<QuickCompilerCallbacks> callbacks_;
1795
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001796 // Ownership for the class path files.
1797 std::vector<std::unique_ptr<const DexFile>> class_path_files_;
1798
Vladimir Marko307dac92015-10-20 11:20:09 +01001799 std::unique_ptr<Runtime> runtime_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001800
1801 size_t thread_count_;
1802 uint64_t start_ns_;
1803 std::unique_ptr<WatchDog> watchdog_;
1804 std::unique_ptr<File> oat_file_;
1805 std::string oat_stripped_;
1806 std::string oat_unstripped_;
1807 std::string oat_location_;
1808 std::string oat_filename_;
1809 int oat_fd_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001810 std::vector<const char*> dex_filenames_;
1811 std::vector<const char*> dex_locations_;
1812 int zip_fd_;
1813 std::string zip_location_;
1814 std::string boot_image_option_;
1815 std::vector<const char*> runtime_args_;
1816 std::string image_filename_;
1817 uintptr_t image_base_;
1818 const char* image_classes_zip_filename_;
1819 const char* image_classes_filename_;
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001820 const char* compiled_classes_zip_filename_;
1821 const char* compiled_classes_filename_;
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001822 const char* compiled_methods_zip_filename_;
1823 const char* compiled_methods_filename_;
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001824 std::unique_ptr<std::unordered_set<std::string>> image_classes_;
1825 std::unique_ptr<std::unordered_set<std::string>> compiled_classes_;
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001826 std::unique_ptr<std::unordered_set<std::string>> compiled_methods_;
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001827 bool app_image_;
1828 bool boot_image_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001829 bool is_host_;
1830 std::string android_root_;
1831 std::vector<const DexFile*> dex_files_;
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001832 std::vector<jobject> dex_caches_;
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001833 std::vector<std::unique_ptr<const DexFile>> opened_dex_files_;
Andreas Gampe3f30e122015-09-17 14:03:21 -07001834
Vladimir Marko307dac92015-10-20 11:20:09 +01001835 std::unique_ptr<ImageWriter> image_writer_;
1836 std::unique_ptr<CompilerDriver> driver_;
Andreas Gampe3f30e122015-09-17 14:03:21 -07001837
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001838 std::vector<std::string> verbose_methods_;
1839 bool dump_stats_;
1840 bool dump_passes_;
1841 bool dump_timing_;
1842 bool dump_slow_timing_;
David Brazdil866c0312015-01-13 21:21:31 +00001843 std::string dump_cfg_file_name_;
Calin Juravle87000a92015-08-24 15:34:44 +01001844 bool dump_cfg_append_;
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001845 std::string swap_file_name_;
1846 int swap_fd_;
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001847 std::string app_image_file_name_;
1848 int app_image_fd_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001849 std::string profile_file_; // Profile file to use
1850 TimingLogger* timings_;
1851 std::unique_ptr<CumulativeLogger> compiler_phases_timings_;
1852
1853 DISALLOW_IMPLICIT_CONSTRUCTORS(Dex2Oat);
1854};
1855
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001856static void b13564922() {
1857#if defined(__linux__) && defined(__arm__)
1858 int major, minor;
1859 struct utsname uts;
1860 if (uname(&uts) != -1 &&
1861 sscanf(uts.release, "%d.%d", &major, &minor) == 2 &&
1862 ((major < 3) || ((major == 3) && (minor < 4)))) {
1863 // Kernels before 3.4 don't handle the ASLR well and we can run out of address
1864 // space (http://b/13564922). Work around the issue by inhibiting further mmap() randomization.
1865 int old_personality = personality(0xffffffff);
1866 if ((old_personality & ADDR_NO_RANDOMIZE) == 0) {
1867 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
1868 if (new_personality == -1) {
1869 LOG(WARNING) << "personality(. | ADDR_NO_RANDOMIZE) failed.";
1870 }
1871 }
1872 }
1873#endif
1874}
1875
Andreas Gampe10e477d2014-11-19 12:57:42 -08001876static int CompileImage(Dex2Oat& dex2oat) {
1877 dex2oat.Compile();
1878
1879 // Create the boot.oat.
1880 if (!dex2oat.CreateOatFile()) {
Andreas Gampea650e702014-12-03 14:28:02 -08001881 dex2oat.EraseOatFile();
Andreas Gampe10e477d2014-11-19 12:57:42 -08001882 return EXIT_FAILURE;
1883 }
1884
1885 // Flush and close the boot.oat. We always expect the output file by name, and it will be
1886 // re-opened from the unstripped name.
1887 if (!dex2oat.FlushCloseOatFile()) {
1888 return EXIT_FAILURE;
1889 }
1890
1891 // Creates the boot.art and patches the boot.oat.
1892 if (!dex2oat.HandleImage()) {
1893 return EXIT_FAILURE;
1894 }
1895
1896 // When given --host, finish early without stripping.
1897 if (dex2oat.IsHost()) {
1898 dex2oat.DumpTiming();
1899 return EXIT_SUCCESS;
1900 }
1901
1902 // Copy unstripped to stripped location, if necessary.
1903 if (!dex2oat.CopyUnstrippedToStripped()) {
1904 return EXIT_FAILURE;
1905 }
1906
Andreas Gampe10e477d2014-11-19 12:57:42 -08001907 // FlushClose again, as stripping might have re-opened the oat file.
1908 if (!dex2oat.FlushCloseOatFile()) {
1909 return EXIT_FAILURE;
1910 }
1911
1912 dex2oat.DumpTiming();
1913 return EXIT_SUCCESS;
1914}
1915
1916static int CompileApp(Dex2Oat& dex2oat) {
1917 dex2oat.Compile();
1918
1919 // Create the app oat.
1920 if (!dex2oat.CreateOatFile()) {
Andreas Gampea650e702014-12-03 14:28:02 -08001921 dex2oat.EraseOatFile();
Andreas Gampe10e477d2014-11-19 12:57:42 -08001922 return EXIT_FAILURE;
1923 }
1924
1925 // Do not close the oat file here. We might haven gotten the output file by file descriptor,
1926 // which we would lose.
1927 if (!dex2oat.FlushOatFile()) {
1928 return EXIT_FAILURE;
1929 }
1930
1931 // When given --host, finish early without stripping.
1932 if (dex2oat.IsHost()) {
1933 if (!dex2oat.FlushCloseOatFile()) {
1934 return EXIT_FAILURE;
1935 }
1936
1937 dex2oat.DumpTiming();
1938 return EXIT_SUCCESS;
1939 }
1940
1941 // Copy unstripped to stripped location, if necessary. This will implicitly flush & close the
1942 // unstripped version. If this is given, we expect to be able to open writable files by name.
1943 if (!dex2oat.CopyUnstrippedToStripped()) {
1944 return EXIT_FAILURE;
1945 }
1946
Andreas Gampe10e477d2014-11-19 12:57:42 -08001947 // Flush and close the file.
1948 if (!dex2oat.FlushCloseOatFile()) {
1949 return EXIT_FAILURE;
1950 }
1951
1952 dex2oat.DumpTiming();
1953 return EXIT_SUCCESS;
1954}
1955
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001956static int dex2oat(int argc, char** argv) {
1957 b13564922();
1958
1959 TimingLogger timings("compiler", false, false);
1960
1961 Dex2Oat dex2oat(&timings);
1962
1963 // Parse arguments. Argument mistakes will lead to exit(EXIT_FAILURE) in UsageError.
1964 dex2oat.ParseArgs(argc, argv);
1965
1966 // Check early that the result of compilation can be written
1967 if (!dex2oat.OpenFile()) {
1968 return EXIT_FAILURE;
1969 }
1970
Andreas Gampe046c7062015-05-18 23:22:54 -07001971 // Print the complete line when any of the following is true:
1972 // 1) Debug build
1973 // 2) Compiling an image
1974 // 3) Compiling with --host
1975 // 4) Compiling on the host (not a target build)
1976 // Otherwise, print a stripped command line.
Mathieu Chartiera90c7722015-10-29 15:41:36 -07001977 if (kIsDebugBuild || dex2oat.IsBootImage() || dex2oat.IsHost() || !kIsTargetBuild) {
Andreas Gampe046c7062015-05-18 23:22:54 -07001978 LOG(INFO) << CommandLine();
1979 } else {
1980 LOG(INFO) << StrippedCommandLine();
1981 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001982
1983 if (!dex2oat.Setup()) {
Andreas Gampea650e702014-12-03 14:28:02 -08001984 dex2oat.EraseOatFile();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001985 return EXIT_FAILURE;
1986 }
1987
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001988 bool result;
Andreas Gampe10e477d2014-11-19 12:57:42 -08001989 if (dex2oat.IsImage()) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001990 result = CompileImage(dex2oat);
Andreas Gampe10e477d2014-11-19 12:57:42 -08001991 } else {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001992 result = CompileApp(dex2oat);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001993 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001994
1995 dex2oat.Shutdown();
1996 return result;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001997}
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001998} // namespace art
Brian Carlstrom7940e442013-07-12 13:46:57 -07001999
2000int main(int argc, char** argv) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002001 int result = art::dex2oat(argc, argv);
2002 // Everything was done, do an explicit exit here to avoid running Runtime destructors that take
2003 // time (bug 10645725) unless we're a debug build or running on valgrind. Note: The Dex2Oat class
2004 // should not destruct the runtime in this case.
Evgenii Stepanov1e133742015-05-20 12:30:59 -07002005 if (!art::kIsDebugBuild && (RUNNING_ON_MEMORY_TOOL == 0)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002006 exit(result);
2007 }
2008 return result;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002009}