blob: 384b8794c1ea43a48b6c3897c32d95aa2a3b9cbc [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"
Andreas Gampe88ec7f42014-11-05 10:18:32 -080058#include "elf_file.h"
Tong Shen62d1ca32014-09-03 17:24:56 -070059#include "elf_writer.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070060#include "gc/space/image_space.h"
61#include "gc/space/space-inl.h"
62#include "image_writer.h"
Andreas Gampe2969bcd2015-03-09 12:57:41 -070063#include "interpreter/unstarted_runtime.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070064#include "leb128.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070065#include "mirror/class-inl.h"
66#include "mirror/class_loader.h"
67#include "mirror/object-inl.h"
68#include "mirror/object_array-inl.h"
69#include "oat_writer.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070070#include "os.h"
71#include "runtime.h"
72#include "ScopedLocalRef.h"
73#include "scoped_thread_state_change.h"
Alex Light53cb16b2014-06-12 11:26:29 -070074#include "utils.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070075#include "vector_output_stream.h"
76#include "well_known_classes.h"
77#include "zip_archive.h"
78
79namespace art {
80
Brian Carlstrom6449c622014-02-10 23:48:36 -080081static int original_argc;
82static char** original_argv;
83
84static std::string CommandLine() {
85 std::vector<std::string> command;
86 for (int i = 0; i < original_argc; ++i) {
87 command.push_back(original_argv[i]);
88 }
89 return Join(command, ' ');
90}
91
Andreas Gampe046c7062015-05-18 23:22:54 -070092// A stripped version. Remove some less essential parameters. If we see a "--zip-fd=" parameter, be
93// even more aggressive. There won't be much reasonable data here for us in that case anyways (the
94// locations are all staged).
95static std::string StrippedCommandLine() {
96 std::vector<std::string> command;
97
98 // Do a pre-pass to look for zip-fd.
99 bool saw_zip_fd = false;
100 for (int i = 0; i < original_argc; ++i) {
101 if (StartsWith(original_argv[i], "--zip-fd=")) {
102 saw_zip_fd = true;
103 break;
104 }
105 }
106
107 // Now filter out things.
108 for (int i = 0; i < original_argc; ++i) {
109 // All runtime-arg parameters are dropped.
110 if (strcmp(original_argv[i], "--runtime-arg") == 0) {
111 i++; // Drop the next part, too.
112 continue;
113 }
114
115 // Any instruction-setXXX is dropped.
116 if (StartsWith(original_argv[i], "--instruction-set")) {
117 continue;
118 }
119
120 // The boot image is dropped.
121 if (StartsWith(original_argv[i], "--boot-image=")) {
122 continue;
123 }
124
125 // This should leave any dex-file and oat-file options, describing what we compiled.
126
127 // However, we prefer to drop this when we saw --zip-fd.
128 if (saw_zip_fd) {
129 // Drop anything --zip-X, --dex-X, --oat-X, --swap-X.
130 if (StartsWith(original_argv[i], "--zip-") ||
131 StartsWith(original_argv[i], "--dex-") ||
132 StartsWith(original_argv[i], "--oat-") ||
133 StartsWith(original_argv[i], "--swap-")) {
134 continue;
135 }
136 }
137
138 command.push_back(original_argv[i]);
139 }
140
141 // Construct the final output.
142 if (command.size() <= 1U) {
143 // It seems only "/system/bin/dex2oat" is left, or not even that. Use a pretty line.
144 return "Starting dex2oat.";
145 }
146 return Join(command, ' ');
147}
148
Brian Carlstrom7940e442013-07-12 13:46:57 -0700149static void UsageErrorV(const char* fmt, va_list ap) {
150 std::string error;
151 StringAppendV(&error, fmt, ap);
152 LOG(ERROR) << error;
153}
154
155static void UsageError(const char* fmt, ...) {
156 va_list ap;
157 va_start(ap, fmt);
158 UsageErrorV(fmt, ap);
159 va_end(ap);
160}
161
Andreas Gampe794ad762015-02-23 08:12:24 -0800162NO_RETURN static void Usage(const char* fmt, ...) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700163 va_list ap;
164 va_start(ap, fmt);
165 UsageErrorV(fmt, ap);
166 va_end(ap);
167
Brian Carlstrom6449c622014-02-10 23:48:36 -0800168 UsageError("Command: %s", CommandLine().c_str());
169
Brian Carlstrom7940e442013-07-12 13:46:57 -0700170 UsageError("Usage: dex2oat [options]...");
171 UsageError("");
Jean-Philippe Halimi3d329d72015-03-23 14:09:48 +0100172 UsageError(" -j<number>: specifies the number of threads used for compilation.");
173 UsageError(" Default is the number of detected hardware threads available on the");
174 UsageError(" host system.");
175 UsageError(" Example: -j12");
176 UsageError("");
Richard Uhlere934df22015-03-17 11:26:16 -0700177 UsageError(" --dex-file=<dex-file>: specifies a .dex, .jar, or .apk file to compile.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700178 UsageError(" Example: --dex-file=/system/framework/core.jar");
179 UsageError("");
Richard Uhlere934df22015-03-17 11:26:16 -0700180 UsageError(" --dex-location=<dex-location>: specifies an alternative dex location to");
181 UsageError(" encode in the oat file for the corresponding --dex-file argument.");
182 UsageError(" Example: --dex-file=/home/build/out/system/framework/core.jar");
183 UsageError(" --dex-location=/system/framework/core.jar");
184 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700185 UsageError(" --zip-fd=<file-descriptor>: specifies a file descriptor of a zip file");
186 UsageError(" containing a classes.dex file to compile.");
187 UsageError(" Example: --zip-fd=5");
188 UsageError("");
Brian Carlstrom45602482013-07-21 22:07:55 -0700189 UsageError(" --zip-location=<zip-location>: specifies a symbolic name for the file");
190 UsageError(" corresponding to the file descriptor specified by --zip-fd.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700191 UsageError(" Example: --zip-location=/system/app/Calculator.apk");
192 UsageError("");
193 UsageError(" --oat-file=<file.oat>: specifies the oat output destination via a filename.");
194 UsageError(" Example: --oat-file=/system/framework/boot.oat");
195 UsageError("");
196 UsageError(" --oat-fd=<number>: specifies the oat output destination via a file descriptor.");
Wonil Kim9cb554a2014-04-28 11:26:55 +0900197 UsageError(" Example: --oat-fd=6");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700198 UsageError("");
199 UsageError(" --oat-location=<oat-name>: specifies a symbolic name for the file corresponding");
200 UsageError(" to the file descriptor specified by --oat-fd.");
201 UsageError(" Example: --oat-location=/data/dalvik-cache/system@app@Calculator.apk.oat");
202 UsageError("");
203 UsageError(" --oat-symbols=<file.oat>: specifies the oat output destination with full symbols.");
204 UsageError(" Example: --oat-symbols=/symbols/system/framework/boot.oat");
205 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700206 UsageError(" --image=<file.art>: specifies the output image filename.");
207 UsageError(" Example: --image=/system/framework/boot.art");
208 UsageError("");
209 UsageError(" --image-classes=<classname-file>: specifies classes to include in an image.");
210 UsageError(" Example: --image=frameworks/base/preloaded-classes");
211 UsageError("");
212 UsageError(" --base=<hex-address>: specifies the base address when creating a boot image.");
213 UsageError(" Example: --base=0x50000000");
214 UsageError("");
215 UsageError(" --boot-image=<file.art>: provide the image file for the boot class path.");
216 UsageError(" Example: --boot-image=/system/framework/boot.art");
Nicolas Geoffray9583fbc2014-02-28 15:21:07 +0000217 UsageError(" Default: $ANDROID_ROOT/system/framework/boot.art");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700218 UsageError("");
219 UsageError(" --android-root=<path>: used to locate libraries for portable linking.");
220 UsageError(" Example: --android-root=out/host/linux-x86");
221 UsageError(" Default: $ANDROID_ROOT");
222 UsageError("");
Andreas Gampe57b34292015-01-14 15:45:59 -0800223 UsageError(" --instruction-set=(arm|arm64|mips|mips64|x86|x86_64): compile for a particular");
Alex Light53cb16b2014-06-12 11:26:29 -0700224 UsageError(" instruction set.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700225 UsageError(" Example: --instruction-set=x86");
226 UsageError(" Default: arm");
227 UsageError("");
Dave Allison70202782013-10-22 17:52:19 -0700228 UsageError(" --instruction-set-features=...,: Specify instruction set features");
229 UsageError(" Example: --instruction-set-features=div");
230 UsageError(" Default: default");
231 UsageError("");
Igor Murashkin46774762014-10-22 11:37:02 -0700232 UsageError(" --compile-pic: Force indirect use of code, methods, and classes");
233 UsageError(" Default: disabled");
234 UsageError("");
Elliott Hughes956af0f2014-12-11 14:34:28 -0800235 UsageError(" --compiler-backend=(Quick|Optimizing): select compiler backend");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700236 UsageError(" set.");
Elliott Hughes956af0f2014-12-11 14:34:28 -0800237 UsageError(" Example: --compiler-backend=Optimizing");
Nicolas Geoffray409e8092015-10-01 10:32:19 +0100238 UsageError(" Default: Optimizing");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700239 UsageError("");
Nicolas Geoffray88157ef2014-09-12 10:29:53 +0100240 UsageError(" --compiler-filter="
241 "(verify-none"
242 "|interpret-only"
243 "|space"
244 "|balanced"
245 "|speed"
246 "|everything"
247 "|time):");
Jeff Hao4a200f52014-04-01 14:58:49 -0700248 UsageError(" select compiler filter.");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800249 UsageError(" Example: --compiler-filter=everything");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800250 UsageError(" Default: speed");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800251 UsageError("");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800252 UsageError(" --huge-method-max=<method-instruction-count>: threshold size for a huge");
253 UsageError(" method for compiler filter tuning.");
254 UsageError(" Example: --huge-method-max=%d", CompilerOptions::kDefaultHugeMethodThreshold);
255 UsageError(" Default: %d", CompilerOptions::kDefaultHugeMethodThreshold);
256 UsageError("");
257 UsageError(" --large-method-max=<method-instruction-count>: threshold size for a large");
258 UsageError(" method for compiler filter tuning.");
259 UsageError(" Example: --large-method-max=%d", CompilerOptions::kDefaultLargeMethodThreshold);
260 UsageError(" Default: %d", CompilerOptions::kDefaultLargeMethodThreshold);
261 UsageError("");
262 UsageError(" --small-method-max=<method-instruction-count>: threshold size for a small");
263 UsageError(" method for compiler filter tuning.");
264 UsageError(" Example: --small-method-max=%d", CompilerOptions::kDefaultSmallMethodThreshold);
265 UsageError(" Default: %d", CompilerOptions::kDefaultSmallMethodThreshold);
266 UsageError("");
267 UsageError(" --tiny-method-max=<method-instruction-count>: threshold size for a tiny");
268 UsageError(" method for compiler filter tuning.");
269 UsageError(" Example: --tiny-method-max=%d", CompilerOptions::kDefaultTinyMethodThreshold);
270 UsageError(" Default: %d", CompilerOptions::kDefaultTinyMethodThreshold);
271 UsageError("");
272 UsageError(" --num-dex-methods=<method-count>: threshold size for a small dex file for");
273 UsageError(" compiler filter tuning. If the input has fewer than this many methods");
Jeff Hao4a200f52014-04-01 14:58:49 -0700274 UsageError(" and the filter is not interpret-only or verify-none, overrides the");
275 UsageError(" filter to use speed");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800276 UsageError(" Example: --num-dex-method=%d", CompilerOptions::kDefaultNumDexMethodsThreshold);
277 UsageError(" Default: %d", CompilerOptions::kDefaultNumDexMethodsThreshold);
278 UsageError("");
Calin Juravleec748352015-07-29 13:52:12 +0100279 UsageError(" --inline-depth-limit=<depth-limit>: the depth limit of inlining for fine tuning");
280 UsageError(" the compiler. A zero value will disable inlining. Honored only by Optimizing.");
Roland Levillaina215b952015-08-07 11:38:32 +0100281 UsageError(" Has priority over the --compiler-filter option. Intended for ");
282 UsageError(" development/experimental use.");
Calin Juravleec748352015-07-29 13:52:12 +0100283 UsageError(" Example: --inline-depth-limit=%d", CompilerOptions::kDefaultInlineDepthLimit);
284 UsageError(" Default: %d", CompilerOptions::kDefaultInlineDepthLimit);
285 UsageError("");
286 UsageError(" --inline-max-code-units=<code-units-count>: the maximum code units that a method");
287 UsageError(" can have to be considered for inlining. A zero value will disable inlining.");
Roland Levillaina215b952015-08-07 11:38:32 +0100288 UsageError(" Honored only by Optimizing. Has priority over the --compiler-filter option.");
289 UsageError(" Intended for development/experimental use.");
Calin Juravleec748352015-07-29 13:52:12 +0100290 UsageError(" Example: --inline-max-code-units=%d",
291 CompilerOptions::kDefaultInlineMaxCodeUnits);
292 UsageError(" Default: %d", CompilerOptions::kDefaultInlineMaxCodeUnits);
293 UsageError("");
Ian Rogers46398602013-08-20 07:50:36 -0700294 UsageError(" --dump-timing: display a breakdown of where time was spent");
295 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700296 UsageError(" --include-patch-information: Include patching information so the generated code");
297 UsageError(" can have its base address moved without full recompilation.");
298 UsageError("");
299 UsageError(" --no-include-patch-information: Do not include patching information.");
300 UsageError("");
David Srbecky8363c772015-05-28 16:12:43 +0100301 UsageError(" -g");
302 UsageError(" --generate-debug-info: Generate debug information for native debugging,");
303 UsageError(" such as stack unwinding information, ELF symbols and DWARF sections.");
304 UsageError(" This generates all the available information. Unneeded parts can be");
305 UsageError(" stripped using standard command line tools such as strip or objcopy.");
306 UsageError(" (enabled by default in debug builds, disabled by default otherwise)");
Alex Light78382fa2014-06-06 15:45:32 -0700307 UsageError("");
Roland Levillainb2872da2015-09-02 09:35:25 +0100308 UsageError(" --debuggable: Produce debuggable code. Implies --generate-debug-info.");
309 UsageError("");
David Srbecky8363c772015-05-28 16:12:43 +0100310 UsageError(" --no-generate-debug-info: Do not generate debug information for native debugging.");
David Srbecky8dc73242015-04-12 11:40:39 +0100311 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700312 UsageError(" --runtime-arg <argument>: used to specify various arguments for the runtime,");
313 UsageError(" such as initial heap size, maximum heap size, and verbose output.");
314 UsageError(" Use a separate --runtime-arg switch for each argument.");
315 UsageError(" Example: --runtime-arg -Xms256m");
Jeff Hao4a200f52014-04-01 14:58:49 -0700316 UsageError("");
Dave Allisond6ed6422014-04-09 23:36:15 +0000317 UsageError(" --profile-file=<filename>: specify profiler output file to use for compilation.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700318 UsageError("");
Chao-ying Fucd8ce662014-03-11 14:57:19 -0700319 UsageError(" --print-pass-names: print a list of pass names");
320 UsageError("");
321 UsageError(" --disable-passes=<pass-names>: disable one or more passes separated by comma.");
322 UsageError(" Example: --disable-passes=UseCount,BBOptimizations");
323 UsageError("");
Razvan A Lupusorubd25d4b2014-07-02 18:16:51 -0700324 UsageError(" --print-pass-options: print a list of passes that have configurable options along "
325 "with the setting.");
326 UsageError(" Will print default if no overridden setting exists.");
327 UsageError("");
328 UsageError(" --pass-options=Pass1Name:Pass1OptionName:Pass1Option#,"
329 "Pass2Name:Pass2OptionName:Pass2Option#");
330 UsageError(" Used to specify a pass specific option. The setting itself must be integer.");
331 UsageError(" Separator used between options is a comma.");
332 UsageError("");
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800333 UsageError(" --swap-file=<file-name>: specifies a file to use for swap.");
334 UsageError(" Example: --swap-file=/data/tmp/swap.001");
335 UsageError("");
336 UsageError(" --swap-fd=<file-descriptor>: specifies a file to use for swap (by descriptor).");
337 UsageError(" Example: --swap-fd=10");
338 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700339 std::cerr << "See log for usage error information\n";
340 exit(EXIT_FAILURE);
341}
342
Brian Carlstrom7940e442013-07-12 13:46:57 -0700343// The primary goal of the watchdog is to prevent stuck build servers
344// during development when fatal aborts lead to a cascade of failures
345// that result in a deadlock.
346class WatchDog {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800347// WatchDog defines its own CHECK_PTHREAD_CALL to avoid using LOG which uses locks
Brian Carlstrom7940e442013-07-12 13:46:57 -0700348#undef CHECK_PTHREAD_CALL
349#define CHECK_WATCH_DOG_PTHREAD_CALL(call, args, what) \
350 do { \
351 int rc = call args; \
352 if (rc != 0) { \
353 errno = rc; \
354 std::string message(# call); \
355 message += " failed for "; \
356 message += reason; \
357 Fatal(message); \
358 } \
359 } while (false)
360
361 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -0700362 explicit WatchDog(bool is_watch_dog_enabled) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700363 is_watch_dog_enabled_ = is_watch_dog_enabled;
364 if (!is_watch_dog_enabled_) {
365 return;
366 }
367 shutting_down_ = false;
368 const char* reason = "dex2oat watch dog thread startup";
Kenny Root51316382014-05-13 14:59:37 -0700369 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_init, (&mutex_, nullptr), reason);
370 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_init, (&cond_, nullptr), reason);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700371 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_init, (&attr_), reason);
372 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_create, (&pthread_, &attr_, &CallBack, this), reason);
373 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_destroy, (&attr_), reason);
374 }
375 ~WatchDog() {
376 if (!is_watch_dog_enabled_) {
377 return;
378 }
379 const char* reason = "dex2oat watch dog thread shutdown";
380 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
381 shutting_down_ = true;
382 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_signal, (&cond_), reason);
383 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
384
Kenny Root51316382014-05-13 14:59:37 -0700385 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_join, (pthread_, nullptr), reason);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700386
387 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_destroy, (&cond_), reason);
388 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_destroy, (&mutex_), reason);
389 }
390
391 private:
392 static void* CallBack(void* arg) {
393 WatchDog* self = reinterpret_cast<WatchDog*>(arg);
394 ::art::SetThreadName("dex2oat watch dog");
395 self->Wait();
Kenny Root51316382014-05-13 14:59:37 -0700396 return nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700397 }
398
Andreas Gampe794ad762015-02-23 08:12:24 -0800399 NO_RETURN static void Fatal(const std::string& message) {
Andreas Gamped687e372015-04-28 23:16:03 -0700400 // TODO: When we can guarantee it won't prevent shutdown in error cases, move to LOG. However,
401 // it's rather easy to hang in unwinding.
402 // LogLine also avoids ART logging lock issues, as it's really only a wrapper around
403 // logcat logging or stderr output.
404 LogMessage::LogLine(__FILE__, __LINE__, LogSeverity::FATAL, message.c_str());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700405 exit(1);
406 }
407
408 void Wait() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700409 // TODO: tune the multiplier for GC verification, the following is just to make the timeout
410 // large.
Andreas Gamped687e372015-04-28 23:16:03 -0700411 constexpr int64_t multiplier = kVerifyObjectSupport > kVerifyObjectModeFast ? 100 : 1;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700412 timespec timeout_ts;
413 InitTimeSpec(true, CLOCK_REALTIME, multiplier * kWatchDogTimeoutSeconds * 1000, 0, &timeout_ts);
414 const char* reason = "dex2oat watch dog thread waiting";
415 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
416 while (!shutting_down_) {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800417 int rc = TEMP_FAILURE_RETRY(pthread_cond_timedwait(&cond_, &mutex_, &timeout_ts));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700418 if (rc == ETIMEDOUT) {
Andreas Gamped687e372015-04-28 23:16:03 -0700419 Fatal(StringPrintf("dex2oat did not finish after %" PRId64 " seconds",
420 kWatchDogTimeoutSeconds));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700421 } else if (rc != 0) {
422 std::string message(StringPrintf("pthread_cond_timedwait failed: %s",
423 strerror(errno)));
424 Fatal(message.c_str());
425 }
426 }
427 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
428 }
429
430 // 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 -0700431 // Debug builds are slower so they have larger timeouts.
Andreas Gamped687e372015-04-28 23:16:03 -0700432 static constexpr int64_t kSlowdownFactor = kIsDebugBuild ? 5U : 1U;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800433
Andreas Gampe540138a2015-09-14 15:34:38 -0700434 // 9.5 minutes scaled by kSlowdownFactor. This is slightly smaller than the Package Manager
435 // watchdog (PackageManagerService.WATCHDOG_TIMEOUT, 10 minutes), so that dex2oat will abort
436 // itself before that watchdog would take down the system server.
437 static constexpr int64_t kWatchDogTimeoutSeconds = kSlowdownFactor * (9 * 60 + 30);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700438
439 bool is_watch_dog_enabled_;
440 bool shutting_down_;
441 // TODO: Switch to Mutex when we can guarantee it won't prevent shutdown in error cases.
442 pthread_mutex_t mutex_;
443 pthread_cond_t cond_;
444 pthread_attr_t attr_;
445 pthread_t pthread_;
446};
Brian Carlstrom7940e442013-07-12 13:46:57 -0700447
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800448static void ParseStringAfterChar(const std::string& s, char c, std::string* parsed_value) {
Calin Juravlec1b643c2014-05-30 23:44:11 +0100449 std::string::size_type colon = s.find(c);
450 if (colon == std::string::npos) {
451 Usage("Missing char %c in option %s\n", c, s.c_str());
452 }
453 // Add one to remove the char we were trimming until.
454 *parsed_value = s.substr(colon + 1);
455}
456
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800457static void ParseDouble(const std::string& option, char after_char, double min, double max,
458 double* parsed_value) {
Calin Juravlec1b643c2014-05-30 23:44:11 +0100459 std::string substring;
460 ParseStringAfterChar(option, after_char, &substring);
461 bool sane_val = true;
462 double value;
463 if (false) {
464 // TODO: this doesn't seem to work on the emulator. b/15114595
465 std::stringstream iss(substring);
466 iss >> value;
467 // Ensure that we have a value, there was no cruft after it and it satisfies a sensible range.
468 sane_val = iss.eof() && (value >= min) && (value <= max);
469 } else {
470 char* end = nullptr;
471 value = strtod(substring.c_str(), &end);
472 sane_val = *end == '\0' && value >= min && value <= max;
473 }
474 if (!sane_val) {
475 Usage("Invalid double value %s for option %s\n", substring.c_str(), option.c_str());
476 }
477 *parsed_value = value;
478}
479
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800480static constexpr size_t kMinDexFilesForSwap = 2;
481static constexpr size_t kMinDexFileCumulativeSizeForSwap = 20 * MB;
482
483static bool UseSwap(bool is_image, std::vector<const DexFile*>& dex_files) {
484 if (is_image) {
485 // Don't use swap, we know generation should succeed, and we don't want to slow it down.
486 return false;
487 }
488 if (dex_files.size() < kMinDexFilesForSwap) {
489 // If there are less dex files than the threshold, assume it's gonna be fine.
490 return false;
491 }
492 size_t dex_files_size = 0;
493 for (const auto* dex_file : dex_files) {
494 dex_files_size += dex_file->GetHeader().file_size_;
495 }
496 return dex_files_size >= kMinDexFileCumulativeSizeForSwap;
497}
498
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800499class Dex2Oat FINAL {
500 public:
501 explicit Dex2Oat(TimingLogger* timings) :
Nicolas Geoffray409e8092015-10-01 10:32:19 +0100502 compiler_kind_(Compiler::kOptimizing),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800503 instruction_set_(kRuntimeISA),
504 // Take the default set of instruction features from the build.
Andreas Gampe3f30e122015-09-17 14:03:21 -0700505 verification_results_(nullptr),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800506 method_inliner_map_(),
507 runtime_(nullptr),
508 thread_count_(sysconf(_SC_NPROCESSORS_CONF)),
509 start_ns_(NanoTime()),
510 oat_fd_(-1),
511 zip_fd_(-1),
512 image_base_(0U),
513 image_classes_zip_filename_(nullptr),
514 image_classes_filename_(nullptr),
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800515 compiled_classes_zip_filename_(nullptr),
516 compiled_classes_filename_(nullptr),
Andreas Gampe70bef0d2015-04-15 02:37:28 -0700517 compiled_methods_zip_filename_(nullptr),
518 compiled_methods_filename_(nullptr),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800519 image_(false),
520 is_host_(false),
Andreas Gampe3f30e122015-09-17 14:03:21 -0700521 driver_(nullptr),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800522 dump_stats_(false),
523 dump_passes_(false),
524 dump_timing_(false),
525 dump_slow_timing_(kIsDebugBuild),
Calin Juravle87000a92015-08-24 15:34:44 +0100526 dump_cfg_append_(false),
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800527 swap_fd_(-1),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800528 timings_(timings) {}
529
530 ~Dex2Oat() {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800531 // Free opened dex files before deleting the runtime_, because ~DexFile
532 // uses MemMap, which is shut down by ~Runtime.
533 class_path_files_.clear();
534 opened_dex_files_.clear();
535
536 // Log completion time before deleting the runtime_, because this accesses
537 // the runtime.
538 LogCompletionTime();
539
Vladimir Marko307dac92015-10-20 11:20:09 +0100540 if (!kIsDebugBuild && !(RUNNING_ON_MEMORY_TOOL && kMemoryToolDetectsLeaks)) {
541 // We want to just exit on non-debug builds, not bringing the runtime down
542 // in an orderly fashion. So release the following fields.
543 driver_.release();
544 image_writer_.release();
545 for (std::unique_ptr<const DexFile>& dex_file : opened_dex_files_) {
546 dex_file.release();
547 }
548 oat_file_.release();
549 runtime_.release();
550 verification_results_.release();
551 key_value_store_.release();
Vladimir Markof94b7812014-06-05 15:48:04 +0100552 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700553 }
554
Roland Levillain9ec5e222015-08-17 20:18:41 +0100555 struct ParserOptions {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800556 std::string oat_symbols;
557 std::string boot_image_filename;
558 const char* compiler_filter_string = nullptr;
Roland Levillain9ec5e222015-08-17 20:18:41 +0100559 CompilerOptions::CompilerFilter compiler_filter = CompilerOptions::kDefaultCompilerFilter;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800560 bool compile_pic = false;
561 int huge_method_threshold = CompilerOptions::kDefaultHugeMethodThreshold;
562 int large_method_threshold = CompilerOptions::kDefaultLargeMethodThreshold;
563 int small_method_threshold = CompilerOptions::kDefaultSmallMethodThreshold;
564 int tiny_method_threshold = CompilerOptions::kDefaultTinyMethodThreshold;
565 int num_dex_methods_threshold = CompilerOptions::kDefaultNumDexMethodsThreshold;
Roland Levillaina215b952015-08-07 11:38:32 +0100566 static constexpr int kUnsetInlineDepthLimit = -1;
567 int inline_depth_limit = kUnsetInlineDepthLimit;
568 static constexpr int kUnsetInlineMaxCodeUnits = -1;
569 int inline_max_code_units = kUnsetInlineMaxCodeUnits;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800570
571 // Profile file to use
572 double top_k_profile_threshold = CompilerOptions::kDefaultTopKProfileThreshold;
573
Andreas Gampe7b2f09e2015-03-02 14:07:33 -0800574 bool debuggable = false;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800575 bool include_patch_information = CompilerOptions::kDefaultIncludePatchInformation;
David Srbecky8363c772015-05-28 16:12:43 +0100576 bool generate_debug_info = kIsDebugBuild;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800577 bool watch_dog_enabled = true;
Andreas Gampe6cf49e52015-03-05 13:08:45 -0800578 bool abort_on_hard_verifier_error = false;
Nicolas Geoffray1412dfa2015-03-20 14:48:13 +0000579 bool requested_specific_compiler = false;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800580
Roland Levillain9ec5e222015-08-17 20:18:41 +0100581 bool implicit_null_checks = false;
582 bool implicit_so_checks = false;
583 bool implicit_suspend_checks = false;
584
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800585 PassManagerOptions pass_manager_options;
586
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800587 std::string error_msg;
Roland Levillain9ec5e222015-08-17 20:18:41 +0100588 };
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800589
Roland Levillain9ec5e222015-08-17 20:18:41 +0100590 template <typename T>
591 static void ParseUintOption(const StringPiece& option,
592 const std::string& option_name,
593 T* out,
594 bool is_long_option = true) {
595 std::string option_prefix = option_name + (is_long_option ? "=" : "");
596 DCHECK(option.starts_with(option_prefix));
597 const char* value_string = option.substr(option_prefix.size()).data();
Andreas Gampe99e7df62015-08-17 14:14:25 -0700598 int64_t parsed_integer_value;
Roland Levillain9ec5e222015-08-17 20:18:41 +0100599 if (!ParseInt(value_string, &parsed_integer_value)) {
600 Usage("Failed to parse %s '%s' as an integer", option_name.c_str(), value_string);
601 }
602 if (parsed_integer_value < 0) {
603 Usage("%s passed a negative value %d", option_name.c_str(), parsed_integer_value);
604 }
Andreas Gampe99e7df62015-08-17 14:14:25 -0700605 *out = dchecked_integral_cast<T>(parsed_integer_value);
Roland Levillain9ec5e222015-08-17 20:18:41 +0100606 }
607
608 void ParseZipFd(const StringPiece& option) {
609 ParseUintOption(option, "--zip-fd", &zip_fd_);
610 }
611
612 void ParseOatFd(const StringPiece& option) {
613 ParseUintOption(option, "--oat-fd", &oat_fd_);
614 }
615
616 void ParseJ(const StringPiece& option) {
617 ParseUintOption(option, "-j", &thread_count_, /* is_long_option */ false);
618 }
619
620 void ParseBase(const StringPiece& option) {
621 DCHECK(option.starts_with("--base="));
622 const char* image_base_str = option.substr(strlen("--base=")).data();
623 char* end;
624 image_base_ = strtoul(image_base_str, &end, 16);
625 if (end == image_base_str || *end != '\0') {
626 Usage("Failed to parse hexadecimal value for option %s", option.data());
627 }
628 }
629
630 void ParseInstructionSet(const StringPiece& option) {
631 DCHECK(option.starts_with("--instruction-set="));
632 StringPiece instruction_set_str = option.substr(strlen("--instruction-set=")).data();
633 // StringPiece is not necessarily zero-terminated, so need to make a copy and ensure it.
634 std::unique_ptr<char[]> buf(new char[instruction_set_str.length() + 1]);
635 strncpy(buf.get(), instruction_set_str.data(), instruction_set_str.length());
636 buf.get()[instruction_set_str.length()] = 0;
637 instruction_set_ = GetInstructionSetFromString(buf.get());
638 // arm actually means thumb2.
639 if (instruction_set_ == InstructionSet::kArm) {
640 instruction_set_ = InstructionSet::kThumb2;
641 }
642 }
643
644 void ParseInstructionSetVariant(const StringPiece& option, ParserOptions* parser_options) {
645 DCHECK(option.starts_with("--instruction-set-variant="));
646 StringPiece str = option.substr(strlen("--instruction-set-variant=")).data();
647 instruction_set_features_.reset(
648 InstructionSetFeatures::FromVariant(
649 instruction_set_, str.as_string(), &parser_options->error_msg));
650 if (instruction_set_features_.get() == nullptr) {
651 Usage("%s", parser_options->error_msg.c_str());
652 }
653 }
654
655 void ParseInstructionSetFeatures(const StringPiece& option, ParserOptions* parser_options) {
656 DCHECK(option.starts_with("--instruction-set-features="));
657 StringPiece str = option.substr(strlen("--instruction-set-features=")).data();
658 if (instruction_set_features_.get() == nullptr) {
659 instruction_set_features_.reset(
660 InstructionSetFeatures::FromVariant(
661 instruction_set_, "default", &parser_options->error_msg));
662 if (instruction_set_features_.get() == nullptr) {
663 Usage("Problem initializing default instruction set features variant: %s",
664 parser_options->error_msg.c_str());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700665 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800666 }
Roland Levillain9ec5e222015-08-17 20:18:41 +0100667 instruction_set_features_.reset(
668 instruction_set_features_->AddFeaturesFromString(str.as_string(),
669 &parser_options->error_msg));
670 if (instruction_set_features_.get() == nullptr) {
671 Usage("Error parsing '%s': %s", option.data(), parser_options->error_msg.c_str());
672 }
673 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800674
Roland Levillain9ec5e222015-08-17 20:18:41 +0100675 void ParseCompilerBackend(const StringPiece& option, ParserOptions* parser_options) {
676 DCHECK(option.starts_with("--compiler-backend="));
677 parser_options->requested_specific_compiler = true;
678 StringPiece backend_str = option.substr(strlen("--compiler-backend=")).data();
679 if (backend_str == "Quick") {
680 compiler_kind_ = Compiler::kQuick;
681 } else if (backend_str == "Optimizing") {
682 compiler_kind_ = Compiler::kOptimizing;
683 } else {
684 Usage("Unknown compiler backend: %s", backend_str.data());
685 }
686 }
687
688 void ParseHugeMethodMax(const StringPiece& option, ParserOptions* parser_options) {
689 ParseUintOption(option, "--huge-method-max", &parser_options->huge_method_threshold);
690 }
691
692 void ParseLargeMethodMax(const StringPiece& option, ParserOptions* parser_options) {
693 ParseUintOption(option, "--large-method-max", &parser_options->large_method_threshold);
694 }
695
696 void ParseSmallMethodMax(const StringPiece& option, ParserOptions* parser_options) {
697 ParseUintOption(option, "--small-method-max", &parser_options->small_method_threshold);
698 }
699
700 void ParseTinyMethodMax(const StringPiece& option, ParserOptions* parser_options) {
701 ParseUintOption(option, "--tiny-method-max", &parser_options->tiny_method_threshold);
702 }
703
704 void ParseNumDexMethods(const StringPiece& option, ParserOptions* parser_options) {
705 ParseUintOption(option, "--num-dex-methods", &parser_options->num_dex_methods_threshold);
706 }
707
708 void ParseInlineDepthLimit(const StringPiece& option, ParserOptions* parser_options) {
709 ParseUintOption(option, "--inline-depth-limit", &parser_options->inline_depth_limit);
710 }
711
712 void ParseInlineMaxCodeUnits(const StringPiece& option, ParserOptions* parser_options) {
713 ParseUintOption(option, "--inline-max-code-units=", &parser_options->inline_max_code_units);
714 }
715
716 void ParseDisablePasses(const StringPiece& option, ParserOptions* parser_options) {
717 DCHECK(option.starts_with("--disable-passes="));
718 const std::string disable_passes = option.substr(strlen("--disable-passes=")).data();
719 parser_options->pass_manager_options.SetDisablePassList(disable_passes);
720 }
721
722 void ParsePrintPasses(const StringPiece& option, ParserOptions* parser_options) {
723 DCHECK(option.starts_with("--print-passes="));
724 const std::string print_passes = option.substr(strlen("--print-passes=")).data();
725 parser_options->pass_manager_options.SetPrintPassList(print_passes);
726 }
727
728 void ParseDumpCfgPasses(const StringPiece& option, ParserOptions* parser_options) {
729 DCHECK(option.starts_with("--dump-cfg-passes="));
730 const std::string dump_passes_string = option.substr(strlen("--dump-cfg-passes=")).data();
731 parser_options->pass_manager_options.SetDumpPassList(dump_passes_string);
732 }
733
734 void ParsePassOptions(const StringPiece& option, ParserOptions* parser_options) {
735 DCHECK(option.starts_with("--pass-options="));
736 const std::string pass_options = option.substr(strlen("--pass-options=")).data();
737 parser_options->pass_manager_options.SetOverriddenPassOptions(pass_options);
738 }
739
740 void ParseDumpInitFailures(const StringPiece& option) {
741 DCHECK(option.starts_with("--dump-init-failures="));
742 std::string file_name = option.substr(strlen("--dump-init-failures=")).data();
743 init_failure_output_.reset(new std::ofstream(file_name));
744 if (init_failure_output_.get() == nullptr) {
745 LOG(ERROR) << "Failed to allocate ofstream";
746 } else if (init_failure_output_->fail()) {
747 LOG(ERROR) << "Failed to open " << file_name << " for writing the initialization "
748 << "failures.";
749 init_failure_output_.reset();
750 }
751 }
752
753 void ParseSwapFd(const StringPiece& option) {
754 ParseUintOption(option, "--swap-fd", &swap_fd_);
755 }
756
757 void ProcessOptions(ParserOptions* parser_options) {
Nicolas Geoffray1412dfa2015-03-20 14:48:13 +0000758 image_ = (!image_filename_.empty());
Nicolas Geoffray409e8092015-10-01 10:32:19 +0100759 if (image_) {
760 // We need the boot image to always be debuggable.
761 parser_options->debuggable = true;
Nicolas Geoffray1412dfa2015-03-20 14:48:13 +0000762 }
Nicolas Geoffray9bb492a2014-11-25 23:42:00 +0000763
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800764 if (oat_filename_.empty() && oat_fd_ == -1) {
765 Usage("Output must be supplied with either --oat-file or --oat-fd");
766 }
767
768 if (!oat_filename_.empty() && oat_fd_ != -1) {
769 Usage("--oat-file should not be used with --oat-fd");
770 }
771
Roland Levillain9ec5e222015-08-17 20:18:41 +0100772 if (!parser_options->oat_symbols.empty() && oat_fd_ != -1) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800773 Usage("--oat-symbols should not be used with --oat-fd");
774 }
775
Roland Levillain9ec5e222015-08-17 20:18:41 +0100776 if (!parser_options->oat_symbols.empty() && is_host_) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800777 Usage("--oat-symbols should not be used with --host");
778 }
779
780 if (oat_fd_ != -1 && !image_filename_.empty()) {
781 Usage("--oat-fd should not be used with --image");
782 }
783
784 if (android_root_.empty()) {
785 const char* android_root_env_var = getenv("ANDROID_ROOT");
786 if (android_root_env_var == nullptr) {
787 Usage("--android-root unspecified and ANDROID_ROOT not set");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700788 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800789 android_root_ += android_root_env_var;
790 }
791
Roland Levillain9ec5e222015-08-17 20:18:41 +0100792 if (!image_ && parser_options->boot_image_filename.empty()) {
793 parser_options->boot_image_filename += android_root_;
794 parser_options->boot_image_filename += "/framework/boot.art";
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800795 }
Roland Levillain9ec5e222015-08-17 20:18:41 +0100796 if (!parser_options->boot_image_filename.empty()) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800797 boot_image_option_ += "-Ximage:";
Roland Levillain9ec5e222015-08-17 20:18:41 +0100798 boot_image_option_ += parser_options->boot_image_filename;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800799 }
800
801 if (image_classes_filename_ != nullptr && !image_) {
802 Usage("--image-classes should only be used with --image");
803 }
804
805 if (image_classes_filename_ != nullptr && !boot_image_option_.empty()) {
806 Usage("--image-classes should not be used with --boot-image");
807 }
808
809 if (image_classes_zip_filename_ != nullptr && image_classes_filename_ == nullptr) {
810 Usage("--image-classes-zip should be used with --image-classes");
811 }
812
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800813 if (compiled_classes_filename_ != nullptr && !image_) {
814 Usage("--compiled-classes should only be used with --image");
815 }
816
817 if (compiled_classes_filename_ != nullptr && !boot_image_option_.empty()) {
818 Usage("--compiled-classes should not be used with --boot-image");
819 }
820
821 if (compiled_classes_zip_filename_ != nullptr && compiled_classes_filename_ == nullptr) {
822 Usage("--compiled-classes-zip should be used with --compiled-classes");
823 }
824
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800825 if (dex_filenames_.empty() && zip_fd_ == -1) {
826 Usage("Input must be supplied with either --dex-file or --zip-fd");
827 }
828
829 if (!dex_filenames_.empty() && zip_fd_ != -1) {
830 Usage("--dex-file should not be used with --zip-fd");
831 }
832
833 if (!dex_filenames_.empty() && !zip_location_.empty()) {
834 Usage("--dex-file should not be used with --zip-location");
835 }
836
837 if (dex_locations_.empty()) {
838 for (const char* dex_file_name : dex_filenames_) {
839 dex_locations_.push_back(dex_file_name);
840 }
841 } else if (dex_locations_.size() != dex_filenames_.size()) {
842 Usage("--dex-location arguments do not match --dex-file arguments");
843 }
844
845 if (zip_fd_ != -1 && zip_location_.empty()) {
846 Usage("--zip-location should be supplied with --zip-fd");
847 }
848
849 if (boot_image_option_.empty()) {
850 if (image_base_ == 0) {
851 Usage("Non-zero --base not specified");
852 }
853 }
854
855 oat_stripped_ = oat_filename_;
Roland Levillain9ec5e222015-08-17 20:18:41 +0100856 if (!parser_options->oat_symbols.empty()) {
857 oat_unstripped_ = parser_options->oat_symbols;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700858 } else {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800859 oat_unstripped_ = oat_filename_;
860 }
861
862 // If no instruction set feature was given, use the default one for the target
863 // instruction set.
864 if (instruction_set_features_.get() == nullptr) {
865 instruction_set_features_.reset(
Roland Levillain9ec5e222015-08-17 20:18:41 +0100866 InstructionSetFeatures::FromVariant(
867 instruction_set_, "default", &parser_options->error_msg));
Ian Rogersd582fa42014-11-05 23:46:43 -0800868 if (instruction_set_features_.get() == nullptr) {
869 Usage("Problem initializing default instruction set features variant: %s",
Roland Levillain9ec5e222015-08-17 20:18:41 +0100870 parser_options->error_msg.c_str());
Ian Rogersd582fa42014-11-05 23:46:43 -0800871 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800872 }
873
874 if (instruction_set_ == kRuntimeISA) {
875 std::unique_ptr<const InstructionSetFeatures> runtime_features(
876 InstructionSetFeatures::FromCppDefines());
877 if (!instruction_set_features_->Equals(runtime_features.get())) {
878 LOG(WARNING) << "Mismatch between dex2oat instruction set features ("
879 << *instruction_set_features_ << ") and those of dex2oat executable ("
880 << *runtime_features <<") for the command line:\n"
881 << CommandLine();
882 }
883 }
884
Roland Levillain9ec5e222015-08-17 20:18:41 +0100885 if (parser_options->compiler_filter_string == nullptr) {
886 parser_options->compiler_filter_string = "speed";
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800887 }
Maja Gagic6ea651f2015-02-24 16:55:04 +0100888
Roland Levillain9ec5e222015-08-17 20:18:41 +0100889 CHECK(parser_options->compiler_filter_string != nullptr);
890 if (strcmp(parser_options->compiler_filter_string, "verify-none") == 0) {
891 parser_options->compiler_filter = CompilerOptions::kVerifyNone;
892 } else if (strcmp(parser_options->compiler_filter_string, "interpret-only") == 0) {
893 parser_options->compiler_filter = CompilerOptions::kInterpretOnly;
894 } else if (strcmp(parser_options->compiler_filter_string, "verify-at-runtime") == 0) {
895 parser_options->compiler_filter = CompilerOptions::kVerifyAtRuntime;
896 } else if (strcmp(parser_options->compiler_filter_string, "space") == 0) {
897 parser_options->compiler_filter = CompilerOptions::kSpace;
898 } else if (strcmp(parser_options->compiler_filter_string, "balanced") == 0) {
899 parser_options->compiler_filter = CompilerOptions::kBalanced;
900 } else if (strcmp(parser_options->compiler_filter_string, "speed") == 0) {
901 parser_options->compiler_filter = CompilerOptions::kSpeed;
902 } else if (strcmp(parser_options->compiler_filter_string, "everything") == 0) {
903 parser_options->compiler_filter = CompilerOptions::kEverything;
904 } else if (strcmp(parser_options->compiler_filter_string, "time") == 0) {
905 parser_options->compiler_filter = CompilerOptions::kTime;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800906 } else {
Roland Levillain9ec5e222015-08-17 20:18:41 +0100907 Usage("Unknown --compiler-filter value %s", parser_options->compiler_filter_string);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800908 }
909
Roland Levillaina215b952015-08-07 11:38:32 +0100910 // It they are not set, use default values for inlining settings.
911 // TODO: We should rethink the compiler filter. We mostly save
912 // time here, which is orthogonal to space.
Roland Levillain9ec5e222015-08-17 20:18:41 +0100913 if (parser_options->inline_depth_limit == ParserOptions::kUnsetInlineDepthLimit) {
914 parser_options->inline_depth_limit =
915 (parser_options->compiler_filter == CompilerOptions::kSpace)
Roland Levillaina215b952015-08-07 11:38:32 +0100916 // Implementation of the space filter: limit inlining depth.
917 ? CompilerOptions::kSpaceFilterInlineDepthLimit
918 : CompilerOptions::kDefaultInlineDepthLimit;
919 }
Roland Levillain9ec5e222015-08-17 20:18:41 +0100920 if (parser_options->inline_max_code_units == ParserOptions::kUnsetInlineMaxCodeUnits) {
921 parser_options->inline_max_code_units =
922 (parser_options->compiler_filter == CompilerOptions::kSpace)
Roland Levillaina215b952015-08-07 11:38:32 +0100923 // Implementation of the space filter: limit inlining max code units.
924 ? CompilerOptions::kSpaceFilterInlineMaxCodeUnits
925 : CompilerOptions::kDefaultInlineMaxCodeUnits;
926 }
927
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800928 // Checks are all explicit until we know the architecture.
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800929 // Set the compilation target's implicit checks options.
930 switch (instruction_set_) {
931 case kArm:
932 case kThumb2:
933 case kArm64:
934 case kX86:
935 case kX86_64:
Douglas Leung22bb5a22015-07-02 16:42:08 -0700936 case kMips:
937 case kMips64:
Roland Levillain9ec5e222015-08-17 20:18:41 +0100938 parser_options->implicit_null_checks = true;
939 parser_options->implicit_so_checks = true;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800940 break;
941
942 default:
943 // Defaults are correct.
944 break;
945 }
946
Roland Levillain9ec5e222015-08-17 20:18:41 +0100947 compiler_options_.reset(new CompilerOptions(parser_options->compiler_filter,
948 parser_options->huge_method_threshold,
949 parser_options->large_method_threshold,
950 parser_options->small_method_threshold,
951 parser_options->tiny_method_threshold,
952 parser_options->num_dex_methods_threshold,
953 parser_options->inline_depth_limit,
954 parser_options->inline_max_code_units,
955 parser_options->include_patch_information,
956 parser_options->top_k_profile_threshold,
957 parser_options->debuggable,
958 parser_options->generate_debug_info,
959 parser_options->implicit_null_checks,
960 parser_options->implicit_so_checks,
961 parser_options->implicit_suspend_checks,
962 parser_options->compile_pic,
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800963 verbose_methods_.empty() ?
964 nullptr :
Andreas Gampedbfe2542014-11-25 22:21:42 -0800965 &verbose_methods_,
Roland Levillain9ec5e222015-08-17 20:18:41 +0100966 new PassManagerOptions(
967 parser_options->pass_manager_options),
Andreas Gampe6cf49e52015-03-05 13:08:45 -0800968 init_failure_output_.get(),
Roland Levillain9ec5e222015-08-17 20:18:41 +0100969 parser_options->abort_on_hard_verifier_error));
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800970
971 // Done with usage checks, enable watchdog if requested
Roland Levillain9ec5e222015-08-17 20:18:41 +0100972 if (parser_options->watch_dog_enabled) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800973 watchdog_.reset(new WatchDog(true));
974 }
975
976 // Fill some values into the key-value store for the oat header.
977 key_value_store_.reset(new SafeMap<std::string, std::string>());
Roland Levillain9ec5e222015-08-17 20:18:41 +0100978 }
979
980 void InsertCompileOptions(int argc, char** argv, ParserOptions* parser_options) {
981 std::ostringstream oss;
982 for (int i = 0; i < argc; ++i) {
983 if (i > 0) {
984 oss << ' ';
985 }
986 oss << argv[i];
987 }
988 key_value_store_->Put(OatHeader::kDex2OatCmdLineKey, oss.str());
989 oss.str(""); // Reset.
990 oss << kRuntimeISA;
991 key_value_store_->Put(OatHeader::kDex2OatHostKey, oss.str());
992 key_value_store_->Put(
993 OatHeader::kPicKey,
994 parser_options->compile_pic ? OatHeader::kTrueValue : OatHeader::kFalseValue);
995 key_value_store_->Put(
996 OatHeader::kDebuggableKey,
997 parser_options->debuggable ? OatHeader::kTrueValue : OatHeader::kFalseValue);
998 }
999
1000 // Parse the arguments from the command line. In case of an unrecognized option or impossible
1001 // values/combinations, a usage error will be displayed and exit() is called. Thus, if the method
1002 // returns, arguments have been successfully parsed.
1003 void ParseArgs(int argc, char** argv) {
1004 original_argc = argc;
1005 original_argv = argv;
1006
1007 InitLogging(argv);
1008
1009 // Skip over argv[0].
1010 argv++;
1011 argc--;
1012
1013 if (argc == 0) {
1014 Usage("No arguments specified");
1015 }
1016
1017 std::unique_ptr<ParserOptions> parser_options(new ParserOptions());
1018
1019 for (int i = 0; i < argc; i++) {
1020 const StringPiece option(argv[i]);
1021 const bool log_options = false;
1022 if (log_options) {
1023 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
1024 }
1025 if (option.starts_with("--dex-file=")) {
1026 dex_filenames_.push_back(option.substr(strlen("--dex-file=")).data());
1027 } else if (option.starts_with("--dex-location=")) {
1028 dex_locations_.push_back(option.substr(strlen("--dex-location=")).data());
1029 } else if (option.starts_with("--zip-fd=")) {
1030 ParseZipFd(option);
1031 } else if (option.starts_with("--zip-location=")) {
1032 zip_location_ = option.substr(strlen("--zip-location=")).data();
1033 } else if (option.starts_with("--oat-file=")) {
1034 oat_filename_ = option.substr(strlen("--oat-file=")).data();
1035 } else if (option.starts_with("--oat-symbols=")) {
1036 parser_options->oat_symbols = option.substr(strlen("--oat-symbols=")).data();
1037 } else if (option.starts_with("--oat-fd=")) {
1038 ParseOatFd(option);
1039 } else if (option == "--watch-dog") {
1040 parser_options->watch_dog_enabled = true;
1041 } else if (option == "--no-watch-dog") {
1042 parser_options->watch_dog_enabled = false;
1043 } else if (option.starts_with("-j")) {
1044 ParseJ(option);
1045 } else if (option.starts_with("--oat-location=")) {
1046 oat_location_ = option.substr(strlen("--oat-location=")).data();
1047 } else if (option.starts_with("--image=")) {
1048 image_filename_ = option.substr(strlen("--image=")).data();
1049 } else if (option.starts_with("--image-classes=")) {
1050 image_classes_filename_ = option.substr(strlen("--image-classes=")).data();
1051 } else if (option.starts_with("--image-classes-zip=")) {
1052 image_classes_zip_filename_ = option.substr(strlen("--image-classes-zip=")).data();
1053 } else if (option.starts_with("--compiled-classes=")) {
1054 compiled_classes_filename_ = option.substr(strlen("--compiled-classes=")).data();
1055 } else if (option.starts_with("--compiled-classes-zip=")) {
1056 compiled_classes_zip_filename_ = option.substr(strlen("--compiled-classes-zip=")).data();
1057 } else if (option.starts_with("--compiled-methods=")) {
1058 compiled_methods_filename_ = option.substr(strlen("--compiled-methods=")).data();
1059 } else if (option.starts_with("--compiled-methods-zip=")) {
1060 compiled_methods_zip_filename_ = option.substr(strlen("--compiled-methods-zip=")).data();
1061 } else if (option.starts_with("--base=")) {
1062 ParseBase(option);
1063 } else if (option.starts_with("--boot-image=")) {
1064 parser_options->boot_image_filename = option.substr(strlen("--boot-image=")).data();
1065 } else if (option.starts_with("--android-root=")) {
1066 android_root_ = option.substr(strlen("--android-root=")).data();
1067 } else if (option.starts_with("--instruction-set=")) {
1068 ParseInstructionSet(option);
1069 } else if (option.starts_with("--instruction-set-variant=")) {
1070 ParseInstructionSetVariant(option, parser_options.get());
1071 } else if (option.starts_with("--instruction-set-features=")) {
1072 ParseInstructionSetFeatures(option, parser_options.get());
1073 } else if (option.starts_with("--compiler-backend=")) {
1074 ParseCompilerBackend(option, parser_options.get());
1075 } else if (option.starts_with("--compiler-filter=")) {
1076 parser_options->compiler_filter_string = option.substr(strlen("--compiler-filter=")).data();
1077 } else if (option == "--compile-pic") {
1078 parser_options->compile_pic = true;
1079 } else if (option.starts_with("--huge-method-max=")) {
1080 ParseHugeMethodMax(option, parser_options.get());
1081 } else if (option.starts_with("--large-method-max=")) {
1082 ParseLargeMethodMax(option, parser_options.get());
1083 } else if (option.starts_with("--small-method-max=")) {
1084 ParseSmallMethodMax(option, parser_options.get());
1085 } else if (option.starts_with("--tiny-method-max=")) {
1086 ParseTinyMethodMax(option, parser_options.get());
1087 } else if (option.starts_with("--num-dex-methods=")) {
1088 ParseNumDexMethods(option, parser_options.get());
1089 } else if (option.starts_with("--inline-depth-limit=")) {
1090 ParseInlineDepthLimit(option, parser_options.get());
1091 } else if (option.starts_with("--inline-max-code-units=")) {
1092 ParseInlineMaxCodeUnits(option, parser_options.get());
1093 } else if (option == "--host") {
1094 is_host_ = true;
1095 } else if (option == "--runtime-arg") {
1096 if (++i >= argc) {
1097 Usage("Missing required argument for --runtime-arg");
1098 }
1099 if (log_options) {
1100 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
1101 }
1102 runtime_args_.push_back(argv[i]);
1103 } else if (option == "--dump-timing") {
1104 dump_timing_ = true;
1105 } else if (option == "--dump-passes") {
1106 dump_passes_ = true;
1107 } else if (option.starts_with("--dump-cfg=")) {
1108 dump_cfg_file_name_ = option.substr(strlen("--dump-cfg=")).data();
Calin Juravle87000a92015-08-24 15:34:44 +01001109 } else if (option.starts_with("--dump-cfg-append")) {
1110 dump_cfg_append_ = true;
Roland Levillain9ec5e222015-08-17 20:18:41 +01001111 } else if (option == "--dump-stats") {
1112 dump_stats_ = true;
1113 } else if (option == "--generate-debug-info" || option == "-g") {
1114 parser_options->generate_debug_info = true;
1115 } else if (option == "--no-generate-debug-info") {
1116 parser_options->generate_debug_info = false;
1117 } else if (option == "--debuggable") {
1118 parser_options->debuggable = true;
1119 parser_options->generate_debug_info = true;
1120 } else if (option.starts_with("--profile-file=")) {
1121 profile_file_ = option.substr(strlen("--profile-file=")).data();
1122 VLOG(compiler) << "dex2oat: profile file is " << profile_file_;
1123 } else if (option == "--no-profile-file") {
1124 // No profile
1125 } else if (option.starts_with("--top-k-profile-threshold=")) {
1126 ParseDouble(option.data(), '=', 0.0, 100.0, &parser_options->top_k_profile_threshold);
1127 } else if (option == "--print-pass-names") {
1128 parser_options->pass_manager_options.SetPrintPassNames(true);
1129 } else if (option.starts_with("--disable-passes=")) {
1130 ParseDisablePasses(option, parser_options.get());
1131 } else if (option.starts_with("--print-passes=")) {
1132 ParsePrintPasses(option, parser_options.get());
1133 } else if (option == "--print-all-passes") {
1134 parser_options->pass_manager_options.SetPrintAllPasses();
1135 } else if (option.starts_with("--dump-cfg-passes=")) {
1136 ParseDumpCfgPasses(option, parser_options.get());
1137 } else if (option == "--print-pass-options") {
1138 parser_options->pass_manager_options.SetPrintPassOptions(true);
1139 } else if (option.starts_with("--pass-options=")) {
1140 ParsePassOptions(option, parser_options.get());
1141 } else if (option == "--include-patch-information") {
1142 parser_options->include_patch_information = true;
1143 } else if (option == "--no-include-patch-information") {
1144 parser_options->include_patch_information = false;
1145 } else if (option.starts_with("--verbose-methods=")) {
1146 // TODO: rather than switch off compiler logging, make all VLOG(compiler) messages
1147 // conditional on having verbost methods.
1148 gLogVerbosity.compiler = false;
1149 Split(option.substr(strlen("--verbose-methods=")).ToString(), ',', &verbose_methods_);
1150 } else if (option.starts_with("--dump-init-failures=")) {
1151 ParseDumpInitFailures(option);
1152 } else if (option.starts_with("--swap-file=")) {
1153 swap_file_name_ = option.substr(strlen("--swap-file=")).data();
1154 } else if (option.starts_with("--swap-fd=")) {
1155 ParseSwapFd(option);
1156 } else if (option == "--abort-on-hard-verifier-error") {
1157 parser_options->abort_on_hard_verifier_error = true;
1158 } else {
1159 Usage("Unknown argument %s", option.data());
1160 }
1161 }
1162
1163 ProcessOptions(parser_options.get());
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001164
1165 // Insert some compiler things.
Roland Levillain9ec5e222015-08-17 20:18:41 +01001166 InsertCompileOptions(argc, argv, parser_options.get());
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001167 }
1168
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001169 // Check whether the oat output file is writable, and open it for later. Also open a swap file,
1170 // if a name is given.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001171 bool OpenFile() {
1172 bool create_file = !oat_unstripped_.empty(); // as opposed to using open file descriptor
1173 if (create_file) {
1174 oat_file_.reset(OS::CreateEmptyFile(oat_unstripped_.c_str()));
1175 if (oat_location_.empty()) {
1176 oat_location_ = oat_filename_;
1177 }
1178 } else {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001179 oat_file_.reset(new File(oat_fd_, oat_location_, true));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001180 oat_file_->DisableAutoClose();
Andreas Gampe4303ba92014-11-06 01:00:46 -08001181 if (oat_file_->SetLength(0) != 0) {
1182 PLOG(WARNING) << "Truncating oat file " << oat_location_ << " failed.";
1183 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001184 }
1185 if (oat_file_.get() == nullptr) {
1186 PLOG(ERROR) << "Failed to create oat file: " << oat_location_;
1187 return false;
1188 }
1189 if (create_file && fchmod(oat_file_->Fd(), 0644) != 0) {
1190 PLOG(ERROR) << "Failed to make oat file world readable: " << oat_location_;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001191 oat_file_->Erase();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001192 return false;
1193 }
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001194
1195 // Swap file handling.
1196 //
1197 // If the swap fd is not -1, we assume this is the file descriptor of an open but unlinked file
1198 // that we can use for swap.
1199 //
1200 // If the swap fd is -1 and we have a swap-file string, open the given file as a swap file. We
1201 // will immediately unlink to satisfy the swap fd assumption.
1202 if (swap_fd_ == -1 && !swap_file_name_.empty()) {
1203 std::unique_ptr<File> swap_file(OS::CreateEmptyFile(swap_file_name_.c_str()));
1204 if (swap_file.get() == nullptr) {
1205 PLOG(ERROR) << "Failed to create swap file: " << swap_file_name_;
1206 return false;
1207 }
1208 swap_fd_ = swap_file->Fd();
1209 swap_file->MarkUnchecked(); // We don't we to track this, it will be unlinked immediately.
1210 swap_file->DisableAutoClose(); // We'll handle it ourselves, the File object will be
1211 // released immediately.
1212 unlink(swap_file_name_.c_str());
1213 }
1214
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001215 return true;
1216 }
1217
Andreas Gampea650e702014-12-03 14:28:02 -08001218 void EraseOatFile() {
1219 DCHECK(oat_file_.get() != nullptr);
1220 oat_file_->Erase();
1221 oat_file_.reset();
1222 }
1223
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001224 void Shutdown() {
1225 ScopedObjectAccess soa(Thread::Current());
1226 for (jobject dex_cache : dex_caches_) {
1227 soa.Env()->DeleteLocalRef(dex_cache);
1228 }
1229 dex_caches_.clear();
1230 }
1231
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001232 // Set up the environment for compilation. Includes starting the runtime and loading/opening the
1233 // boot class path.
1234 bool Setup() {
1235 TimingLogger::ScopedTiming t("dex2oat Setup", timings_);
1236 RuntimeOptions runtime_options;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001237 art::MemMap::Init(); // For ZipEntry::ExtractToMemMap.
1238 if (boot_image_option_.empty()) {
Richard Uhlerc2752592015-01-02 13:28:22 -08001239 std::string boot_class_path = "-Xbootclasspath:";
1240 boot_class_path += Join(dex_filenames_, ':');
1241 runtime_options.push_back(std::make_pair(boot_class_path, nullptr));
1242 std::string boot_class_path_locations = "-Xbootclasspath-locations:";
1243 boot_class_path_locations += Join(dex_locations_, ':');
1244 runtime_options.push_back(std::make_pair(boot_class_path_locations, nullptr));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001245 } else {
Richard Uhlerc2752592015-01-02 13:28:22 -08001246 runtime_options.push_back(std::make_pair(boot_image_option_, nullptr));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001247 }
1248 for (size_t i = 0; i < runtime_args_.size(); i++) {
1249 runtime_options.push_back(std::make_pair(runtime_args_[i], nullptr));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001250 }
Brian Carlstromd76e0832013-08-29 15:17:42 -07001251
Vladimir Marko307dac92015-10-20 11:20:09 +01001252 verification_results_.reset(new VerificationResults(compiler_options_.get()));
Andreas Gampe4585f872015-03-27 23:45:15 -07001253 callbacks_.reset(new QuickCompilerCallbacks(
Vladimir Marko307dac92015-10-20 11:20:09 +01001254 verification_results_.get(),
Andreas Gampe4585f872015-03-27 23:45:15 -07001255 &method_inliner_map_,
1256 image_ ?
1257 CompilerCallbacks::CallbackMode::kCompileBootImage :
1258 CompilerCallbacks::CallbackMode::kCompileApp));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001259 runtime_options.push_back(std::make_pair("compilercallbacks", callbacks_.get()));
1260 runtime_options.push_back(
1261 std::make_pair("imageinstructionset", GetInstructionSetString(instruction_set_)));
1262
Andreas Gampe1d00add2015-02-27 19:35:46 -08001263 // Only allow no boot image for the runtime if we're compiling one. When we compile an app,
1264 // we don't want fallback mode, it will abort as we do not push a boot classpath (it might
1265 // have been stripped in preopting, anyways).
1266 if (!image_) {
1267 runtime_options.push_back(std::make_pair("-Xno-dex-file-fallback", nullptr));
1268 }
Calin Juravle01aaf6e2015-06-19 22:05:39 +01001269 // Disable libsigchain. We don't don't need it during compilation and it prevents us
1270 // from getting a statically linked version of dex2oat (because of dlsym and RTLD_NEXT).
1271 runtime_options.push_back(std::make_pair("-Xno-sig-chain", nullptr));
Andreas Gampe1d00add2015-02-27 19:35:46 -08001272
Andreas Gampec7ae55d2015-09-15 20:04:54 -07001273 {
1274 TimingLogger::ScopedTiming t_runtime("Create runtime", timings_);
1275 if (!CreateRuntime(runtime_options)) {
1276 return false;
1277 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001278 }
1279
1280 // Runtime::Create acquired the mutator_lock_ that is normally given away when we
1281 // Runtime::Start, give it away now so that we don't starve GC.
1282 Thread* self = Thread::Current();
1283 self->TransitionFromRunnableToSuspended(kNative);
1284 // If we're doing the image, override the compiler filter to force full compilation. Must be
1285 // done ahead of WellKnownClasses::Init that causes verification. Note: doesn't force
1286 // compilation of class initializers.
1287 // Whilst we're in native take the opportunity to initialize well known classes.
1288 WellKnownClasses::Init(self->GetJniEnv());
1289
1290 // If --image-classes was specified, calculate the full list of classes to include in the image
1291 if (image_classes_filename_ != nullptr) {
1292 std::string error_msg;
1293 if (image_classes_zip_filename_ != nullptr) {
1294 image_classes_.reset(ReadImageClassesFromZip(image_classes_zip_filename_,
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001295 image_classes_filename_,
1296 &error_msg));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001297 } else {
1298 image_classes_.reset(ReadImageClassesFromFile(image_classes_filename_));
1299 }
1300 if (image_classes_.get() == nullptr) {
1301 LOG(ERROR) << "Failed to create list of image classes from '" << image_classes_filename_ <<
1302 "': " << error_msg;
1303 return false;
1304 }
1305 } else if (image_) {
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001306 image_classes_.reset(new std::unordered_set<std::string>);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001307 }
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001308 // If --compiled-classes was specified, calculate the full list of classes to compile in the
1309 // image.
1310 if (compiled_classes_filename_ != nullptr) {
1311 std::string error_msg;
1312 if (compiled_classes_zip_filename_ != nullptr) {
1313 compiled_classes_.reset(ReadImageClassesFromZip(compiled_classes_zip_filename_,
1314 compiled_classes_filename_,
1315 &error_msg));
1316 } else {
1317 compiled_classes_.reset(ReadImageClassesFromFile(compiled_classes_filename_));
1318 }
1319 if (compiled_classes_.get() == nullptr) {
1320 LOG(ERROR) << "Failed to create list of compiled classes from '"
1321 << compiled_classes_filename_ << "': " << error_msg;
1322 return false;
1323 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001324 } else {
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001325 compiled_classes_.reset(nullptr); // By default compile everything.
1326 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001327 // If --compiled-methods was specified, read the methods to compile from the given file(s).
1328 if (compiled_methods_filename_ != nullptr) {
1329 std::string error_msg;
1330 if (compiled_methods_zip_filename_ != nullptr) {
1331 compiled_methods_.reset(ReadCommentedInputFromZip(compiled_methods_zip_filename_,
1332 compiled_methods_filename_,
1333 nullptr, // No post-processing.
1334 &error_msg));
1335 } else {
1336 compiled_methods_.reset(ReadCommentedInputFromFile(compiled_methods_filename_,
1337 nullptr)); // No post-processing.
1338 }
1339 if (compiled_methods_.get() == nullptr) {
1340 LOG(ERROR) << "Failed to create list of compiled methods from '"
1341 << compiled_methods_filename_ << "': " << error_msg;
1342 return false;
1343 }
1344 } else {
1345 compiled_methods_.reset(nullptr); // By default compile everything.
1346 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001347
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001348 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001349 if (boot_image_option_.empty()) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001350 dex_files_ = class_linker->GetBootClassPath();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001351 } else {
Andreas Gampec7ae55d2015-09-15 20:04:54 -07001352 TimingLogger::ScopedTiming t_dex("Opening dex files", timings_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001353 if (dex_filenames_.empty()) {
1354 ATRACE_BEGIN("Opening zip archive from file descriptor");
1355 std::string error_msg;
1356 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(zip_fd_,
1357 zip_location_.c_str(),
1358 &error_msg));
1359 if (zip_archive.get() == nullptr) {
1360 LOG(ERROR) << "Failed to open zip from file descriptor for '" << zip_location_ << "': "
1361 << error_msg;
1362 return false;
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001363 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001364 if (!DexFile::OpenFromZip(*zip_archive.get(), zip_location_, &error_msg, &opened_dex_files_)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001365 LOG(ERROR) << "Failed to open dex from file descriptor for zip file '" << zip_location_
1366 << "': " << error_msg;
1367 return false;
1368 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001369 for (auto& dex_file : opened_dex_files_) {
1370 dex_files_.push_back(dex_file.get());
1371 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001372 ATRACE_END();
1373 } else {
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001374 size_t failure_count = OpenDexFiles(dex_filenames_, dex_locations_, &opened_dex_files_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001375 if (failure_count > 0) {
1376 LOG(ERROR) << "Failed to open some dex files: " << failure_count;
1377 return false;
1378 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001379 for (auto& dex_file : opened_dex_files_) {
1380 dex_files_.push_back(dex_file.get());
1381 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001382 }
1383
1384 constexpr bool kSaveDexInput = false;
1385 if (kSaveDexInput) {
1386 for (size_t i = 0; i < dex_files_.size(); ++i) {
1387 const DexFile* dex_file = dex_files_[i];
Brian Carlstrom95b033b2014-12-03 22:29:37 -08001388 std::string tmp_file_name(StringPrintf("/data/local/tmp/dex2oat.%d.%zd.dex",
1389 getpid(), i));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001390 std::unique_ptr<File> tmp_file(OS::CreateEmptyFile(tmp_file_name.c_str()));
1391 if (tmp_file.get() == nullptr) {
1392 PLOG(ERROR) << "Failed to open file " << tmp_file_name
1393 << ". Try: adb shell chmod 777 /data/local/tmp";
1394 continue;
1395 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001396 // This is just dumping files for debugging. Ignore errors, and leave remnants.
1397 UNUSED(tmp_file->WriteFully(dex_file->Begin(), dex_file->Size()));
1398 UNUSED(tmp_file->Flush());
1399 UNUSED(tmp_file->Close());
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001400 LOG(INFO) << "Wrote input to " << tmp_file_name;
1401 }
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001402 }
1403 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001404 // Ensure opened dex files are writable for dex-to-dex transformations. Also ensure that
1405 // the dex caches stay live since we don't want class unloading to occur during compilation.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001406 for (const auto& dex_file : dex_files_) {
1407 if (!dex_file->EnableWrite()) {
1408 PLOG(ERROR) << "Failed to make .dex file writeable '" << dex_file->GetLocation() << "'\n";
Andreas Gampe7ba64962014-10-23 11:37:40 -07001409 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001410 ScopedObjectAccess soa(self);
1411 dex_caches_.push_back(soa.AddLocalReference<jobject>(
Mathieu Chartierd57d4542015-10-14 10:55:30 -07001412 class_linker->RegisterDexFile(*dex_file, Runtime::Current()->GetLinearAlloc())));
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001413 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001414
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001415 // If we use a swap file, ensure we are above the threshold to make it necessary.
1416 if (swap_fd_ != -1) {
1417 if (!UseSwap(image_, dex_files_)) {
1418 close(swap_fd_);
1419 swap_fd_ = -1;
Andreas Gampef99bcd22015-04-24 16:22:18 -07001420 VLOG(compiler) << "Decided to run without swap.";
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001421 } else {
Andreas Gampef99bcd22015-04-24 16:22:18 -07001422 LOG(INFO) << "Large app, accepted running with swap.";
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001423 }
1424 }
1425 // Note that dex2oat won't close the swap_fd_. The compiler driver's swap space will do that.
1426
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001427 /*
1428 * If we're not in interpret-only or verify-none mode, go ahead and compile small applications.
1429 * Don't bother to check if we're doing the image.
1430 */
Brian Carlstrom95b033b2014-12-03 22:29:37 -08001431 if (!image_ &&
1432 compiler_options_->IsCompilationEnabled() &&
1433 compiler_kind_ == Compiler::kQuick) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001434 size_t num_methods = 0;
1435 for (size_t i = 0; i != dex_files_.size(); ++i) {
1436 const DexFile* dex_file = dex_files_[i];
1437 CHECK(dex_file != nullptr);
1438 num_methods += dex_file->NumMethodIds();
1439 }
1440 if (num_methods <= compiler_options_->GetNumDexMethodsThreshold()) {
1441 compiler_options_->SetCompilerFilter(CompilerOptions::kSpeed);
1442 VLOG(compiler) << "Below method threshold, compiling anyways";
1443 }
1444 }
1445
1446 return true;
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001447 }
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001448
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001449 // Create and invoke the compiler driver. This will compile all the dex files.
1450 void Compile() {
1451 TimingLogger::ScopedTiming t("dex2oat Compile", timings_);
1452 compiler_phases_timings_.reset(new CumulativeLogger("compilation times"));
Vladimir Markof4da6752014-08-01 19:04:18 +01001453
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001454 // Handle and ClassLoader creation needs to come after Runtime::Create
1455 jobject class_loader = nullptr;
1456 Thread* self = Thread::Current();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001457
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001458 if (!boot_image_option_.empty()) {
1459 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001460 OpenClassPathFiles(runtime_->GetClassPathString(), dex_files_, &class_path_files_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001461 ScopedObjectAccess soa(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07001462
1463 // Classpath: first the class-path given.
1464 std::vector<const DexFile*> class_path_files;
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001465 for (auto& class_path_file : class_path_files_) {
1466 class_path_files.push_back(class_path_file.get());
1467 }
Andreas Gampe7848da42015-04-09 11:15:04 -07001468
1469 // Store the classpath we have right now.
1470 key_value_store_->Put(OatHeader::kClassPathKey,
1471 OatFile::EncodeDexFileDependencies(class_path_files));
1472
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07001473 // Then the dex files we'll compile. Thus we'll resolve the class-path first.
1474 class_path_files.insert(class_path_files.end(), dex_files_.begin(), dex_files_.end());
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001475
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07001476 class_loader = class_linker->CreatePathClassLoader(self, class_path_files);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001477 }
1478
Vladimir Marko307dac92015-10-20 11:20:09 +01001479 driver_.reset(new CompilerDriver(compiler_options_.get(),
1480 verification_results_.get(),
1481 &method_inliner_map_,
1482 compiler_kind_,
1483 instruction_set_,
1484 instruction_set_features_.get(),
1485 image_,
1486 image_classes_.release(),
1487 compiled_classes_.release(),
1488 nullptr,
1489 thread_count_,
1490 dump_stats_,
1491 dump_passes_,
1492 dump_cfg_file_name_,
1493 dump_cfg_append_,
1494 compiler_phases_timings_.get(),
1495 swap_fd_,
1496 profile_file_));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001497
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001498 driver_->CompileAll(class_loader, dex_files_, timings_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001499 }
1500
Brian Carlstrom7940e442013-07-12 13:46:57 -07001501 // Notes on the interleaving of creating the image and oat file to
1502 // ensure the references between the two are correct.
1503 //
1504 // Currently we have a memory layout that looks something like this:
1505 //
1506 // +--------------+
1507 // | image |
1508 // +--------------+
1509 // | boot oat |
1510 // +--------------+
1511 // | alloc spaces |
1512 // +--------------+
1513 //
Brian Carlstrom45602482013-07-21 22:07:55 -07001514 // There are several constraints on the loading of the image and boot.oat.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001515 //
1516 // 1. The image is expected to be loaded at an absolute address and
1517 // contains Objects with absolute pointers within the image.
1518 //
1519 // 2. There are absolute pointers from Methods in the image to their
1520 // code in the oat.
1521 //
1522 // 3. There are absolute pointers from the code in the oat to Methods
1523 // in the image.
1524 //
1525 // 4. There are absolute pointers from code in the oat to other code
1526 // in the oat.
1527 //
1528 // To get this all correct, we go through several steps.
1529 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001530 // 1. We prepare offsets for all data in the oat file and calculate
1531 // the oat data size and code size. During this stage, we also set
1532 // oat code offsets in methods for use by the image writer.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001533 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001534 // 2. We prepare offsets for the objects in the image and calculate
1535 // the image size.
1536 //
1537 // 3. We create the oat file. Originally this was just our own proprietary
1538 // file but now it is contained within an ELF dynamic object (aka an .so
1539 // file). Since we know the image size and oat data size and code size we
1540 // can prepare the ELF headers and we then know the ELF memory segment
1541 // layout and we can now resolve all references. The compiler provides
1542 // LinkerPatch information in each CompiledMethod and we resolve these,
1543 // using the layout information and image object locations provided by
1544 // image writer, as we're writing the method code.
1545 //
1546 // 4. We create the image file. It needs to know where the oat file
Brian Carlstrom7940e442013-07-12 13:46:57 -07001547 // will be loaded after itself. Originally when oat file was simply
1548 // memory mapped so we could predict where its contents were based
1549 // on the file size. Now that it is an ELF file, we need to inspect
1550 // the ELF file to understand the in memory segment layout including
Vladimir Markof4da6752014-08-01 19:04:18 +01001551 // where the oat header is located within.
1552 // TODO: We could just remember this information from step 3.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001553 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001554 // 5. We fixup the ELF program headers so that dlopen will try to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001555 // load the .so at the desired location at runtime by offsetting the
1556 // Elf32_Phdr.p_vaddr values by the desired base address.
Vladimir Markof4da6752014-08-01 19:04:18 +01001557 // TODO: Do this in step 3. We already know the layout there.
1558 //
1559 // Steps 1.-3. are done by the CreateOatFile() above, steps 4.-5.
1560 // are done by the CreateImageFile() below.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001561
1562
1563 // Write out the generated code part. Calls the OatWriter and ElfBuilder. Also prepares the
1564 // ImageWriter, if necessary.
Andreas Gampe10e477d2014-11-19 12:57:42 -08001565 // Note: Flushing (and closing) the file is the caller's responsibility, except for the failure
1566 // case (when the file will be explicitly erased).
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001567 bool CreateOatFile() {
1568 CHECK(key_value_store_.get() != nullptr);
1569
1570 TimingLogger::ScopedTiming t("dex2oat Oat", timings_);
1571
1572 std::unique_ptr<OatWriter> oat_writer;
1573 {
1574 TimingLogger::ScopedTiming t2("dex2oat OatWriter", timings_);
1575 std::string image_file_location;
1576 uint32_t image_file_location_oat_checksum = 0;
1577 uintptr_t image_file_location_oat_data_begin = 0;
1578 int32_t image_patch_delta = 0;
1579 if (image_) {
1580 PrepareImageWriter(image_base_);
1581 } else {
1582 TimingLogger::ScopedTiming t3("Loading image checksum", timings_);
1583 gc::space::ImageSpace* image_space = Runtime::Current()->GetHeap()->GetImageSpace();
1584 image_file_location_oat_checksum = image_space->GetImageHeader().GetOatChecksum();
1585 image_file_location_oat_data_begin =
1586 reinterpret_cast<uintptr_t>(image_space->GetImageHeader().GetOatDataBegin());
1587 image_file_location = image_space->GetImageFilename();
1588 image_patch_delta = image_space->GetImageHeader().GetPatchDelta();
1589 }
1590
1591 if (!image_file_location.empty()) {
1592 key_value_store_->Put(OatHeader::kImageLocationKey, image_file_location);
1593 }
1594
1595 oat_writer.reset(new OatWriter(dex_files_, image_file_location_oat_checksum,
1596 image_file_location_oat_data_begin,
1597 image_patch_delta,
Vladimir Marko307dac92015-10-20 11:20:09 +01001598 driver_.get(),
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001599 image_writer_.get(),
1600 timings_,
1601 key_value_store_.get()));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001602 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001603
1604 if (image_) {
1605 // The OatWriter constructor has already updated offsets in methods and we need to
1606 // prepare method offsets in the image address space for direct method patching.
1607 TimingLogger::ScopedTiming t2("dex2oat Prepare image address space", timings_);
1608 if (!image_writer_->PrepareImageAddressSpace()) {
1609 LOG(ERROR) << "Failed to prepare image address space.";
1610 return false;
1611 }
1612 }
1613
1614 {
1615 TimingLogger::ScopedTiming t2("dex2oat Write ELF", timings_);
1616 if (!driver_->WriteElf(android_root_, is_host_, dex_files_, oat_writer.get(),
1617 oat_file_.get())) {
1618 LOG(ERROR) << "Failed to write ELF file " << oat_file_->GetPath();
1619 return false;
1620 }
1621 }
1622
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001623 VLOG(compiler) << "Oat file written successfully (unstripped): " << oat_location_;
1624 return true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001625 }
1626
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001627 // If we are compiling an image, invoke the image creation routine. Else just skip.
1628 bool HandleImage() {
1629 if (image_) {
1630 TimingLogger::ScopedTiming t("dex2oat ImageWriter", timings_);
1631 if (!CreateImageFile()) {
1632 return false;
1633 }
1634 VLOG(compiler) << "Image written successfully: " << image_filename_;
Brian Carlstrom45602482013-07-21 22:07:55 -07001635 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001636 return true;
1637 }
1638
Andreas Gampe10e477d2014-11-19 12:57:42 -08001639 // Create a copy from unstripped to stripped.
1640 bool CopyUnstrippedToStripped() {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001641 // If we don't want to strip in place, copy from unstripped location to stripped location.
1642 // We need to strip after image creation because FixupElf needs to use .strtab.
1643 if (oat_unstripped_ != oat_stripped_) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08001644 // If the oat file is still open, flush it.
1645 if (oat_file_.get() != nullptr && oat_file_->IsOpened()) {
1646 if (!FlushCloseOatFile()) {
1647 return false;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001648 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001649 }
Andreas Gampe10e477d2014-11-19 12:57:42 -08001650
1651 TimingLogger::ScopedTiming t("dex2oat OatFile copy", timings_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001652 std::unique_ptr<File> in(OS::OpenFileForReading(oat_unstripped_.c_str()));
1653 std::unique_ptr<File> out(OS::CreateEmptyFile(oat_stripped_.c_str()));
1654 size_t buffer_size = 8192;
Dan Albert6fc59ab2014-12-11 14:09:51 -08001655 std::unique_ptr<uint8_t[]> buffer(new uint8_t[buffer_size]);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001656 while (true) {
1657 int bytes_read = TEMP_FAILURE_RETRY(read(in->Fd(), buffer.get(), buffer_size));
1658 if (bytes_read <= 0) {
1659 break;
1660 }
1661 bool write_ok = out->WriteFully(buffer.get(), bytes_read);
1662 CHECK(write_ok);
1663 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08001664 if (out->FlushCloseOrErase() != 0) {
1665 PLOG(ERROR) << "Failed to flush and close copied oat file: " << oat_stripped_;
1666 return false;
Andreas Gampe10e477d2014-11-19 12:57:42 -08001667 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001668 VLOG(compiler) << "Oat file copied successfully (stripped): " << oat_stripped_;
Nicolas Geoffrayea3fa0b2014-02-10 11:59:41 +00001669 }
Andreas Gampe10e477d2014-11-19 12:57:42 -08001670 return true;
1671 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001672
Andreas Gampe10e477d2014-11-19 12:57:42 -08001673 bool FlushOatFile() {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001674 if (oat_file_.get() != nullptr) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08001675 TimingLogger::ScopedTiming t2("dex2oat Flush ELF", timings_);
1676 if (oat_file_->Flush() != 0) {
1677 PLOG(ERROR) << "Failed to flush oat file: " << oat_location_ << " / "
1678 << oat_filename_;
1679 oat_file_->Erase();
1680 return false;
1681 }
1682 }
1683 return true;
1684 }
1685
1686 bool FlushCloseOatFile() {
1687 if (oat_file_.get() != nullptr) {
1688 std::unique_ptr<File> tmp(oat_file_.release());
1689 if (tmp->FlushCloseOrErase() != 0) {
1690 PLOG(ERROR) << "Failed to flush and close oat file: " << oat_location_ << " / "
1691 << oat_filename_;
1692 return false;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001693 }
1694 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001695 return true;
1696 }
1697
1698 void DumpTiming() {
1699 if (dump_timing_ || (dump_slow_timing_ && timings_->GetTotalNs() > MsToNs(1000))) {
1700 LOG(INFO) << Dumpable<TimingLogger>(*timings_);
1701 }
1702 if (dump_passes_) {
1703 LOG(INFO) << Dumpable<CumulativeLogger>(*driver_->GetTimingsLogger());
1704 }
1705 }
1706
1707 CompilerOptions* GetCompilerOptions() const {
1708 return compiler_options_.get();
1709 }
1710
Andreas Gampe10e477d2014-11-19 12:57:42 -08001711 bool IsImage() const {
1712 return image_;
1713 }
1714
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001715 bool IsHost() const {
1716 return is_host_;
1717 }
1718
1719 private:
1720 static size_t OpenDexFiles(const std::vector<const char*>& dex_filenames,
1721 const std::vector<const char*>& dex_locations,
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001722 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001723 DCHECK(dex_files != nullptr) << "OpenDexFiles out-param is nullptr";
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001724 size_t failure_count = 0;
1725 for (size_t i = 0; i < dex_filenames.size(); i++) {
1726 const char* dex_filename = dex_filenames[i];
1727 const char* dex_location = dex_locations[i];
1728 ATRACE_BEGIN(StringPrintf("Opening dex file '%s'", dex_filenames[i]).c_str());
1729 std::string error_msg;
1730 if (!OS::FileExists(dex_filename)) {
1731 LOG(WARNING) << "Skipping non-existent dex file '" << dex_filename << "'";
1732 continue;
1733 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001734 if (!DexFile::Open(dex_filename, dex_location, &error_msg, dex_files)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001735 LOG(WARNING) << "Failed to open .dex from file '" << dex_filename << "': " << error_msg;
1736 ++failure_count;
1737 }
1738 ATRACE_END();
1739 }
1740 return failure_count;
1741 }
1742
Andreas Gampee3712d02015-04-09 14:46:31 -07001743 // Returns true if dex_files has a dex with the named location. We compare canonical locations,
1744 // so that relative and absolute paths will match. Not caching for the dex_files isn't very
1745 // efficient, but under normal circumstances the list is neither large nor is this part too
1746 // sensitive.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001747 static bool DexFilesContains(const std::vector<const DexFile*>& dex_files,
1748 const std::string& location) {
Andreas Gampee3712d02015-04-09 14:46:31 -07001749 std::string canonical_location(DexFile::GetDexCanonicalLocation(location.c_str()));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001750 for (size_t i = 0; i < dex_files.size(); ++i) {
Andreas Gampee3712d02015-04-09 14:46:31 -07001751 if (DexFile::GetDexCanonicalLocation(dex_files[i]->GetLocation().c_str()) ==
1752 canonical_location) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001753 return true;
1754 }
1755 }
1756 return false;
1757 }
1758
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001759 // Appends to opened_dex_files any elements of class_path that dex_files
1760 // doesn't already contain. This will open those dex files as necessary.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001761 static void OpenClassPathFiles(const std::string& class_path,
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001762 std::vector<const DexFile*> dex_files,
1763 std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001764 DCHECK(opened_dex_files != nullptr) << "OpenClassPathFiles out-param is nullptr";
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001765 std::vector<std::string> parsed;
1766 Split(class_path, ':', &parsed);
1767 // Take Locks::mutator_lock_ so that lock ordering on the ClassLinker::dex_lock_ is maintained.
1768 ScopedObjectAccess soa(Thread::Current());
1769 for (size_t i = 0; i < parsed.size(); ++i) {
1770 if (DexFilesContains(dex_files, parsed[i])) {
1771 continue;
1772 }
1773 std::string error_msg;
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001774 if (!DexFile::Open(parsed[i].c_str(), parsed[i].c_str(), &error_msg, opened_dex_files)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001775 LOG(WARNING) << "Failed to open dex file '" << parsed[i] << "': " << error_msg;
1776 }
1777 }
1778 }
1779
1780 // Create a runtime necessary for compilation.
1781 bool CreateRuntime(const RuntimeOptions& runtime_options)
1782 SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_) {
1783 if (!Runtime::Create(runtime_options, false)) {
1784 LOG(ERROR) << "Failed to create runtime";
1785 return false;
1786 }
Vladimir Marko307dac92015-10-20 11:20:09 +01001787 runtime_.reset(Runtime::Current());
1788 runtime_->SetInstructionSet(instruction_set_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001789 for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
1790 Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i);
Vladimir Marko307dac92015-10-20 11:20:09 +01001791 if (!runtime_->HasCalleeSaveMethod(type)) {
1792 runtime_->SetCalleeSaveMethod(runtime_->CreateCalleeSaveMethod(), type);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001793 }
1794 }
Vladimir Marko307dac92015-10-20 11:20:09 +01001795 runtime_->GetClassLinker()->FixupDexCaches(runtime_->GetResolutionMethod());
Andreas Gampe2969bcd2015-03-09 12:57:41 -07001796
1797 // Initialize maps for unstarted runtime. This needs to be here, as running clinits needs this
1798 // set up.
Andreas Gampe799681b2015-05-15 19:24:12 -07001799 interpreter::UnstartedRuntime::Initialize();
Andreas Gampe2969bcd2015-03-09 12:57:41 -07001800
Vladimir Marko307dac92015-10-20 11:20:09 +01001801 runtime_->GetClassLinker()->RunRootClinits();
Andreas Gampe2969bcd2015-03-09 12:57:41 -07001802
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001803 return true;
1804 }
1805
1806 void PrepareImageWriter(uintptr_t image_base) {
1807 image_writer_.reset(new ImageWriter(*driver_, image_base, compiler_options_->GetCompilePic()));
1808 }
1809
1810 // Let the ImageWriter write the image file. If we do not compile PIC, also fix up the oat file.
1811 bool CreateImageFile()
Mathieu Chartier90443472015-07-16 20:32:27 -07001812 REQUIRES(!Locks::mutator_lock_) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001813 CHECK(image_writer_ != nullptr);
1814 if (!image_writer_->Write(image_filename_, oat_unstripped_, oat_location_)) {
1815 LOG(ERROR) << "Failed to create image file " << image_filename_;
1816 return false;
1817 }
1818 uintptr_t oat_data_begin = image_writer_->GetOatDataBegin();
1819
1820 // Destroy ImageWriter before doing FixupElf.
1821 image_writer_.reset();
1822
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001823 // Do not fix up the ELF file if we are --compile-pic
1824 if (!compiler_options_->GetCompilePic()) {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001825 std::unique_ptr<File> oat_file(OS::OpenFileReadWrite(oat_unstripped_.c_str()));
1826 if (oat_file.get() == nullptr) {
1827 PLOG(ERROR) << "Failed to open ELF file: " << oat_unstripped_;
1828 return false;
1829 }
1830
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001831 if (!ElfWriter::Fixup(oat_file.get(), oat_data_begin)) {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001832 oat_file->Erase();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001833 LOG(ERROR) << "Failed to fixup ELF file " << oat_file->GetPath();
1834 return false;
1835 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001836
1837 if (oat_file->FlushCloseOrErase()) {
1838 PLOG(ERROR) << "Failed to flush and close fixed ELF file " << oat_file->GetPath();
1839 return false;
1840 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001841 }
1842
1843 return true;
1844 }
1845
1846 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001847 static std::unordered_set<std::string>* ReadImageClassesFromFile(
1848 const char* image_classes_filename) {
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001849 std::function<std::string(const char*)> process = DotToDescriptor;
1850 return ReadCommentedInputFromFile(image_classes_filename, &process);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001851 }
1852
1853 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001854 static std::unordered_set<std::string>* ReadImageClassesFromZip(
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001855 const char* zip_filename,
1856 const char* image_classes_filename,
1857 std::string* error_msg) {
1858 std::function<std::string(const char*)> process = DotToDescriptor;
1859 return ReadCommentedInputFromZip(zip_filename, image_classes_filename, &process, error_msg);
1860 }
1861
1862 // Read lines from the given file, dropping comments and empty lines. Post-process each line with
1863 // the given function.
1864 static std::unordered_set<std::string>* ReadCommentedInputFromFile(
1865 const char* input_filename, std::function<std::string(const char*)>* process) {
1866 std::unique_ptr<std::ifstream> input_file(new std::ifstream(input_filename, std::ifstream::in));
1867 if (input_file.get() == nullptr) {
1868 LOG(ERROR) << "Failed to open input file " << input_filename;
1869 return nullptr;
1870 }
1871 std::unique_ptr<std::unordered_set<std::string>> result(
1872 ReadCommentedInputStream(*input_file, process));
1873 input_file->close();
1874 return result.release();
1875 }
1876
1877 // Read lines from the given file from the given zip file, dropping comments and empty lines.
1878 // Post-process each line with the given function.
1879 static std::unordered_set<std::string>* ReadCommentedInputFromZip(
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001880 const char* zip_filename,
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001881 const char* input_filename,
1882 std::function<std::string(const char*)>* process,
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001883 std::string* error_msg) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001884 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::Open(zip_filename, error_msg));
1885 if (zip_archive.get() == nullptr) {
1886 return nullptr;
1887 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001888 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(input_filename, error_msg));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001889 if (zip_entry.get() == nullptr) {
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001890 *error_msg = StringPrintf("Failed to find '%s' within '%s': %s", input_filename,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001891 zip_filename, error_msg->c_str());
1892 return nullptr;
1893 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001894 std::unique_ptr<MemMap> input_file(zip_entry->ExtractToMemMap(zip_filename,
1895 input_filename,
1896 error_msg));
1897 if (input_file.get() == nullptr) {
1898 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", input_filename,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001899 zip_filename, error_msg->c_str());
1900 return nullptr;
1901 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001902 const std::string input_string(reinterpret_cast<char*>(input_file->Begin()),
1903 input_file->Size());
1904 std::istringstream input_stream(input_string);
1905 return ReadCommentedInputStream(input_stream, process);
1906 }
1907
1908 // Read lines from the given stream, dropping comments and empty lines. Post-process each line
1909 // with the given function.
1910 static std::unordered_set<std::string>* ReadCommentedInputStream(
1911 std::istream& in_stream,
1912 std::function<std::string(const char*)>* process) {
1913 std::unique_ptr<std::unordered_set<std::string>> image_classes(
1914 new std::unordered_set<std::string>);
1915 while (in_stream.good()) {
1916 std::string dot;
1917 std::getline(in_stream, dot);
1918 if (StartsWith(dot, "#") || dot.empty()) {
1919 continue;
1920 }
1921 if (process != nullptr) {
1922 std::string descriptor((*process)(dot.c_str()));
1923 image_classes->insert(descriptor);
1924 } else {
1925 image_classes->insert(dot);
1926 }
1927 }
1928 return image_classes.release();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001929 }
1930
Mathieu Chartier49285c52014-12-02 15:43:48 -08001931 void LogCompletionTime() {
Andreas Gampe1d00add2015-02-27 19:35:46 -08001932 // Note: when creation of a runtime fails, e.g., when trying to compile an app but when there
1933 // is no image, there won't be a Runtime::Current().
Brian Carlstroma11a34c2015-03-06 08:44:45 -08001934 // Note: driver creation can fail when loading an invalid dex file.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001935 LOG(INFO) << "dex2oat took " << PrettyDuration(NanoTime() - start_ns_)
Mathieu Chartierab972ef2014-12-03 17:38:22 -08001936 << " (threads: " << thread_count_ << ") "
Andreas Gampe3f30e122015-09-17 14:03:21 -07001937 << ((Runtime::Current() != nullptr && driver_ != nullptr) ?
Andreas Gampe1d00add2015-02-27 19:35:46 -08001938 driver_->GetMemoryUsageString(kIsDebugBuild || VLOG_IS_ON(compiler)) :
1939 "");
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001940 }
1941
1942 std::unique_ptr<CompilerOptions> compiler_options_;
1943 Compiler::Kind compiler_kind_;
1944
1945 InstructionSet instruction_set_;
1946 std::unique_ptr<const InstructionSetFeatures> instruction_set_features_;
1947
1948 std::unique_ptr<SafeMap<std::string, std::string> > key_value_store_;
1949
Vladimir Marko307dac92015-10-20 11:20:09 +01001950 std::unique_ptr<VerificationResults> verification_results_;
Andreas Gampe3f30e122015-09-17 14:03:21 -07001951
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001952 DexFileToMethodInlinerMap method_inliner_map_;
1953 std::unique_ptr<QuickCompilerCallbacks> callbacks_;
1954
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001955 // Ownership for the class path files.
1956 std::vector<std::unique_ptr<const DexFile>> class_path_files_;
1957
Vladimir Marko307dac92015-10-20 11:20:09 +01001958 std::unique_ptr<Runtime> runtime_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001959
1960 size_t thread_count_;
1961 uint64_t start_ns_;
1962 std::unique_ptr<WatchDog> watchdog_;
1963 std::unique_ptr<File> oat_file_;
1964 std::string oat_stripped_;
1965 std::string oat_unstripped_;
1966 std::string oat_location_;
1967 std::string oat_filename_;
1968 int oat_fd_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001969 std::vector<const char*> dex_filenames_;
1970 std::vector<const char*> dex_locations_;
1971 int zip_fd_;
1972 std::string zip_location_;
1973 std::string boot_image_option_;
1974 std::vector<const char*> runtime_args_;
1975 std::string image_filename_;
1976 uintptr_t image_base_;
1977 const char* image_classes_zip_filename_;
1978 const char* image_classes_filename_;
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001979 const char* compiled_classes_zip_filename_;
1980 const char* compiled_classes_filename_;
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001981 const char* compiled_methods_zip_filename_;
1982 const char* compiled_methods_filename_;
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001983 std::unique_ptr<std::unordered_set<std::string>> image_classes_;
1984 std::unique_ptr<std::unordered_set<std::string>> compiled_classes_;
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001985 std::unique_ptr<std::unordered_set<std::string>> compiled_methods_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001986 bool image_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001987 bool is_host_;
1988 std::string android_root_;
1989 std::vector<const DexFile*> dex_files_;
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001990 std::vector<jobject> dex_caches_;
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001991 std::vector<std::unique_ptr<const DexFile>> opened_dex_files_;
Andreas Gampe3f30e122015-09-17 14:03:21 -07001992
Vladimir Marko307dac92015-10-20 11:20:09 +01001993 std::unique_ptr<ImageWriter> image_writer_;
1994 std::unique_ptr<CompilerDriver> driver_;
Andreas Gampe3f30e122015-09-17 14:03:21 -07001995
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001996 std::vector<std::string> verbose_methods_;
1997 bool dump_stats_;
1998 bool dump_passes_;
1999 bool dump_timing_;
2000 bool dump_slow_timing_;
David Brazdil866c0312015-01-13 21:21:31 +00002001 std::string dump_cfg_file_name_;
Calin Juravle87000a92015-08-24 15:34:44 +01002002 bool dump_cfg_append_;
Andreas Gampee21dc3d2014-12-08 16:59:43 -08002003 std::string swap_file_name_;
2004 int swap_fd_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002005 std::string profile_file_; // Profile file to use
2006 TimingLogger* timings_;
2007 std::unique_ptr<CumulativeLogger> compiler_phases_timings_;
Andreas Gampedbfe2542014-11-25 22:21:42 -08002008 std::unique_ptr<std::ostream> init_failure_output_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002009
2010 DISALLOW_IMPLICIT_CONSTRUCTORS(Dex2Oat);
2011};
2012
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002013static void b13564922() {
2014#if defined(__linux__) && defined(__arm__)
2015 int major, minor;
2016 struct utsname uts;
2017 if (uname(&uts) != -1 &&
2018 sscanf(uts.release, "%d.%d", &major, &minor) == 2 &&
2019 ((major < 3) || ((major == 3) && (minor < 4)))) {
2020 // Kernels before 3.4 don't handle the ASLR well and we can run out of address
2021 // space (http://b/13564922). Work around the issue by inhibiting further mmap() randomization.
2022 int old_personality = personality(0xffffffff);
2023 if ((old_personality & ADDR_NO_RANDOMIZE) == 0) {
2024 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
2025 if (new_personality == -1) {
2026 LOG(WARNING) << "personality(. | ADDR_NO_RANDOMIZE) failed.";
2027 }
2028 }
2029 }
2030#endif
2031}
2032
Andreas Gampe10e477d2014-11-19 12:57:42 -08002033static int CompileImage(Dex2Oat& dex2oat) {
2034 dex2oat.Compile();
2035
2036 // Create the boot.oat.
2037 if (!dex2oat.CreateOatFile()) {
Andreas Gampea650e702014-12-03 14:28:02 -08002038 dex2oat.EraseOatFile();
Andreas Gampe10e477d2014-11-19 12:57:42 -08002039 return EXIT_FAILURE;
2040 }
2041
2042 // Flush and close the boot.oat. We always expect the output file by name, and it will be
2043 // re-opened from the unstripped name.
2044 if (!dex2oat.FlushCloseOatFile()) {
2045 return EXIT_FAILURE;
2046 }
2047
2048 // Creates the boot.art and patches the boot.oat.
2049 if (!dex2oat.HandleImage()) {
2050 return EXIT_FAILURE;
2051 }
2052
2053 // When given --host, finish early without stripping.
2054 if (dex2oat.IsHost()) {
2055 dex2oat.DumpTiming();
2056 return EXIT_SUCCESS;
2057 }
2058
2059 // Copy unstripped to stripped location, if necessary.
2060 if (!dex2oat.CopyUnstrippedToStripped()) {
2061 return EXIT_FAILURE;
2062 }
2063
Andreas Gampe10e477d2014-11-19 12:57:42 -08002064 // FlushClose again, as stripping might have re-opened the oat file.
2065 if (!dex2oat.FlushCloseOatFile()) {
2066 return EXIT_FAILURE;
2067 }
2068
2069 dex2oat.DumpTiming();
2070 return EXIT_SUCCESS;
2071}
2072
2073static int CompileApp(Dex2Oat& dex2oat) {
2074 dex2oat.Compile();
2075
2076 // Create the app oat.
2077 if (!dex2oat.CreateOatFile()) {
Andreas Gampea650e702014-12-03 14:28:02 -08002078 dex2oat.EraseOatFile();
Andreas Gampe10e477d2014-11-19 12:57:42 -08002079 return EXIT_FAILURE;
2080 }
2081
2082 // Do not close the oat file here. We might haven gotten the output file by file descriptor,
2083 // which we would lose.
2084 if (!dex2oat.FlushOatFile()) {
2085 return EXIT_FAILURE;
2086 }
2087
2088 // When given --host, finish early without stripping.
2089 if (dex2oat.IsHost()) {
2090 if (!dex2oat.FlushCloseOatFile()) {
2091 return EXIT_FAILURE;
2092 }
2093
2094 dex2oat.DumpTiming();
2095 return EXIT_SUCCESS;
2096 }
2097
2098 // Copy unstripped to stripped location, if necessary. This will implicitly flush & close the
2099 // unstripped version. If this is given, we expect to be able to open writable files by name.
2100 if (!dex2oat.CopyUnstrippedToStripped()) {
2101 return EXIT_FAILURE;
2102 }
2103
Andreas Gampe10e477d2014-11-19 12:57:42 -08002104 // Flush and close the file.
2105 if (!dex2oat.FlushCloseOatFile()) {
2106 return EXIT_FAILURE;
2107 }
2108
2109 dex2oat.DumpTiming();
2110 return EXIT_SUCCESS;
2111}
2112
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002113static int dex2oat(int argc, char** argv) {
2114 b13564922();
2115
2116 TimingLogger timings("compiler", false, false);
2117
2118 Dex2Oat dex2oat(&timings);
2119
2120 // Parse arguments. Argument mistakes will lead to exit(EXIT_FAILURE) in UsageError.
2121 dex2oat.ParseArgs(argc, argv);
2122
2123 // Check early that the result of compilation can be written
2124 if (!dex2oat.OpenFile()) {
2125 return EXIT_FAILURE;
2126 }
2127
Andreas Gampe046c7062015-05-18 23:22:54 -07002128 // Print the complete line when any of the following is true:
2129 // 1) Debug build
2130 // 2) Compiling an image
2131 // 3) Compiling with --host
2132 // 4) Compiling on the host (not a target build)
2133 // Otherwise, print a stripped command line.
2134 if (kIsDebugBuild || dex2oat.IsImage() || dex2oat.IsHost() || !kIsTargetBuild) {
2135 LOG(INFO) << CommandLine();
2136 } else {
2137 LOG(INFO) << StrippedCommandLine();
2138 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002139
2140 if (!dex2oat.Setup()) {
Andreas Gampea650e702014-12-03 14:28:02 -08002141 dex2oat.EraseOatFile();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002142 return EXIT_FAILURE;
2143 }
2144
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002145 bool result;
Andreas Gampe10e477d2014-11-19 12:57:42 -08002146 if (dex2oat.IsImage()) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002147 result = CompileImage(dex2oat);
Andreas Gampe10e477d2014-11-19 12:57:42 -08002148 } else {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002149 result = CompileApp(dex2oat);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002150 }
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07002151
2152 dex2oat.Shutdown();
2153 return result;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002154}
Brian Carlstrom7934ac22013-07-26 10:54:15 -07002155} // namespace art
Brian Carlstrom7940e442013-07-12 13:46:57 -07002156
2157int main(int argc, char** argv) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002158 int result = art::dex2oat(argc, argv);
2159 // Everything was done, do an explicit exit here to avoid running Runtime destructors that take
2160 // time (bug 10645725) unless we're a debug build or running on valgrind. Note: The Dex2Oat class
2161 // should not destruct the runtime in this case.
Evgenii Stepanov1e133742015-05-20 12:30:59 -07002162 if (!art::kIsDebugBuild && (RUNNING_ON_MEMORY_TOOL == 0)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08002163 exit(result);
2164 }
2165 return result;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002166}