blob: e0f367ed8b860ffe619ef217806ee662baf6d948 [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>
Ian Rogers2672a9f2013-09-05 17:24:22 -070021#include <valgrind.h>
Brian Carlstrom7940e442013-07-12 13:46:57 -070022
23#include <fstream>
24#include <iostream>
25#include <sstream>
26#include <string>
Andreas Gampeb1fcead2015-04-20 18:53:51 -070027#include <unordered_set>
Brian Carlstrom7940e442013-07-12 13:46:57 -070028#include <vector>
29
Vladimir Markof94b7812014-06-05 15:48:04 +010030#if defined(__linux__) && defined(__arm__)
31#include <sys/personality.h>
32#include <sys/utsname.h>
33#endif
34
Ian Rogerscf7f1912014-10-22 22:06:39 -070035#define ATRACE_TAG ATRACE_TAG_DALVIK
Ian Rogersd582fa42014-11-05 23:46:43 -080036#include <cutils/trace.h>
Ian Rogerscf7f1912014-10-22 22:06:39 -070037
Ian Rogersd582fa42014-11-05 23:46:43 -080038#include "arch/instruction_set_features.h"
Andreas Gampec5a3ea72015-01-13 16:41:53 -080039#include "arch/mips/instruction_set_features_mips.h"
Ian Rogersc7dd2952014-10-21 23:31:19 -070040#include "base/dumpable.h"
Andreas Gampe794ad762015-02-23 08:12:24 -080041#include "base/macros.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070042#include "base/stl_util.h"
43#include "base/stringpiece.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010044#include "base/time_utils.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070045#include "base/timing_logger.h"
46#include "base/unix_file/fd_file.h"
47#include "class_linker.h"
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +000048#include "compiler.h"
Vladimir Marko2b5eaa22013-12-13 13:59:30 +000049#include "compiler_callbacks.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070050#include "dex_file-inl.h"
Mathieu Chartier5bdab122015-01-26 18:30:19 -080051#include "dex/pass_manager.h"
Vladimir Markoc7f83202014-01-24 17:55:18 +000052#include "dex/verification_results.h"
Ian Rogerse63db272014-07-15 15:36:11 -070053#include "dex/quick_compiler_callbacks.h"
54#include "dex/quick/dex_file_to_method_inliner_map.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070055#include "driver/compiler_driver.h"
Brian Carlstrom6449c622014-02-10 23:48:36 -080056#include "driver/compiler_options.h"
Andreas Gampe88ec7f42014-11-05 10:18:32 -080057#include "elf_file.h"
Tong Shen62d1ca32014-09-03 17:24:56 -070058#include "elf_writer.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070059#include "gc/space/image_space.h"
60#include "gc/space/space-inl.h"
61#include "image_writer.h"
Andreas Gampe2969bcd2015-03-09 12:57:41 -070062#include "interpreter/unstarted_runtime.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070063#include "leb128.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070064#include "mirror/art_method-inl.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
Brian Carlstrom7940e442013-07-12 13:46:57 -070092static void UsageErrorV(const char* fmt, va_list ap) {
93 std::string error;
94 StringAppendV(&error, fmt, ap);
95 LOG(ERROR) << error;
96}
97
98static void UsageError(const char* fmt, ...) {
99 va_list ap;
100 va_start(ap, fmt);
101 UsageErrorV(fmt, ap);
102 va_end(ap);
103}
104
Andreas Gampe794ad762015-02-23 08:12:24 -0800105NO_RETURN static void Usage(const char* fmt, ...) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700106 va_list ap;
107 va_start(ap, fmt);
108 UsageErrorV(fmt, ap);
109 va_end(ap);
110
Brian Carlstrom6449c622014-02-10 23:48:36 -0800111 UsageError("Command: %s", CommandLine().c_str());
112
Brian Carlstrom7940e442013-07-12 13:46:57 -0700113 UsageError("Usage: dex2oat [options]...");
114 UsageError("");
Jean-Philippe Halimi3d329d72015-03-23 14:09:48 +0100115 UsageError(" -j<number>: specifies the number of threads used for compilation.");
116 UsageError(" Default is the number of detected hardware threads available on the");
117 UsageError(" host system.");
118 UsageError(" Example: -j12");
119 UsageError("");
Richard Uhlere934df22015-03-17 11:26:16 -0700120 UsageError(" --dex-file=<dex-file>: specifies a .dex, .jar, or .apk file to compile.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700121 UsageError(" Example: --dex-file=/system/framework/core.jar");
122 UsageError("");
Richard Uhlere934df22015-03-17 11:26:16 -0700123 UsageError(" --dex-location=<dex-location>: specifies an alternative dex location to");
124 UsageError(" encode in the oat file for the corresponding --dex-file argument.");
125 UsageError(" Example: --dex-file=/home/build/out/system/framework/core.jar");
126 UsageError(" --dex-location=/system/framework/core.jar");
127 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700128 UsageError(" --zip-fd=<file-descriptor>: specifies a file descriptor of a zip file");
129 UsageError(" containing a classes.dex file to compile.");
130 UsageError(" Example: --zip-fd=5");
131 UsageError("");
Brian Carlstrom45602482013-07-21 22:07:55 -0700132 UsageError(" --zip-location=<zip-location>: specifies a symbolic name for the file");
133 UsageError(" corresponding to the file descriptor specified by --zip-fd.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700134 UsageError(" Example: --zip-location=/system/app/Calculator.apk");
135 UsageError("");
136 UsageError(" --oat-file=<file.oat>: specifies the oat output destination via a filename.");
137 UsageError(" Example: --oat-file=/system/framework/boot.oat");
138 UsageError("");
139 UsageError(" --oat-fd=<number>: specifies the oat output destination via a file descriptor.");
Wonil Kim9cb554a2014-04-28 11:26:55 +0900140 UsageError(" Example: --oat-fd=6");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700141 UsageError("");
142 UsageError(" --oat-location=<oat-name>: specifies a symbolic name for the file corresponding");
143 UsageError(" to the file descriptor specified by --oat-fd.");
144 UsageError(" Example: --oat-location=/data/dalvik-cache/system@app@Calculator.apk.oat");
145 UsageError("");
146 UsageError(" --oat-symbols=<file.oat>: specifies the oat output destination with full symbols.");
147 UsageError(" Example: --oat-symbols=/symbols/system/framework/boot.oat");
148 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700149 UsageError(" --image=<file.art>: specifies the output image filename.");
150 UsageError(" Example: --image=/system/framework/boot.art");
151 UsageError("");
152 UsageError(" --image-classes=<classname-file>: specifies classes to include in an image.");
153 UsageError(" Example: --image=frameworks/base/preloaded-classes");
154 UsageError("");
155 UsageError(" --base=<hex-address>: specifies the base address when creating a boot image.");
156 UsageError(" Example: --base=0x50000000");
157 UsageError("");
158 UsageError(" --boot-image=<file.art>: provide the image file for the boot class path.");
159 UsageError(" Example: --boot-image=/system/framework/boot.art");
Nicolas Geoffray9583fbc2014-02-28 15:21:07 +0000160 UsageError(" Default: $ANDROID_ROOT/system/framework/boot.art");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700161 UsageError("");
162 UsageError(" --android-root=<path>: used to locate libraries for portable linking.");
163 UsageError(" Example: --android-root=out/host/linux-x86");
164 UsageError(" Default: $ANDROID_ROOT");
165 UsageError("");
Andreas Gampe57b34292015-01-14 15:45:59 -0800166 UsageError(" --instruction-set=(arm|arm64|mips|mips64|x86|x86_64): compile for a particular");
Alex Light53cb16b2014-06-12 11:26:29 -0700167 UsageError(" instruction set.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700168 UsageError(" Example: --instruction-set=x86");
169 UsageError(" Default: arm");
170 UsageError("");
Dave Allison70202782013-10-22 17:52:19 -0700171 UsageError(" --instruction-set-features=...,: Specify instruction set features");
172 UsageError(" Example: --instruction-set-features=div");
173 UsageError(" Default: default");
174 UsageError("");
Igor Murashkin46774762014-10-22 11:37:02 -0700175 UsageError(" --compile-pic: Force indirect use of code, methods, and classes");
176 UsageError(" Default: disabled");
177 UsageError("");
Elliott Hughes956af0f2014-12-11 14:34:28 -0800178 UsageError(" --compiler-backend=(Quick|Optimizing): select compiler backend");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700179 UsageError(" set.");
Elliott Hughes956af0f2014-12-11 14:34:28 -0800180 UsageError(" Example: --compiler-backend=Optimizing");
181 if (kUseOptimizingCompiler) {
Nicolas Geoffray4586fb62014-11-28 16:22:11 +0000182 UsageError(" Default: Optimizing");
183 } else {
184 UsageError(" Default: Quick");
185 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700186 UsageError("");
Nicolas Geoffray88157ef2014-09-12 10:29:53 +0100187 UsageError(" --compiler-filter="
188 "(verify-none"
189 "|interpret-only"
190 "|space"
191 "|balanced"
192 "|speed"
193 "|everything"
194 "|time):");
Jeff Hao4a200f52014-04-01 14:58:49 -0700195 UsageError(" select compiler filter.");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800196 UsageError(" Example: --compiler-filter=everything");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800197 UsageError(" Default: speed");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800198 UsageError("");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800199 UsageError(" --huge-method-max=<method-instruction-count>: threshold size for a huge");
200 UsageError(" method for compiler filter tuning.");
201 UsageError(" Example: --huge-method-max=%d", CompilerOptions::kDefaultHugeMethodThreshold);
202 UsageError(" Default: %d", CompilerOptions::kDefaultHugeMethodThreshold);
203 UsageError("");
204 UsageError(" --large-method-max=<method-instruction-count>: threshold size for a large");
205 UsageError(" method for compiler filter tuning.");
206 UsageError(" Example: --large-method-max=%d", CompilerOptions::kDefaultLargeMethodThreshold);
207 UsageError(" Default: %d", CompilerOptions::kDefaultLargeMethodThreshold);
208 UsageError("");
209 UsageError(" --small-method-max=<method-instruction-count>: threshold size for a small");
210 UsageError(" method for compiler filter tuning.");
211 UsageError(" Example: --small-method-max=%d", CompilerOptions::kDefaultSmallMethodThreshold);
212 UsageError(" Default: %d", CompilerOptions::kDefaultSmallMethodThreshold);
213 UsageError("");
214 UsageError(" --tiny-method-max=<method-instruction-count>: threshold size for a tiny");
215 UsageError(" method for compiler filter tuning.");
216 UsageError(" Example: --tiny-method-max=%d", CompilerOptions::kDefaultTinyMethodThreshold);
217 UsageError(" Default: %d", CompilerOptions::kDefaultTinyMethodThreshold);
218 UsageError("");
219 UsageError(" --num-dex-methods=<method-count>: threshold size for a small dex file for");
220 UsageError(" compiler filter tuning. If the input has fewer than this many methods");
Jeff Hao4a200f52014-04-01 14:58:49 -0700221 UsageError(" and the filter is not interpret-only or verify-none, overrides the");
222 UsageError(" filter to use speed");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800223 UsageError(" Example: --num-dex-method=%d", CompilerOptions::kDefaultNumDexMethodsThreshold);
224 UsageError(" Default: %d", CompilerOptions::kDefaultNumDexMethodsThreshold);
225 UsageError("");
Ian Rogers46398602013-08-20 07:50:36 -0700226 UsageError(" --dump-timing: display a breakdown of where time was spent");
227 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700228 UsageError(" --include-patch-information: Include patching information so the generated code");
229 UsageError(" can have its base address moved without full recompilation.");
230 UsageError("");
231 UsageError(" --no-include-patch-information: Do not include patching information.");
232 UsageError("");
Alex Light78382fa2014-06-06 15:45:32 -0700233 UsageError(" --include-debug-symbols: Include ELF symbols in this oat file");
234 UsageError("");
235 UsageError(" --no-include-debug-symbols: Do not include ELF symbols in this oat file");
236 UsageError("");
David Srbecky8dc73242015-04-12 11:40:39 +0100237 UsageError(" --include-cfi: Include call frame information in the .eh_frame section.");
238 UsageError(" The --include-debug-symbols option implies --include-cfi.");
239 UsageError("");
240 UsageError(" --no-include-cfi: Do not include call frame information in the .eh_frame section.");
241 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700242 UsageError(" --runtime-arg <argument>: used to specify various arguments for the runtime,");
243 UsageError(" such as initial heap size, maximum heap size, and verbose output.");
244 UsageError(" Use a separate --runtime-arg switch for each argument.");
245 UsageError(" Example: --runtime-arg -Xms256m");
Jeff Hao4a200f52014-04-01 14:58:49 -0700246 UsageError("");
Dave Allisond6ed6422014-04-09 23:36:15 +0000247 UsageError(" --profile-file=<filename>: specify profiler output file to use for compilation.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700248 UsageError("");
Chao-ying Fucd8ce662014-03-11 14:57:19 -0700249 UsageError(" --print-pass-names: print a list of pass names");
250 UsageError("");
251 UsageError(" --disable-passes=<pass-names>: disable one or more passes separated by comma.");
252 UsageError(" Example: --disable-passes=UseCount,BBOptimizations");
253 UsageError("");
Razvan A Lupusorubd25d4b2014-07-02 18:16:51 -0700254 UsageError(" --print-pass-options: print a list of passes that have configurable options along "
255 "with the setting.");
256 UsageError(" Will print default if no overridden setting exists.");
257 UsageError("");
258 UsageError(" --pass-options=Pass1Name:Pass1OptionName:Pass1Option#,"
259 "Pass2Name:Pass2OptionName:Pass2Option#");
260 UsageError(" Used to specify a pass specific option. The setting itself must be integer.");
261 UsageError(" Separator used between options is a comma.");
262 UsageError("");
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800263 UsageError(" --swap-file=<file-name>: specifies a file to use for swap.");
264 UsageError(" Example: --swap-file=/data/tmp/swap.001");
265 UsageError("");
266 UsageError(" --swap-fd=<file-descriptor>: specifies a file to use for swap (by descriptor).");
267 UsageError(" Example: --swap-fd=10");
268 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700269 std::cerr << "See log for usage error information\n";
270 exit(EXIT_FAILURE);
271}
272
Brian Carlstrom7940e442013-07-12 13:46:57 -0700273// The primary goal of the watchdog is to prevent stuck build servers
274// during development when fatal aborts lead to a cascade of failures
275// that result in a deadlock.
276class WatchDog {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800277// WatchDog defines its own CHECK_PTHREAD_CALL to avoid using LOG which uses locks
Brian Carlstrom7940e442013-07-12 13:46:57 -0700278#undef CHECK_PTHREAD_CALL
279#define CHECK_WATCH_DOG_PTHREAD_CALL(call, args, what) \
280 do { \
281 int rc = call args; \
282 if (rc != 0) { \
283 errno = rc; \
284 std::string message(# call); \
285 message += " failed for "; \
286 message += reason; \
287 Fatal(message); \
288 } \
289 } while (false)
290
291 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -0700292 explicit WatchDog(bool is_watch_dog_enabled) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700293 is_watch_dog_enabled_ = is_watch_dog_enabled;
294 if (!is_watch_dog_enabled_) {
295 return;
296 }
297 shutting_down_ = false;
298 const char* reason = "dex2oat watch dog thread startup";
Kenny Root51316382014-05-13 14:59:37 -0700299 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_init, (&mutex_, nullptr), reason);
300 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_init, (&cond_, nullptr), reason);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700301 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_init, (&attr_), reason);
302 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_create, (&pthread_, &attr_, &CallBack, this), reason);
303 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_destroy, (&attr_), reason);
304 }
305 ~WatchDog() {
306 if (!is_watch_dog_enabled_) {
307 return;
308 }
309 const char* reason = "dex2oat watch dog thread shutdown";
310 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
311 shutting_down_ = true;
312 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_signal, (&cond_), reason);
313 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
314
Kenny Root51316382014-05-13 14:59:37 -0700315 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_join, (pthread_, nullptr), reason);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700316
317 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_destroy, (&cond_), reason);
318 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_destroy, (&mutex_), reason);
319 }
320
321 private:
322 static void* CallBack(void* arg) {
323 WatchDog* self = reinterpret_cast<WatchDog*>(arg);
324 ::art::SetThreadName("dex2oat watch dog");
325 self->Wait();
Kenny Root51316382014-05-13 14:59:37 -0700326 return nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700327 }
328
Andreas Gampe794ad762015-02-23 08:12:24 -0800329 NO_RETURN static void Fatal(const std::string& message) {
Andreas Gamped687e372015-04-28 23:16:03 -0700330 // TODO: When we can guarantee it won't prevent shutdown in error cases, move to LOG. However,
331 // it's rather easy to hang in unwinding.
332 // LogLine also avoids ART logging lock issues, as it's really only a wrapper around
333 // logcat logging or stderr output.
334 LogMessage::LogLine(__FILE__, __LINE__, LogSeverity::FATAL, message.c_str());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700335 exit(1);
336 }
337
338 void Wait() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700339 // TODO: tune the multiplier for GC verification, the following is just to make the timeout
340 // large.
Andreas Gamped687e372015-04-28 23:16:03 -0700341 constexpr int64_t multiplier = kVerifyObjectSupport > kVerifyObjectModeFast ? 100 : 1;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700342 timespec timeout_ts;
343 InitTimeSpec(true, CLOCK_REALTIME, multiplier * kWatchDogTimeoutSeconds * 1000, 0, &timeout_ts);
344 const char* reason = "dex2oat watch dog thread waiting";
345 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
346 while (!shutting_down_) {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800347 int rc = TEMP_FAILURE_RETRY(pthread_cond_timedwait(&cond_, &mutex_, &timeout_ts));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700348 if (rc == ETIMEDOUT) {
Andreas Gamped687e372015-04-28 23:16:03 -0700349 Fatal(StringPrintf("dex2oat did not finish after %" PRId64 " seconds",
350 kWatchDogTimeoutSeconds));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700351 } else if (rc != 0) {
352 std::string message(StringPrintf("pthread_cond_timedwait failed: %s",
353 strerror(errno)));
354 Fatal(message.c_str());
355 }
356 }
357 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
358 }
359
360 // 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 -0700361 // Debug builds are slower so they have larger timeouts.
Andreas Gamped687e372015-04-28 23:16:03 -0700362 static constexpr int64_t kSlowdownFactor = kIsDebugBuild ? 5U : 1U;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800363
Andreas Gamped687e372015-04-28 23:16:03 -0700364 // 10 minutes scaled by kSlowdownFactor.
365 static constexpr int64_t kWatchDogTimeoutSeconds = kSlowdownFactor * 10 * 60;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700366
367 bool is_watch_dog_enabled_;
368 bool shutting_down_;
369 // TODO: Switch to Mutex when we can guarantee it won't prevent shutdown in error cases.
370 pthread_mutex_t mutex_;
371 pthread_cond_t cond_;
372 pthread_attr_t attr_;
373 pthread_t pthread_;
374};
Brian Carlstrom7940e442013-07-12 13:46:57 -0700375
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800376static void ParseStringAfterChar(const std::string& s, char c, std::string* parsed_value) {
Calin Juravlec1b643c2014-05-30 23:44:11 +0100377 std::string::size_type colon = s.find(c);
378 if (colon == std::string::npos) {
379 Usage("Missing char %c in option %s\n", c, s.c_str());
380 }
381 // Add one to remove the char we were trimming until.
382 *parsed_value = s.substr(colon + 1);
383}
384
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800385static void ParseDouble(const std::string& option, char after_char, double min, double max,
386 double* parsed_value) {
Calin Juravlec1b643c2014-05-30 23:44:11 +0100387 std::string substring;
388 ParseStringAfterChar(option, after_char, &substring);
389 bool sane_val = true;
390 double value;
391 if (false) {
392 // TODO: this doesn't seem to work on the emulator. b/15114595
393 std::stringstream iss(substring);
394 iss >> value;
395 // Ensure that we have a value, there was no cruft after it and it satisfies a sensible range.
396 sane_val = iss.eof() && (value >= min) && (value <= max);
397 } else {
398 char* end = nullptr;
399 value = strtod(substring.c_str(), &end);
400 sane_val = *end == '\0' && value >= min && value <= max;
401 }
402 if (!sane_val) {
403 Usage("Invalid double value %s for option %s\n", substring.c_str(), option.c_str());
404 }
405 *parsed_value = value;
406}
407
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800408static constexpr size_t kMinDexFilesForSwap = 2;
409static constexpr size_t kMinDexFileCumulativeSizeForSwap = 20 * MB;
410
411static bool UseSwap(bool is_image, std::vector<const DexFile*>& dex_files) {
412 if (is_image) {
413 // Don't use swap, we know generation should succeed, and we don't want to slow it down.
414 return false;
415 }
416 if (dex_files.size() < kMinDexFilesForSwap) {
417 // If there are less dex files than the threshold, assume it's gonna be fine.
418 return false;
419 }
420 size_t dex_files_size = 0;
421 for (const auto* dex_file : dex_files) {
422 dex_files_size += dex_file->GetHeader().file_size_;
423 }
424 return dex_files_size >= kMinDexFileCumulativeSizeForSwap;
425}
426
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800427class Dex2Oat FINAL {
428 public:
429 explicit Dex2Oat(TimingLogger* timings) :
Elliott Hughes956af0f2014-12-11 14:34:28 -0800430 compiler_kind_(kUseOptimizingCompiler ? Compiler::kOptimizing : Compiler::kQuick),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800431 instruction_set_(kRuntimeISA),
432 // Take the default set of instruction features from the build.
433 method_inliner_map_(),
434 runtime_(nullptr),
435 thread_count_(sysconf(_SC_NPROCESSORS_CONF)),
436 start_ns_(NanoTime()),
437 oat_fd_(-1),
438 zip_fd_(-1),
439 image_base_(0U),
440 image_classes_zip_filename_(nullptr),
441 image_classes_filename_(nullptr),
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800442 compiled_classes_zip_filename_(nullptr),
443 compiled_classes_filename_(nullptr),
Andreas Gampe70bef0d2015-04-15 02:37:28 -0700444 compiled_methods_zip_filename_(nullptr),
445 compiled_methods_filename_(nullptr),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800446 image_(false),
447 is_host_(false),
448 dump_stats_(false),
449 dump_passes_(false),
450 dump_timing_(false),
451 dump_slow_timing_(kIsDebugBuild),
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800452 swap_fd_(-1),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800453 timings_(timings) {}
454
455 ~Dex2Oat() {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800456 // Free opened dex files before deleting the runtime_, because ~DexFile
457 // uses MemMap, which is shut down by ~Runtime.
458 class_path_files_.clear();
459 opened_dex_files_.clear();
460
461 // Log completion time before deleting the runtime_, because this accesses
462 // the runtime.
463 LogCompletionTime();
464
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800465 if (kIsDebugBuild || (RUNNING_ON_VALGRIND != 0)) {
466 delete runtime_; // See field declaration for why this is manual.
Vladimir Markof94b7812014-06-05 15:48:04 +0100467 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700468 }
469
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800470 // Parse the arguments from the command line. In case of an unrecognized option or impossible
471 // values/combinations, a usage error will be displayed and exit() is called. Thus, if the method
472 // returns, arguments have been successfully parsed.
473 void ParseArgs(int argc, char** argv) {
474 original_argc = argc;
475 original_argv = argv;
Dave Allison70202782013-10-22 17:52:19 -0700476
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800477 InitLogging(argv);
Dave Allison70202782013-10-22 17:52:19 -0700478
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800479 // Skip over argv[0].
480 argv++;
481 argc--;
Dave Allison70202782013-10-22 17:52:19 -0700482
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800483 if (argc == 0) {
484 Usage("No arguments specified");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700485 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800486
487 std::string oat_symbols;
488 std::string boot_image_filename;
489 const char* compiler_filter_string = nullptr;
490 bool compile_pic = false;
491 int huge_method_threshold = CompilerOptions::kDefaultHugeMethodThreshold;
492 int large_method_threshold = CompilerOptions::kDefaultLargeMethodThreshold;
493 int small_method_threshold = CompilerOptions::kDefaultSmallMethodThreshold;
494 int tiny_method_threshold = CompilerOptions::kDefaultTinyMethodThreshold;
495 int num_dex_methods_threshold = CompilerOptions::kDefaultNumDexMethodsThreshold;
496
497 // Profile file to use
498 double top_k_profile_threshold = CompilerOptions::kDefaultTopKProfileThreshold;
499
Andreas Gampe7b2f09e2015-03-02 14:07:33 -0800500 bool debuggable = false;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800501 bool include_patch_information = CompilerOptions::kDefaultIncludePatchInformation;
502 bool include_debug_symbols = kIsDebugBuild;
David Srbecky8dc73242015-04-12 11:40:39 +0100503 bool include_cfi = kIsDebugBuild;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800504 bool watch_dog_enabled = true;
Andreas Gampe6cf49e52015-03-05 13:08:45 -0800505 bool abort_on_hard_verifier_error = false;
Nicolas Geoffray1412dfa2015-03-20 14:48:13 +0000506 bool requested_specific_compiler = false;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800507
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800508 PassManagerOptions pass_manager_options;
509
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800510 std::string error_msg;
511
512 for (int i = 0; i < argc; i++) {
513 const StringPiece option(argv[i]);
514 const bool log_options = false;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700515 if (log_options) {
516 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
517 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800518 if (option.starts_with("--dex-file=")) {
519 dex_filenames_.push_back(option.substr(strlen("--dex-file=")).data());
520 } else if (option.starts_with("--dex-location=")) {
521 dex_locations_.push_back(option.substr(strlen("--dex-location=")).data());
522 } else if (option.starts_with("--zip-fd=")) {
523 const char* zip_fd_str = option.substr(strlen("--zip-fd=")).data();
524 if (!ParseInt(zip_fd_str, &zip_fd_)) {
525 Usage("Failed to parse --zip-fd argument '%s' as an integer", zip_fd_str);
526 }
527 if (zip_fd_ < 0) {
528 Usage("--zip-fd passed a negative value %d", zip_fd_);
529 }
530 } else if (option.starts_with("--zip-location=")) {
531 zip_location_ = option.substr(strlen("--zip-location=")).data();
532 } else if (option.starts_with("--oat-file=")) {
533 oat_filename_ = option.substr(strlen("--oat-file=")).data();
534 } else if (option.starts_with("--oat-symbols=")) {
535 oat_symbols = option.substr(strlen("--oat-symbols=")).data();
536 } else if (option.starts_with("--oat-fd=")) {
537 const char* oat_fd_str = option.substr(strlen("--oat-fd=")).data();
538 if (!ParseInt(oat_fd_str, &oat_fd_)) {
539 Usage("Failed to parse --oat-fd argument '%s' as an integer", oat_fd_str);
540 }
541 if (oat_fd_ < 0) {
542 Usage("--oat-fd passed a negative value %d", oat_fd_);
543 }
544 } else if (option == "--watch-dog") {
545 watch_dog_enabled = true;
546 } else if (option == "--no-watch-dog") {
547 watch_dog_enabled = false;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800548 } else if (option.starts_with("-j")) {
549 const char* thread_count_str = option.substr(strlen("-j")).data();
550 if (!ParseUint(thread_count_str, &thread_count_)) {
551 Usage("Failed to parse -j argument '%s' as an integer", thread_count_str);
552 }
553 } else if (option.starts_with("--oat-location=")) {
554 oat_location_ = option.substr(strlen("--oat-location=")).data();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800555 } else if (option.starts_with("--image=")) {
556 image_filename_ = option.substr(strlen("--image=")).data();
557 } else if (option.starts_with("--image-classes=")) {
558 image_classes_filename_ = option.substr(strlen("--image-classes=")).data();
559 } else if (option.starts_with("--image-classes-zip=")) {
560 image_classes_zip_filename_ = option.substr(strlen("--image-classes-zip=")).data();
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800561 } else if (option.starts_with("--compiled-classes=")) {
562 compiled_classes_filename_ = option.substr(strlen("--compiled-classes=")).data();
563 } else if (option.starts_with("--compiled-classes-zip=")) {
564 compiled_classes_zip_filename_ = option.substr(strlen("--compiled-classes-zip=")).data();
Andreas Gampe70bef0d2015-04-15 02:37:28 -0700565 } else if (option.starts_with("--compiled-methods=")) {
566 compiled_methods_filename_ = option.substr(strlen("--compiled-methods=")).data();
567 } else if (option.starts_with("--compiled-methods-zip=")) {
568 compiled_methods_zip_filename_ = option.substr(strlen("--compiled-methods-zip=")).data();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800569 } else if (option.starts_with("--base=")) {
570 const char* image_base_str = option.substr(strlen("--base=")).data();
571 char* end;
572 image_base_ = strtoul(image_base_str, &end, 16);
573 if (end == image_base_str || *end != '\0') {
574 Usage("Failed to parse hexadecimal value for option %s", option.data());
575 }
576 } else if (option.starts_with("--boot-image=")) {
577 boot_image_filename = option.substr(strlen("--boot-image=")).data();
578 } else if (option.starts_with("--android-root=")) {
579 android_root_ = option.substr(strlen("--android-root=")).data();
580 } else if (option.starts_with("--instruction-set=")) {
581 StringPiece instruction_set_str = option.substr(strlen("--instruction-set=")).data();
582 // StringPiece is not necessarily zero-terminated, so need to make a copy and ensure it.
Dan Albert6fc59ab2014-12-11 14:09:51 -0800583 std::unique_ptr<char[]> buf(new char[instruction_set_str.length() + 1]);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800584 strncpy(buf.get(), instruction_set_str.data(), instruction_set_str.length());
585 buf.get()[instruction_set_str.length()] = 0;
586 instruction_set_ = GetInstructionSetFromString(buf.get());
587 // arm actually means thumb2.
588 if (instruction_set_ == InstructionSet::kArm) {
589 instruction_set_ = InstructionSet::kThumb2;
590 }
591 } else if (option.starts_with("--instruction-set-variant=")) {
592 StringPiece str = option.substr(strlen("--instruction-set-variant=")).data();
593 instruction_set_features_.reset(
594 InstructionSetFeatures::FromVariant(instruction_set_, str.as_string(), &error_msg));
595 if (instruction_set_features_.get() == nullptr) {
596 Usage("%s", error_msg.c_str());
597 }
598 } else if (option.starts_with("--instruction-set-features=")) {
599 StringPiece str = option.substr(strlen("--instruction-set-features=")).data();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800600 if (instruction_set_features_.get() == nullptr) {
Ian Rogersd582fa42014-11-05 23:46:43 -0800601 instruction_set_features_.reset(
602 InstructionSetFeatures::FromVariant(instruction_set_, "default", &error_msg));
603 if (instruction_set_features_.get() == nullptr) {
604 Usage("Problem initializing default instruction set features variant: %s",
605 error_msg.c_str());
606 }
607 }
608 instruction_set_features_.reset(
609 instruction_set_features_->AddFeaturesFromString(str.as_string(), &error_msg));
610 if (instruction_set_features_.get() == nullptr) {
611 Usage("Error parsing '%s': %s", option.data(), error_msg.c_str());
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800612 }
613 } else if (option.starts_with("--compiler-backend=")) {
Nicolas Geoffray1412dfa2015-03-20 14:48:13 +0000614 requested_specific_compiler = true;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800615 StringPiece backend_str = option.substr(strlen("--compiler-backend=")).data();
616 if (backend_str == "Quick") {
617 compiler_kind_ = Compiler::kQuick;
618 } else if (backend_str == "Optimizing") {
619 compiler_kind_ = Compiler::kOptimizing;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800620 } else {
621 Usage("Unknown compiler backend: %s", backend_str.data());
622 }
623 } else if (option.starts_with("--compiler-filter=")) {
624 compiler_filter_string = option.substr(strlen("--compiler-filter=")).data();
625 } else if (option == "--compile-pic") {
626 compile_pic = true;
627 } else if (option.starts_with("--huge-method-max=")) {
628 const char* threshold = option.substr(strlen("--huge-method-max=")).data();
629 if (!ParseInt(threshold, &huge_method_threshold)) {
630 Usage("Failed to parse --huge-method-max '%s' as an integer", threshold);
631 }
632 if (huge_method_threshold < 0) {
633 Usage("--huge-method-max passed a negative value %s", huge_method_threshold);
634 }
635 } else if (option.starts_with("--large-method-max=")) {
636 const char* threshold = option.substr(strlen("--large-method-max=")).data();
637 if (!ParseInt(threshold, &large_method_threshold)) {
638 Usage("Failed to parse --large-method-max '%s' as an integer", threshold);
639 }
640 if (large_method_threshold < 0) {
641 Usage("--large-method-max passed a negative value %s", large_method_threshold);
642 }
643 } else if (option.starts_with("--small-method-max=")) {
644 const char* threshold = option.substr(strlen("--small-method-max=")).data();
645 if (!ParseInt(threshold, &small_method_threshold)) {
646 Usage("Failed to parse --small-method-max '%s' as an integer", threshold);
647 }
648 if (small_method_threshold < 0) {
649 Usage("--small-method-max passed a negative value %s", small_method_threshold);
650 }
651 } else if (option.starts_with("--tiny-method-max=")) {
652 const char* threshold = option.substr(strlen("--tiny-method-max=")).data();
653 if (!ParseInt(threshold, &tiny_method_threshold)) {
654 Usage("Failed to parse --tiny-method-max '%s' as an integer", threshold);
655 }
656 if (tiny_method_threshold < 0) {
657 Usage("--tiny-method-max passed a negative value %s", tiny_method_threshold);
658 }
659 } else if (option.starts_with("--num-dex-methods=")) {
660 const char* threshold = option.substr(strlen("--num-dex-methods=")).data();
661 if (!ParseInt(threshold, &num_dex_methods_threshold)) {
662 Usage("Failed to parse --num-dex-methods '%s' as an integer", threshold);
663 }
664 if (num_dex_methods_threshold < 0) {
665 Usage("--num-dex-methods passed a negative value %s", num_dex_methods_threshold);
666 }
667 } else if (option == "--host") {
668 is_host_ = true;
669 } else if (option == "--runtime-arg") {
670 if (++i >= argc) {
671 Usage("Missing required argument for --runtime-arg");
672 }
673 if (log_options) {
674 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
675 }
676 runtime_args_.push_back(argv[i]);
677 } else if (option == "--dump-timing") {
678 dump_timing_ = true;
679 } else if (option == "--dump-passes") {
680 dump_passes_ = true;
David Brazdil866c0312015-01-13 21:21:31 +0000681 } else if (option.starts_with("--dump-cfg=")) {
682 dump_cfg_file_name_ = option.substr(strlen("--dump-cfg=")).data();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800683 } else if (option == "--dump-stats") {
684 dump_stats_ = true;
685 } else if (option == "--include-debug-symbols" || option == "--no-strip-symbols") {
686 include_debug_symbols = true;
687 } else if (option == "--no-include-debug-symbols" || option == "--strip-symbols") {
688 include_debug_symbols = false;
David Srbecky8dc73242015-04-12 11:40:39 +0100689 } else if (option == "--include-cfi") {
690 include_cfi = true;
691 } else if (option == "--no-include-cfi") {
692 include_cfi = false;
Andreas Gampe7b2f09e2015-03-02 14:07:33 -0800693 } else if (option == "--debuggable") {
694 debuggable = true;
Andreas Gampef307f8c2015-05-04 08:33:31 -0700695 include_debug_symbols = true;
696 include_cfi = true;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800697 } else if (option.starts_with("--profile-file=")) {
698 profile_file_ = option.substr(strlen("--profile-file=")).data();
699 VLOG(compiler) << "dex2oat: profile file is " << profile_file_;
700 } else if (option == "--no-profile-file") {
701 // No profile
702 } else if (option.starts_with("--top-k-profile-threshold=")) {
703 ParseDouble(option.data(), '=', 0.0, 100.0, &top_k_profile_threshold);
704 } else if (option == "--print-pass-names") {
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800705 pass_manager_options.SetPrintPassNames(true);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800706 } else if (option.starts_with("--disable-passes=")) {
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800707 const std::string disable_passes = option.substr(strlen("--disable-passes=")).data();
708 pass_manager_options.SetDisablePassList(disable_passes);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800709 } else if (option.starts_with("--print-passes=")) {
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800710 const std::string print_passes = option.substr(strlen("--print-passes=")).data();
711 pass_manager_options.SetPrintPassList(print_passes);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800712 } else if (option == "--print-all-passes") {
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800713 pass_manager_options.SetPrintAllPasses();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800714 } else if (option.starts_with("--dump-cfg-passes=")) {
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800715 const std::string dump_passes_string = option.substr(strlen("--dump-cfg-passes=")).data();
716 pass_manager_options.SetDumpPassList(dump_passes_string);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800717 } else if (option == "--print-pass-options") {
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800718 pass_manager_options.SetPrintPassOptions(true);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800719 } else if (option.starts_with("--pass-options=")) {
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800720 const std::string options = option.substr(strlen("--pass-options=")).data();
721 pass_manager_options.SetOverriddenPassOptions(options);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800722 } else if (option == "--include-patch-information") {
723 include_patch_information = true;
724 } else if (option == "--no-include-patch-information") {
725 include_patch_information = false;
726 } else if (option.starts_with("--verbose-methods=")) {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800727 // TODO: rather than switch off compiler logging, make all VLOG(compiler) messages
728 // conditional on having verbost methods.
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800729 gLogVerbosity.compiler = false;
730 Split(option.substr(strlen("--verbose-methods=")).ToString(), ',', &verbose_methods_);
Andreas Gampedbfe2542014-11-25 22:21:42 -0800731 } else if (option.starts_with("--dump-init-failures=")) {
732 std::string file_name = option.substr(strlen("--dump-init-failures=")).data();
733 init_failure_output_.reset(new std::ofstream(file_name));
734 if (init_failure_output_.get() == nullptr) {
735 LOG(ERROR) << "Failed to allocate ofstream";
736 } else if (init_failure_output_->fail()) {
737 LOG(ERROR) << "Failed to open " << file_name << " for writing the initialization "
738 << "failures.";
739 init_failure_output_.reset();
740 }
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800741 } else if (option.starts_with("--swap-file=")) {
742 swap_file_name_ = option.substr(strlen("--swap-file=")).data();
743 } else if (option.starts_with("--swap-fd=")) {
744 const char* swap_fd_str = option.substr(strlen("--swap-fd=")).data();
745 if (!ParseInt(swap_fd_str, &swap_fd_)) {
746 Usage("Failed to parse --swap-fd argument '%s' as an integer", swap_fd_str);
747 }
748 if (swap_fd_ < 0) {
749 Usage("--swap-fd passed a negative value %d", swap_fd_);
750 }
Andreas Gampe6cf49e52015-03-05 13:08:45 -0800751 } else if (option == "--abort-on-hard-verifier-error") {
752 abort_on_hard_verifier_error = true;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800753 } else {
754 Usage("Unknown argument %s", option.data());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700755 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800756 }
757
Nicolas Geoffray1412dfa2015-03-20 14:48:13 +0000758 image_ = (!image_filename_.empty());
759 if (!requested_specific_compiler && !kUseOptimizingCompiler) {
760 // If no specific compiler is requested, the current behavior is
761 // to compile the boot image with Quick, and the rest with Optimizing.
762 compiler_kind_ = image_ ? Compiler::kQuick : Compiler::kOptimizing;
763 }
764
Nicolas Geoffray9bb492a2014-11-25 23:42:00 +0000765 if (compiler_kind_ == Compiler::kOptimizing) {
766 // Optimizing only supports PIC mode.
767 compile_pic = true;
768 }
769
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800770 if (oat_filename_.empty() && oat_fd_ == -1) {
771 Usage("Output must be supplied with either --oat-file or --oat-fd");
772 }
773
774 if (!oat_filename_.empty() && oat_fd_ != -1) {
775 Usage("--oat-file should not be used with --oat-fd");
776 }
777
778 if (!oat_symbols.empty() && oat_fd_ != -1) {
779 Usage("--oat-symbols should not be used with --oat-fd");
780 }
781
782 if (!oat_symbols.empty() && is_host_) {
783 Usage("--oat-symbols should not be used with --host");
784 }
785
786 if (oat_fd_ != -1 && !image_filename_.empty()) {
787 Usage("--oat-fd should not be used with --image");
788 }
789
790 if (android_root_.empty()) {
791 const char* android_root_env_var = getenv("ANDROID_ROOT");
792 if (android_root_env_var == nullptr) {
793 Usage("--android-root unspecified and ANDROID_ROOT not set");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700794 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800795 android_root_ += android_root_env_var;
796 }
797
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800798 if (!image_ && boot_image_filename.empty()) {
799 boot_image_filename += android_root_;
800 boot_image_filename += "/framework/boot.art";
801 }
802 if (!boot_image_filename.empty()) {
803 boot_image_option_ += "-Ximage:";
804 boot_image_option_ += boot_image_filename;
805 }
806
807 if (image_classes_filename_ != nullptr && !image_) {
808 Usage("--image-classes should only be used with --image");
809 }
810
811 if (image_classes_filename_ != nullptr && !boot_image_option_.empty()) {
812 Usage("--image-classes should not be used with --boot-image");
813 }
814
815 if (image_classes_zip_filename_ != nullptr && image_classes_filename_ == nullptr) {
816 Usage("--image-classes-zip should be used with --image-classes");
817 }
818
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800819 if (compiled_classes_filename_ != nullptr && !image_) {
820 Usage("--compiled-classes should only be used with --image");
821 }
822
823 if (compiled_classes_filename_ != nullptr && !boot_image_option_.empty()) {
824 Usage("--compiled-classes should not be used with --boot-image");
825 }
826
827 if (compiled_classes_zip_filename_ != nullptr && compiled_classes_filename_ == nullptr) {
828 Usage("--compiled-classes-zip should be used with --compiled-classes");
829 }
830
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800831 if (dex_filenames_.empty() && zip_fd_ == -1) {
832 Usage("Input must be supplied with either --dex-file or --zip-fd");
833 }
834
835 if (!dex_filenames_.empty() && zip_fd_ != -1) {
836 Usage("--dex-file should not be used with --zip-fd");
837 }
838
839 if (!dex_filenames_.empty() && !zip_location_.empty()) {
840 Usage("--dex-file should not be used with --zip-location");
841 }
842
843 if (dex_locations_.empty()) {
844 for (const char* dex_file_name : dex_filenames_) {
845 dex_locations_.push_back(dex_file_name);
846 }
847 } else if (dex_locations_.size() != dex_filenames_.size()) {
848 Usage("--dex-location arguments do not match --dex-file arguments");
849 }
850
851 if (zip_fd_ != -1 && zip_location_.empty()) {
852 Usage("--zip-location should be supplied with --zip-fd");
853 }
854
855 if (boot_image_option_.empty()) {
856 if (image_base_ == 0) {
857 Usage("Non-zero --base not specified");
858 }
859 }
860
861 oat_stripped_ = oat_filename_;
862 if (!oat_symbols.empty()) {
863 oat_unstripped_ = oat_symbols;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700864 } else {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800865 oat_unstripped_ = oat_filename_;
866 }
867
868 // If no instruction set feature was given, use the default one for the target
869 // instruction set.
870 if (instruction_set_features_.get() == nullptr) {
871 instruction_set_features_.reset(
Ian Rogersd582fa42014-11-05 23:46:43 -0800872 InstructionSetFeatures::FromVariant(instruction_set_, "default", &error_msg));
873 if (instruction_set_features_.get() == nullptr) {
874 Usage("Problem initializing default instruction set features variant: %s",
875 error_msg.c_str());
876 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800877 }
878
879 if (instruction_set_ == kRuntimeISA) {
880 std::unique_ptr<const InstructionSetFeatures> runtime_features(
881 InstructionSetFeatures::FromCppDefines());
882 if (!instruction_set_features_->Equals(runtime_features.get())) {
883 LOG(WARNING) << "Mismatch between dex2oat instruction set features ("
884 << *instruction_set_features_ << ") and those of dex2oat executable ("
885 << *runtime_features <<") for the command line:\n"
886 << CommandLine();
887 }
888 }
889
890 if (compiler_filter_string == nullptr) {
Douglas Leung027f0ff2015-02-27 19:05:03 -0800891 compiler_filter_string = "speed";
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800892 }
Maja Gagic6ea651f2015-02-24 16:55:04 +0100893
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800894 CHECK(compiler_filter_string != nullptr);
895 CompilerOptions::CompilerFilter compiler_filter = CompilerOptions::kDefaultCompilerFilter;
896 if (strcmp(compiler_filter_string, "verify-none") == 0) {
897 compiler_filter = CompilerOptions::kVerifyNone;
898 } else if (strcmp(compiler_filter_string, "interpret-only") == 0) {
899 compiler_filter = CompilerOptions::kInterpretOnly;
Mathieu Chartiere86deef2015-03-19 13:43:37 -0700900 } else if (strcmp(compiler_filter_string, "verify-at-runtime") == 0) {
901 compiler_filter = CompilerOptions::kVerifyAtRuntime;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800902 } else if (strcmp(compiler_filter_string, "space") == 0) {
903 compiler_filter = CompilerOptions::kSpace;
904 } else if (strcmp(compiler_filter_string, "balanced") == 0) {
905 compiler_filter = CompilerOptions::kBalanced;
906 } else if (strcmp(compiler_filter_string, "speed") == 0) {
907 compiler_filter = CompilerOptions::kSpeed;
908 } else if (strcmp(compiler_filter_string, "everything") == 0) {
909 compiler_filter = CompilerOptions::kEverything;
910 } else if (strcmp(compiler_filter_string, "time") == 0) {
911 compiler_filter = CompilerOptions::kTime;
912 } else {
913 Usage("Unknown --compiler-filter value %s", compiler_filter_string);
914 }
915
916 // Checks are all explicit until we know the architecture.
917 bool implicit_null_checks = false;
918 bool implicit_so_checks = false;
919 bool implicit_suspend_checks = false;
920 // Set the compilation target's implicit checks options.
921 switch (instruction_set_) {
922 case kArm:
923 case kThumb2:
924 case kArm64:
925 case kX86:
926 case kX86_64:
927 implicit_null_checks = true;
928 implicit_so_checks = true;
929 break;
930
931 default:
932 // Defaults are correct.
933 break;
934 }
935
Andreas Gampe7b2f09e2015-03-02 14:07:33 -0800936 if (debuggable) {
937 // TODO: Consider adding CFI info and symbols here.
938 }
939
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800940 compiler_options_.reset(new CompilerOptions(compiler_filter,
941 huge_method_threshold,
942 large_method_threshold,
943 small_method_threshold,
944 tiny_method_threshold,
945 num_dex_methods_threshold,
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800946 include_patch_information,
947 top_k_profile_threshold,
Andreas Gampe7b2f09e2015-03-02 14:07:33 -0800948 debuggable,
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800949 include_debug_symbols,
David Srbecky8dc73242015-04-12 11:40:39 +0100950 include_cfi,
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800951 implicit_null_checks,
952 implicit_so_checks,
953 implicit_suspend_checks,
954 compile_pic,
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800955 verbose_methods_.empty() ?
956 nullptr :
Andreas Gampedbfe2542014-11-25 22:21:42 -0800957 &verbose_methods_,
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800958 new PassManagerOptions(pass_manager_options),
Andreas Gampe6cf49e52015-03-05 13:08:45 -0800959 init_failure_output_.get(),
960 abort_on_hard_verifier_error));
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800961
962 // Done with usage checks, enable watchdog if requested
963 if (watch_dog_enabled) {
964 watchdog_.reset(new WatchDog(true));
965 }
966
967 // Fill some values into the key-value store for the oat header.
968 key_value_store_.reset(new SafeMap<std::string, std::string>());
969
970 // Insert some compiler things.
971 {
972 std::ostringstream oss;
973 for (int i = 0; i < argc; ++i) {
974 if (i > 0) {
975 oss << ' ';
976 }
977 oss << argv[i];
978 }
979 key_value_store_->Put(OatHeader::kDex2OatCmdLineKey, oss.str());
980 oss.str(""); // Reset.
981 oss << kRuntimeISA;
982 key_value_store_->Put(OatHeader::kDex2OatHostKey, oss.str());
Sebastien Hertz0de11332015-05-13 12:14:05 +0200983 key_value_store_->Put(OatHeader::kPicKey,
984 compile_pic ? OatHeader::kTrueValue : OatHeader::kFalseValue);
985 key_value_store_->Put(OatHeader::kDebuggableKey,
986 debuggable ? OatHeader::kTrueValue : OatHeader::kFalseValue);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800987 }
988 }
989
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800990 // Check whether the oat output file is writable, and open it for later. Also open a swap file,
991 // if a name is given.
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800992 bool OpenFile() {
993 bool create_file = !oat_unstripped_.empty(); // as opposed to using open file descriptor
994 if (create_file) {
995 oat_file_.reset(OS::CreateEmptyFile(oat_unstripped_.c_str()));
996 if (oat_location_.empty()) {
997 oat_location_ = oat_filename_;
998 }
999 } else {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001000 oat_file_.reset(new File(oat_fd_, oat_location_, true));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001001 oat_file_->DisableAutoClose();
Andreas Gampe4303ba92014-11-06 01:00:46 -08001002 if (oat_file_->SetLength(0) != 0) {
1003 PLOG(WARNING) << "Truncating oat file " << oat_location_ << " failed.";
1004 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001005 }
1006 if (oat_file_.get() == nullptr) {
1007 PLOG(ERROR) << "Failed to create oat file: " << oat_location_;
1008 return false;
1009 }
1010 if (create_file && fchmod(oat_file_->Fd(), 0644) != 0) {
1011 PLOG(ERROR) << "Failed to make oat file world readable: " << oat_location_;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001012 oat_file_->Erase();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001013 return false;
1014 }
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001015
1016 // Swap file handling.
1017 //
1018 // If the swap fd is not -1, we assume this is the file descriptor of an open but unlinked file
1019 // that we can use for swap.
1020 //
1021 // If the swap fd is -1 and we have a swap-file string, open the given file as a swap file. We
1022 // will immediately unlink to satisfy the swap fd assumption.
1023 if (swap_fd_ == -1 && !swap_file_name_.empty()) {
1024 std::unique_ptr<File> swap_file(OS::CreateEmptyFile(swap_file_name_.c_str()));
1025 if (swap_file.get() == nullptr) {
1026 PLOG(ERROR) << "Failed to create swap file: " << swap_file_name_;
1027 return false;
1028 }
1029 swap_fd_ = swap_file->Fd();
1030 swap_file->MarkUnchecked(); // We don't we to track this, it will be unlinked immediately.
1031 swap_file->DisableAutoClose(); // We'll handle it ourselves, the File object will be
1032 // released immediately.
1033 unlink(swap_file_name_.c_str());
1034 }
1035
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001036 return true;
1037 }
1038
Andreas Gampea650e702014-12-03 14:28:02 -08001039 void EraseOatFile() {
1040 DCHECK(oat_file_.get() != nullptr);
1041 oat_file_->Erase();
1042 oat_file_.reset();
1043 }
1044
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001045 // Set up the environment for compilation. Includes starting the runtime and loading/opening the
1046 // boot class path.
1047 bool Setup() {
1048 TimingLogger::ScopedTiming t("dex2oat Setup", timings_);
1049 RuntimeOptions runtime_options;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001050 art::MemMap::Init(); // For ZipEntry::ExtractToMemMap.
1051 if (boot_image_option_.empty()) {
Richard Uhlerc2752592015-01-02 13:28:22 -08001052 std::string boot_class_path = "-Xbootclasspath:";
1053 boot_class_path += Join(dex_filenames_, ':');
1054 runtime_options.push_back(std::make_pair(boot_class_path, nullptr));
1055 std::string boot_class_path_locations = "-Xbootclasspath-locations:";
1056 boot_class_path_locations += Join(dex_locations_, ':');
1057 runtime_options.push_back(std::make_pair(boot_class_path_locations, nullptr));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001058 } else {
Richard Uhlerc2752592015-01-02 13:28:22 -08001059 runtime_options.push_back(std::make_pair(boot_image_option_, nullptr));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001060 }
1061 for (size_t i = 0; i < runtime_args_.size(); i++) {
1062 runtime_options.push_back(std::make_pair(runtime_args_[i], nullptr));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001063 }
Brian Carlstromd76e0832013-08-29 15:17:42 -07001064
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001065 verification_results_.reset(new VerificationResults(compiler_options_.get()));
Andreas Gampe4585f872015-03-27 23:45:15 -07001066 callbacks_.reset(new QuickCompilerCallbacks(
1067 verification_results_.get(),
1068 &method_inliner_map_,
1069 image_ ?
1070 CompilerCallbacks::CallbackMode::kCompileBootImage :
1071 CompilerCallbacks::CallbackMode::kCompileApp));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001072 runtime_options.push_back(std::make_pair("compilercallbacks", callbacks_.get()));
1073 runtime_options.push_back(
1074 std::make_pair("imageinstructionset", GetInstructionSetString(instruction_set_)));
1075
Andreas Gampe1d00add2015-02-27 19:35:46 -08001076 // Only allow no boot image for the runtime if we're compiling one. When we compile an app,
1077 // we don't want fallback mode, it will abort as we do not push a boot classpath (it might
1078 // have been stripped in preopting, anyways).
1079 if (!image_) {
1080 runtime_options.push_back(std::make_pair("-Xno-dex-file-fallback", nullptr));
1081 }
1082
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001083 if (!CreateRuntime(runtime_options)) {
1084 return false;
1085 }
1086
1087 // Runtime::Create acquired the mutator_lock_ that is normally given away when we
1088 // Runtime::Start, give it away now so that we don't starve GC.
1089 Thread* self = Thread::Current();
1090 self->TransitionFromRunnableToSuspended(kNative);
1091 // If we're doing the image, override the compiler filter to force full compilation. Must be
1092 // done ahead of WellKnownClasses::Init that causes verification. Note: doesn't force
1093 // compilation of class initializers.
1094 // Whilst we're in native take the opportunity to initialize well known classes.
1095 WellKnownClasses::Init(self->GetJniEnv());
1096
1097 // If --image-classes was specified, calculate the full list of classes to include in the image
1098 if (image_classes_filename_ != nullptr) {
1099 std::string error_msg;
1100 if (image_classes_zip_filename_ != nullptr) {
1101 image_classes_.reset(ReadImageClassesFromZip(image_classes_zip_filename_,
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001102 image_classes_filename_,
1103 &error_msg));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001104 } else {
1105 image_classes_.reset(ReadImageClassesFromFile(image_classes_filename_));
1106 }
1107 if (image_classes_.get() == nullptr) {
1108 LOG(ERROR) << "Failed to create list of image classes from '" << image_classes_filename_ <<
1109 "': " << error_msg;
1110 return false;
1111 }
1112 } else if (image_) {
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001113 image_classes_.reset(new std::unordered_set<std::string>);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001114 }
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001115 // If --compiled-classes was specified, calculate the full list of classes to compile in the
1116 // image.
1117 if (compiled_classes_filename_ != nullptr) {
1118 std::string error_msg;
1119 if (compiled_classes_zip_filename_ != nullptr) {
1120 compiled_classes_.reset(ReadImageClassesFromZip(compiled_classes_zip_filename_,
1121 compiled_classes_filename_,
1122 &error_msg));
1123 } else {
1124 compiled_classes_.reset(ReadImageClassesFromFile(compiled_classes_filename_));
1125 }
1126 if (compiled_classes_.get() == nullptr) {
1127 LOG(ERROR) << "Failed to create list of compiled classes from '"
1128 << compiled_classes_filename_ << "': " << error_msg;
1129 return false;
1130 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001131 } else {
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001132 compiled_classes_.reset(nullptr); // By default compile everything.
1133 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001134 // If --compiled-methods was specified, read the methods to compile from the given file(s).
1135 if (compiled_methods_filename_ != nullptr) {
1136 std::string error_msg;
1137 if (compiled_methods_zip_filename_ != nullptr) {
1138 compiled_methods_.reset(ReadCommentedInputFromZip(compiled_methods_zip_filename_,
1139 compiled_methods_filename_,
1140 nullptr, // No post-processing.
1141 &error_msg));
1142 } else {
1143 compiled_methods_.reset(ReadCommentedInputFromFile(compiled_methods_filename_,
1144 nullptr)); // No post-processing.
1145 }
1146 if (compiled_methods_.get() == nullptr) {
1147 LOG(ERROR) << "Failed to create list of compiled methods from '"
1148 << compiled_methods_filename_ << "': " << error_msg;
1149 return false;
1150 }
1151 } else {
1152 compiled_methods_.reset(nullptr); // By default compile everything.
1153 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001154
1155 if (boot_image_option_.empty()) {
1156 dex_files_ = Runtime::Current()->GetClassLinker()->GetBootClassPath();
1157 } else {
1158 if (dex_filenames_.empty()) {
1159 ATRACE_BEGIN("Opening zip archive from file descriptor");
1160 std::string error_msg;
1161 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(zip_fd_,
1162 zip_location_.c_str(),
1163 &error_msg));
1164 if (zip_archive.get() == nullptr) {
1165 LOG(ERROR) << "Failed to open zip from file descriptor for '" << zip_location_ << "': "
1166 << error_msg;
1167 return false;
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001168 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001169 if (!DexFile::OpenFromZip(*zip_archive.get(), zip_location_, &error_msg, &opened_dex_files_)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001170 LOG(ERROR) << "Failed to open dex from file descriptor for zip file '" << zip_location_
1171 << "': " << error_msg;
1172 return false;
1173 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001174 for (auto& dex_file : opened_dex_files_) {
1175 dex_files_.push_back(dex_file.get());
1176 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001177 ATRACE_END();
1178 } else {
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001179 size_t failure_count = OpenDexFiles(dex_filenames_, dex_locations_, &opened_dex_files_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001180 if (failure_count > 0) {
1181 LOG(ERROR) << "Failed to open some dex files: " << failure_count;
1182 return false;
1183 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001184 for (auto& dex_file : opened_dex_files_) {
1185 dex_files_.push_back(dex_file.get());
1186 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001187 }
1188
1189 constexpr bool kSaveDexInput = false;
1190 if (kSaveDexInput) {
1191 for (size_t i = 0; i < dex_files_.size(); ++i) {
1192 const DexFile* dex_file = dex_files_[i];
Brian Carlstrom95b033b2014-12-03 22:29:37 -08001193 std::string tmp_file_name(StringPrintf("/data/local/tmp/dex2oat.%d.%zd.dex",
1194 getpid(), i));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001195 std::unique_ptr<File> tmp_file(OS::CreateEmptyFile(tmp_file_name.c_str()));
1196 if (tmp_file.get() == nullptr) {
1197 PLOG(ERROR) << "Failed to open file " << tmp_file_name
1198 << ". Try: adb shell chmod 777 /data/local/tmp";
1199 continue;
1200 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001201 // This is just dumping files for debugging. Ignore errors, and leave remnants.
1202 UNUSED(tmp_file->WriteFully(dex_file->Begin(), dex_file->Size()));
1203 UNUSED(tmp_file->Flush());
1204 UNUSED(tmp_file->Close());
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001205 LOG(INFO) << "Wrote input to " << tmp_file_name;
1206 }
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001207 }
1208 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001209 // Ensure opened dex files are writable for dex-to-dex transformations.
1210 for (const auto& dex_file : dex_files_) {
1211 if (!dex_file->EnableWrite()) {
1212 PLOG(ERROR) << "Failed to make .dex file writeable '" << dex_file->GetLocation() << "'\n";
Andreas Gampe7ba64962014-10-23 11:37:40 -07001213 }
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001214 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001215
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001216 // If we use a swap file, ensure we are above the threshold to make it necessary.
1217 if (swap_fd_ != -1) {
1218 if (!UseSwap(image_, dex_files_)) {
1219 close(swap_fd_);
1220 swap_fd_ = -1;
Andreas Gampef99bcd22015-04-24 16:22:18 -07001221 VLOG(compiler) << "Decided to run without swap.";
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001222 } else {
Andreas Gampef99bcd22015-04-24 16:22:18 -07001223 LOG(INFO) << "Large app, accepted running with swap.";
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001224 }
1225 }
1226 // Note that dex2oat won't close the swap_fd_. The compiler driver's swap space will do that.
1227
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001228 /*
1229 * If we're not in interpret-only or verify-none mode, go ahead and compile small applications.
1230 * Don't bother to check if we're doing the image.
1231 */
Brian Carlstrom95b033b2014-12-03 22:29:37 -08001232 if (!image_ &&
1233 compiler_options_->IsCompilationEnabled() &&
1234 compiler_kind_ == Compiler::kQuick) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001235 size_t num_methods = 0;
1236 for (size_t i = 0; i != dex_files_.size(); ++i) {
1237 const DexFile* dex_file = dex_files_[i];
1238 CHECK(dex_file != nullptr);
1239 num_methods += dex_file->NumMethodIds();
1240 }
1241 if (num_methods <= compiler_options_->GetNumDexMethodsThreshold()) {
1242 compiler_options_->SetCompilerFilter(CompilerOptions::kSpeed);
1243 VLOG(compiler) << "Below method threshold, compiling anyways";
1244 }
1245 }
1246
1247 return true;
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001248 }
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001249
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001250 // Create and invoke the compiler driver. This will compile all the dex files.
1251 void Compile() {
1252 TimingLogger::ScopedTiming t("dex2oat Compile", timings_);
1253 compiler_phases_timings_.reset(new CumulativeLogger("compilation times"));
Vladimir Markof4da6752014-08-01 19:04:18 +01001254
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001255 // Handle and ClassLoader creation needs to come after Runtime::Create
1256 jobject class_loader = nullptr;
1257 Thread* self = Thread::Current();
1258 if (!boot_image_option_.empty()) {
1259 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001260 OpenClassPathFiles(runtime_->GetClassPathString(), dex_files_, &class_path_files_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001261 ScopedObjectAccess soa(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07001262
1263 // Classpath: first the class-path given.
1264 std::vector<const DexFile*> class_path_files;
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001265 for (auto& class_path_file : class_path_files_) {
1266 class_path_files.push_back(class_path_file.get());
1267 }
Andreas Gampe7848da42015-04-09 11:15:04 -07001268
1269 // Store the classpath we have right now.
1270 key_value_store_->Put(OatHeader::kClassPathKey,
1271 OatFile::EncodeDexFileDependencies(class_path_files));
1272
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07001273 // Then the dex files we'll compile. Thus we'll resolve the class-path first.
1274 class_path_files.insert(class_path_files.end(), dex_files_.begin(), dex_files_.end());
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001275
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07001276 class_loader = class_linker->CreatePathClassLoader(self, class_path_files);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001277 }
1278
1279 driver_.reset(new CompilerDriver(compiler_options_.get(),
1280 verification_results_.get(),
1281 &method_inliner_map_,
1282 compiler_kind_,
1283 instruction_set_,
1284 instruction_set_features_.get(),
1285 image_,
1286 image_classes_.release(),
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001287 compiled_classes_.release(),
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001288 nullptr,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001289 thread_count_,
1290 dump_stats_,
1291 dump_passes_,
David Brazdil866c0312015-01-13 21:21:31 +00001292 dump_cfg_file_name_,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001293 compiler_phases_timings_.get(),
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001294 swap_fd_,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001295 profile_file_));
1296
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001297 driver_->CompileAll(class_loader, dex_files_, timings_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001298 }
1299
Brian Carlstrom7940e442013-07-12 13:46:57 -07001300 // Notes on the interleaving of creating the image and oat file to
1301 // ensure the references between the two are correct.
1302 //
1303 // Currently we have a memory layout that looks something like this:
1304 //
1305 // +--------------+
1306 // | image |
1307 // +--------------+
1308 // | boot oat |
1309 // +--------------+
1310 // | alloc spaces |
1311 // +--------------+
1312 //
Brian Carlstrom45602482013-07-21 22:07:55 -07001313 // There are several constraints on the loading of the image and boot.oat.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001314 //
1315 // 1. The image is expected to be loaded at an absolute address and
1316 // contains Objects with absolute pointers within the image.
1317 //
1318 // 2. There are absolute pointers from Methods in the image to their
1319 // code in the oat.
1320 //
1321 // 3. There are absolute pointers from the code in the oat to Methods
1322 // in the image.
1323 //
1324 // 4. There are absolute pointers from code in the oat to other code
1325 // in the oat.
1326 //
1327 // To get this all correct, we go through several steps.
1328 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001329 // 1. We prepare offsets for all data in the oat file and calculate
1330 // the oat data size and code size. During this stage, we also set
1331 // oat code offsets in methods for use by the image writer.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001332 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001333 // 2. We prepare offsets for the objects in the image and calculate
1334 // the image size.
1335 //
1336 // 3. We create the oat file. Originally this was just our own proprietary
1337 // file but now it is contained within an ELF dynamic object (aka an .so
1338 // file). Since we know the image size and oat data size and code size we
1339 // can prepare the ELF headers and we then know the ELF memory segment
1340 // layout and we can now resolve all references. The compiler provides
1341 // LinkerPatch information in each CompiledMethod and we resolve these,
1342 // using the layout information and image object locations provided by
1343 // image writer, as we're writing the method code.
1344 //
1345 // 4. We create the image file. It needs to know where the oat file
Brian Carlstrom7940e442013-07-12 13:46:57 -07001346 // will be loaded after itself. Originally when oat file was simply
1347 // memory mapped so we could predict where its contents were based
1348 // on the file size. Now that it is an ELF file, we need to inspect
1349 // the ELF file to understand the in memory segment layout including
Vladimir Markof4da6752014-08-01 19:04:18 +01001350 // where the oat header is located within.
1351 // TODO: We could just remember this information from step 3.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001352 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001353 // 5. We fixup the ELF program headers so that dlopen will try to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001354 // load the .so at the desired location at runtime by offsetting the
1355 // Elf32_Phdr.p_vaddr values by the desired base address.
Vladimir Markof4da6752014-08-01 19:04:18 +01001356 // TODO: Do this in step 3. We already know the layout there.
1357 //
1358 // Steps 1.-3. are done by the CreateOatFile() above, steps 4.-5.
1359 // are done by the CreateImageFile() below.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001360
1361
1362 // Write out the generated code part. Calls the OatWriter and ElfBuilder. Also prepares the
1363 // ImageWriter, if necessary.
Andreas Gampe10e477d2014-11-19 12:57:42 -08001364 // Note: Flushing (and closing) the file is the caller's responsibility, except for the failure
1365 // case (when the file will be explicitly erased).
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001366 bool CreateOatFile() {
1367 CHECK(key_value_store_.get() != nullptr);
1368
1369 TimingLogger::ScopedTiming t("dex2oat Oat", timings_);
1370
1371 std::unique_ptr<OatWriter> oat_writer;
1372 {
1373 TimingLogger::ScopedTiming t2("dex2oat OatWriter", timings_);
1374 std::string image_file_location;
1375 uint32_t image_file_location_oat_checksum = 0;
1376 uintptr_t image_file_location_oat_data_begin = 0;
1377 int32_t image_patch_delta = 0;
1378 if (image_) {
1379 PrepareImageWriter(image_base_);
1380 } else {
1381 TimingLogger::ScopedTiming t3("Loading image checksum", timings_);
1382 gc::space::ImageSpace* image_space = Runtime::Current()->GetHeap()->GetImageSpace();
1383 image_file_location_oat_checksum = image_space->GetImageHeader().GetOatChecksum();
1384 image_file_location_oat_data_begin =
1385 reinterpret_cast<uintptr_t>(image_space->GetImageHeader().GetOatDataBegin());
1386 image_file_location = image_space->GetImageFilename();
1387 image_patch_delta = image_space->GetImageHeader().GetPatchDelta();
1388 }
1389
1390 if (!image_file_location.empty()) {
1391 key_value_store_->Put(OatHeader::kImageLocationKey, image_file_location);
1392 }
1393
1394 oat_writer.reset(new OatWriter(dex_files_, image_file_location_oat_checksum,
1395 image_file_location_oat_data_begin,
1396 image_patch_delta,
1397 driver_.get(),
1398 image_writer_.get(),
1399 timings_,
1400 key_value_store_.get()));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001401 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001402
1403 if (image_) {
1404 // The OatWriter constructor has already updated offsets in methods and we need to
1405 // prepare method offsets in the image address space for direct method patching.
1406 TimingLogger::ScopedTiming t2("dex2oat Prepare image address space", timings_);
1407 if (!image_writer_->PrepareImageAddressSpace()) {
1408 LOG(ERROR) << "Failed to prepare image address space.";
1409 return false;
1410 }
1411 }
1412
1413 {
1414 TimingLogger::ScopedTiming t2("dex2oat Write ELF", timings_);
1415 if (!driver_->WriteElf(android_root_, is_host_, dex_files_, oat_writer.get(),
1416 oat_file_.get())) {
1417 LOG(ERROR) << "Failed to write ELF file " << oat_file_->GetPath();
1418 return false;
1419 }
1420 }
1421
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001422 VLOG(compiler) << "Oat file written successfully (unstripped): " << oat_location_;
1423 return true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001424 }
1425
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001426 // If we are compiling an image, invoke the image creation routine. Else just skip.
1427 bool HandleImage() {
1428 if (image_) {
1429 TimingLogger::ScopedTiming t("dex2oat ImageWriter", timings_);
1430 if (!CreateImageFile()) {
1431 return false;
1432 }
1433 VLOG(compiler) << "Image written successfully: " << image_filename_;
Brian Carlstrom45602482013-07-21 22:07:55 -07001434 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001435 return true;
1436 }
1437
Andreas Gampe10e477d2014-11-19 12:57:42 -08001438 // Create a copy from unstripped to stripped.
1439 bool CopyUnstrippedToStripped() {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001440 // If we don't want to strip in place, copy from unstripped location to stripped location.
1441 // We need to strip after image creation because FixupElf needs to use .strtab.
1442 if (oat_unstripped_ != oat_stripped_) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08001443 // If the oat file is still open, flush it.
1444 if (oat_file_.get() != nullptr && oat_file_->IsOpened()) {
1445 if (!FlushCloseOatFile()) {
1446 return false;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001447 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001448 }
Andreas Gampe10e477d2014-11-19 12:57:42 -08001449
1450 TimingLogger::ScopedTiming t("dex2oat OatFile copy", timings_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001451 std::unique_ptr<File> in(OS::OpenFileForReading(oat_unstripped_.c_str()));
1452 std::unique_ptr<File> out(OS::CreateEmptyFile(oat_stripped_.c_str()));
1453 size_t buffer_size = 8192;
Dan Albert6fc59ab2014-12-11 14:09:51 -08001454 std::unique_ptr<uint8_t[]> buffer(new uint8_t[buffer_size]);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001455 while (true) {
1456 int bytes_read = TEMP_FAILURE_RETRY(read(in->Fd(), buffer.get(), buffer_size));
1457 if (bytes_read <= 0) {
1458 break;
1459 }
1460 bool write_ok = out->WriteFully(buffer.get(), bytes_read);
1461 CHECK(write_ok);
1462 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08001463 if (out->FlushCloseOrErase() != 0) {
1464 PLOG(ERROR) << "Failed to flush and close copied oat file: " << oat_stripped_;
1465 return false;
Andreas Gampe10e477d2014-11-19 12:57:42 -08001466 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001467 VLOG(compiler) << "Oat file copied successfully (stripped): " << oat_stripped_;
Nicolas Geoffrayea3fa0b2014-02-10 11:59:41 +00001468 }
Andreas Gampe10e477d2014-11-19 12:57:42 -08001469 return true;
1470 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001471
Andreas Gampe10e477d2014-11-19 12:57:42 -08001472 bool FlushOatFile() {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001473 if (oat_file_.get() != nullptr) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08001474 TimingLogger::ScopedTiming t2("dex2oat Flush ELF", timings_);
1475 if (oat_file_->Flush() != 0) {
1476 PLOG(ERROR) << "Failed to flush oat file: " << oat_location_ << " / "
1477 << oat_filename_;
1478 oat_file_->Erase();
1479 return false;
1480 }
1481 }
1482 return true;
1483 }
1484
1485 bool FlushCloseOatFile() {
1486 if (oat_file_.get() != nullptr) {
1487 std::unique_ptr<File> tmp(oat_file_.release());
1488 if (tmp->FlushCloseOrErase() != 0) {
1489 PLOG(ERROR) << "Failed to flush and close oat file: " << oat_location_ << " / "
1490 << oat_filename_;
1491 return false;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001492 }
1493 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001494 return true;
1495 }
1496
1497 void DumpTiming() {
1498 if (dump_timing_ || (dump_slow_timing_ && timings_->GetTotalNs() > MsToNs(1000))) {
1499 LOG(INFO) << Dumpable<TimingLogger>(*timings_);
1500 }
1501 if (dump_passes_) {
1502 LOG(INFO) << Dumpable<CumulativeLogger>(*driver_->GetTimingsLogger());
1503 }
1504 }
1505
1506 CompilerOptions* GetCompilerOptions() const {
1507 return compiler_options_.get();
1508 }
1509
Andreas Gampe10e477d2014-11-19 12:57:42 -08001510 bool IsImage() const {
1511 return image_;
1512 }
1513
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001514 bool IsHost() const {
1515 return is_host_;
1516 }
1517
1518 private:
1519 static size_t OpenDexFiles(const std::vector<const char*>& dex_filenames,
1520 const std::vector<const char*>& dex_locations,
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001521 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001522 DCHECK(dex_files != nullptr) << "OpenDexFiles out-param is nullptr";
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001523 size_t failure_count = 0;
1524 for (size_t i = 0; i < dex_filenames.size(); i++) {
1525 const char* dex_filename = dex_filenames[i];
1526 const char* dex_location = dex_locations[i];
1527 ATRACE_BEGIN(StringPrintf("Opening dex file '%s'", dex_filenames[i]).c_str());
1528 std::string error_msg;
1529 if (!OS::FileExists(dex_filename)) {
1530 LOG(WARNING) << "Skipping non-existent dex file '" << dex_filename << "'";
1531 continue;
1532 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001533 if (!DexFile::Open(dex_filename, dex_location, &error_msg, dex_files)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001534 LOG(WARNING) << "Failed to open .dex from file '" << dex_filename << "': " << error_msg;
1535 ++failure_count;
1536 }
1537 ATRACE_END();
1538 }
1539 return failure_count;
1540 }
1541
Andreas Gampee3712d02015-04-09 14:46:31 -07001542 // Returns true if dex_files has a dex with the named location. We compare canonical locations,
1543 // so that relative and absolute paths will match. Not caching for the dex_files isn't very
1544 // efficient, but under normal circumstances the list is neither large nor is this part too
1545 // sensitive.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001546 static bool DexFilesContains(const std::vector<const DexFile*>& dex_files,
1547 const std::string& location) {
Andreas Gampee3712d02015-04-09 14:46:31 -07001548 std::string canonical_location(DexFile::GetDexCanonicalLocation(location.c_str()));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001549 for (size_t i = 0; i < dex_files.size(); ++i) {
Andreas Gampee3712d02015-04-09 14:46:31 -07001550 if (DexFile::GetDexCanonicalLocation(dex_files[i]->GetLocation().c_str()) ==
1551 canonical_location) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001552 return true;
1553 }
1554 }
1555 return false;
1556 }
1557
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001558 // Appends to opened_dex_files any elements of class_path that dex_files
1559 // doesn't already contain. This will open those dex files as necessary.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001560 static void OpenClassPathFiles(const std::string& class_path,
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001561 std::vector<const DexFile*> dex_files,
1562 std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001563 DCHECK(opened_dex_files != nullptr) << "OpenClassPathFiles out-param is nullptr";
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001564 std::vector<std::string> parsed;
1565 Split(class_path, ':', &parsed);
1566 // Take Locks::mutator_lock_ so that lock ordering on the ClassLinker::dex_lock_ is maintained.
1567 ScopedObjectAccess soa(Thread::Current());
1568 for (size_t i = 0; i < parsed.size(); ++i) {
1569 if (DexFilesContains(dex_files, parsed[i])) {
1570 continue;
1571 }
1572 std::string error_msg;
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001573 if (!DexFile::Open(parsed[i].c_str(), parsed[i].c_str(), &error_msg, opened_dex_files)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001574 LOG(WARNING) << "Failed to open dex file '" << parsed[i] << "': " << error_msg;
1575 }
1576 }
1577 }
1578
1579 // Create a runtime necessary for compilation.
1580 bool CreateRuntime(const RuntimeOptions& runtime_options)
1581 SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_) {
1582 if (!Runtime::Create(runtime_options, false)) {
1583 LOG(ERROR) << "Failed to create runtime";
1584 return false;
1585 }
1586 Runtime* runtime = Runtime::Current();
1587 runtime->SetInstructionSet(instruction_set_);
1588 for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
1589 Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i);
1590 if (!runtime->HasCalleeSaveMethod(type)) {
1591 runtime->SetCalleeSaveMethod(runtime->CreateCalleeSaveMethod(), type);
1592 }
1593 }
1594 runtime->GetClassLinker()->FixupDexCaches(runtime->GetResolutionMethod());
Andreas Gampe2969bcd2015-03-09 12:57:41 -07001595
1596 // Initialize maps for unstarted runtime. This needs to be here, as running clinits needs this
1597 // set up.
Andreas Gampe799681b2015-05-15 19:24:12 -07001598 interpreter::UnstartedRuntime::Initialize();
Andreas Gampe2969bcd2015-03-09 12:57:41 -07001599
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001600 runtime->GetClassLinker()->RunRootClinits();
1601 runtime_ = runtime;
Andreas Gampe2969bcd2015-03-09 12:57:41 -07001602
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001603 return true;
1604 }
1605
1606 void PrepareImageWriter(uintptr_t image_base) {
1607 image_writer_.reset(new ImageWriter(*driver_, image_base, compiler_options_->GetCompilePic()));
1608 }
1609
1610 // Let the ImageWriter write the image file. If we do not compile PIC, also fix up the oat file.
1611 bool CreateImageFile()
1612 LOCKS_EXCLUDED(Locks::mutator_lock_) {
1613 CHECK(image_writer_ != nullptr);
1614 if (!image_writer_->Write(image_filename_, oat_unstripped_, oat_location_)) {
1615 LOG(ERROR) << "Failed to create image file " << image_filename_;
1616 return false;
1617 }
1618 uintptr_t oat_data_begin = image_writer_->GetOatDataBegin();
1619
1620 // Destroy ImageWriter before doing FixupElf.
1621 image_writer_.reset();
1622
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001623 // Do not fix up the ELF file if we are --compile-pic
1624 if (!compiler_options_->GetCompilePic()) {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001625 std::unique_ptr<File> oat_file(OS::OpenFileReadWrite(oat_unstripped_.c_str()));
1626 if (oat_file.get() == nullptr) {
1627 PLOG(ERROR) << "Failed to open ELF file: " << oat_unstripped_;
1628 return false;
1629 }
1630
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001631 if (!ElfWriter::Fixup(oat_file.get(), oat_data_begin)) {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001632 oat_file->Erase();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001633 LOG(ERROR) << "Failed to fixup ELF file " << oat_file->GetPath();
1634 return false;
1635 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001636
1637 if (oat_file->FlushCloseOrErase()) {
1638 PLOG(ERROR) << "Failed to flush and close fixed ELF file " << oat_file->GetPath();
1639 return false;
1640 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001641 }
1642
1643 return true;
1644 }
1645
1646 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001647 static std::unordered_set<std::string>* ReadImageClassesFromFile(
1648 const char* image_classes_filename) {
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001649 std::function<std::string(const char*)> process = DotToDescriptor;
1650 return ReadCommentedInputFromFile(image_classes_filename, &process);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001651 }
1652
1653 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001654 static std::unordered_set<std::string>* ReadImageClassesFromZip(
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001655 const char* zip_filename,
1656 const char* image_classes_filename,
1657 std::string* error_msg) {
1658 std::function<std::string(const char*)> process = DotToDescriptor;
1659 return ReadCommentedInputFromZip(zip_filename, image_classes_filename, &process, error_msg);
1660 }
1661
1662 // Read lines from the given file, dropping comments and empty lines. Post-process each line with
1663 // the given function.
1664 static std::unordered_set<std::string>* ReadCommentedInputFromFile(
1665 const char* input_filename, std::function<std::string(const char*)>* process) {
1666 std::unique_ptr<std::ifstream> input_file(new std::ifstream(input_filename, std::ifstream::in));
1667 if (input_file.get() == nullptr) {
1668 LOG(ERROR) << "Failed to open input file " << input_filename;
1669 return nullptr;
1670 }
1671 std::unique_ptr<std::unordered_set<std::string>> result(
1672 ReadCommentedInputStream(*input_file, process));
1673 input_file->close();
1674 return result.release();
1675 }
1676
1677 // Read lines from the given file from the given zip file, dropping comments and empty lines.
1678 // Post-process each line with the given function.
1679 static std::unordered_set<std::string>* ReadCommentedInputFromZip(
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001680 const char* zip_filename,
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001681 const char* input_filename,
1682 std::function<std::string(const char*)>* process,
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001683 std::string* error_msg) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001684 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::Open(zip_filename, error_msg));
1685 if (zip_archive.get() == nullptr) {
1686 return nullptr;
1687 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001688 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(input_filename, error_msg));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001689 if (zip_entry.get() == nullptr) {
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001690 *error_msg = StringPrintf("Failed to find '%s' within '%s': %s", input_filename,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001691 zip_filename, error_msg->c_str());
1692 return nullptr;
1693 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001694 std::unique_ptr<MemMap> input_file(zip_entry->ExtractToMemMap(zip_filename,
1695 input_filename,
1696 error_msg));
1697 if (input_file.get() == nullptr) {
1698 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", input_filename,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001699 zip_filename, error_msg->c_str());
1700 return nullptr;
1701 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001702 const std::string input_string(reinterpret_cast<char*>(input_file->Begin()),
1703 input_file->Size());
1704 std::istringstream input_stream(input_string);
1705 return ReadCommentedInputStream(input_stream, process);
1706 }
1707
1708 // Read lines from the given stream, dropping comments and empty lines. Post-process each line
1709 // with the given function.
1710 static std::unordered_set<std::string>* ReadCommentedInputStream(
1711 std::istream& in_stream,
1712 std::function<std::string(const char*)>* process) {
1713 std::unique_ptr<std::unordered_set<std::string>> image_classes(
1714 new std::unordered_set<std::string>);
1715 while (in_stream.good()) {
1716 std::string dot;
1717 std::getline(in_stream, dot);
1718 if (StartsWith(dot, "#") || dot.empty()) {
1719 continue;
1720 }
1721 if (process != nullptr) {
1722 std::string descriptor((*process)(dot.c_str()));
1723 image_classes->insert(descriptor);
1724 } else {
1725 image_classes->insert(dot);
1726 }
1727 }
1728 return image_classes.release();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001729 }
1730
Mathieu Chartier49285c52014-12-02 15:43:48 -08001731 void LogCompletionTime() {
Andreas Gampe1d00add2015-02-27 19:35:46 -08001732 // Note: when creation of a runtime fails, e.g., when trying to compile an app but when there
1733 // is no image, there won't be a Runtime::Current().
Brian Carlstroma11a34c2015-03-06 08:44:45 -08001734 // Note: driver creation can fail when loading an invalid dex file.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001735 LOG(INFO) << "dex2oat took " << PrettyDuration(NanoTime() - start_ns_)
Mathieu Chartierab972ef2014-12-03 17:38:22 -08001736 << " (threads: " << thread_count_ << ") "
Brian Carlstroma11a34c2015-03-06 08:44:45 -08001737 << ((Runtime::Current() != nullptr && driver_.get() != nullptr) ?
Andreas Gampe1d00add2015-02-27 19:35:46 -08001738 driver_->GetMemoryUsageString(kIsDebugBuild || VLOG_IS_ON(compiler)) :
1739 "");
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001740 }
1741
1742 std::unique_ptr<CompilerOptions> compiler_options_;
1743 Compiler::Kind compiler_kind_;
1744
1745 InstructionSet instruction_set_;
1746 std::unique_ptr<const InstructionSetFeatures> instruction_set_features_;
1747
1748 std::unique_ptr<SafeMap<std::string, std::string> > key_value_store_;
1749
1750 std::unique_ptr<VerificationResults> verification_results_;
1751 DexFileToMethodInlinerMap method_inliner_map_;
1752 std::unique_ptr<QuickCompilerCallbacks> callbacks_;
1753
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001754 // Ownership for the class path files.
1755 std::vector<std::unique_ptr<const DexFile>> class_path_files_;
1756
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001757 // Not a unique_ptr as we want to just exit on non-debug builds, not bringing the runtime down
1758 // in an orderly fashion. The destructor takes care of deleting this.
1759 Runtime* runtime_;
1760
1761 size_t thread_count_;
1762 uint64_t start_ns_;
1763 std::unique_ptr<WatchDog> watchdog_;
1764 std::unique_ptr<File> oat_file_;
1765 std::string oat_stripped_;
1766 std::string oat_unstripped_;
1767 std::string oat_location_;
1768 std::string oat_filename_;
1769 int oat_fd_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001770 std::vector<const char*> dex_filenames_;
1771 std::vector<const char*> dex_locations_;
1772 int zip_fd_;
1773 std::string zip_location_;
1774 std::string boot_image_option_;
1775 std::vector<const char*> runtime_args_;
1776 std::string image_filename_;
1777 uintptr_t image_base_;
1778 const char* image_classes_zip_filename_;
1779 const char* image_classes_filename_;
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001780 const char* compiled_classes_zip_filename_;
1781 const char* compiled_classes_filename_;
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001782 const char* compiled_methods_zip_filename_;
1783 const char* compiled_methods_filename_;
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001784 std::unique_ptr<std::unordered_set<std::string>> image_classes_;
1785 std::unique_ptr<std::unordered_set<std::string>> compiled_classes_;
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001786 std::unique_ptr<std::unordered_set<std::string>> compiled_methods_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001787 bool image_;
1788 std::unique_ptr<ImageWriter> image_writer_;
1789 bool is_host_;
1790 std::string android_root_;
1791 std::vector<const DexFile*> dex_files_;
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001792 std::vector<std::unique_ptr<const DexFile>> opened_dex_files_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001793 std::unique_ptr<CompilerDriver> driver_;
1794 std::vector<std::string> verbose_methods_;
1795 bool dump_stats_;
1796 bool dump_passes_;
1797 bool dump_timing_;
1798 bool dump_slow_timing_;
David Brazdil866c0312015-01-13 21:21:31 +00001799 std::string dump_cfg_file_name_;
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001800 std::string swap_file_name_;
1801 int swap_fd_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001802 std::string profile_file_; // Profile file to use
1803 TimingLogger* timings_;
1804 std::unique_ptr<CumulativeLogger> compiler_phases_timings_;
Andreas Gampedbfe2542014-11-25 22:21:42 -08001805 std::unique_ptr<std::ostream> init_failure_output_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001806
1807 DISALLOW_IMPLICIT_CONSTRUCTORS(Dex2Oat);
1808};
1809
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001810static void b13564922() {
1811#if defined(__linux__) && defined(__arm__)
1812 int major, minor;
1813 struct utsname uts;
1814 if (uname(&uts) != -1 &&
1815 sscanf(uts.release, "%d.%d", &major, &minor) == 2 &&
1816 ((major < 3) || ((major == 3) && (minor < 4)))) {
1817 // Kernels before 3.4 don't handle the ASLR well and we can run out of address
1818 // space (http://b/13564922). Work around the issue by inhibiting further mmap() randomization.
1819 int old_personality = personality(0xffffffff);
1820 if ((old_personality & ADDR_NO_RANDOMIZE) == 0) {
1821 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
1822 if (new_personality == -1) {
1823 LOG(WARNING) << "personality(. | ADDR_NO_RANDOMIZE) failed.";
1824 }
1825 }
1826 }
1827#endif
1828}
1829
Andreas Gampe10e477d2014-11-19 12:57:42 -08001830static int CompileImage(Dex2Oat& dex2oat) {
1831 dex2oat.Compile();
1832
1833 // Create the boot.oat.
1834 if (!dex2oat.CreateOatFile()) {
Andreas Gampea650e702014-12-03 14:28:02 -08001835 dex2oat.EraseOatFile();
Andreas Gampe10e477d2014-11-19 12:57:42 -08001836 return EXIT_FAILURE;
1837 }
1838
1839 // Flush and close the boot.oat. We always expect the output file by name, and it will be
1840 // re-opened from the unstripped name.
1841 if (!dex2oat.FlushCloseOatFile()) {
1842 return EXIT_FAILURE;
1843 }
1844
1845 // Creates the boot.art and patches the boot.oat.
1846 if (!dex2oat.HandleImage()) {
1847 return EXIT_FAILURE;
1848 }
1849
1850 // When given --host, finish early without stripping.
1851 if (dex2oat.IsHost()) {
1852 dex2oat.DumpTiming();
1853 return EXIT_SUCCESS;
1854 }
1855
1856 // Copy unstripped to stripped location, if necessary.
1857 if (!dex2oat.CopyUnstrippedToStripped()) {
1858 return EXIT_FAILURE;
1859 }
1860
Andreas Gampe10e477d2014-11-19 12:57:42 -08001861 // FlushClose again, as stripping might have re-opened the oat file.
1862 if (!dex2oat.FlushCloseOatFile()) {
1863 return EXIT_FAILURE;
1864 }
1865
1866 dex2oat.DumpTiming();
1867 return EXIT_SUCCESS;
1868}
1869
1870static int CompileApp(Dex2Oat& dex2oat) {
1871 dex2oat.Compile();
1872
1873 // Create the app oat.
1874 if (!dex2oat.CreateOatFile()) {
Andreas Gampea650e702014-12-03 14:28:02 -08001875 dex2oat.EraseOatFile();
Andreas Gampe10e477d2014-11-19 12:57:42 -08001876 return EXIT_FAILURE;
1877 }
1878
1879 // Do not close the oat file here. We might haven gotten the output file by file descriptor,
1880 // which we would lose.
1881 if (!dex2oat.FlushOatFile()) {
1882 return EXIT_FAILURE;
1883 }
1884
1885 // When given --host, finish early without stripping.
1886 if (dex2oat.IsHost()) {
1887 if (!dex2oat.FlushCloseOatFile()) {
1888 return EXIT_FAILURE;
1889 }
1890
1891 dex2oat.DumpTiming();
1892 return EXIT_SUCCESS;
1893 }
1894
1895 // Copy unstripped to stripped location, if necessary. This will implicitly flush & close the
1896 // unstripped version. If this is given, we expect to be able to open writable files by name.
1897 if (!dex2oat.CopyUnstrippedToStripped()) {
1898 return EXIT_FAILURE;
1899 }
1900
Andreas Gampe10e477d2014-11-19 12:57:42 -08001901 // Flush and close the file.
1902 if (!dex2oat.FlushCloseOatFile()) {
1903 return EXIT_FAILURE;
1904 }
1905
1906 dex2oat.DumpTiming();
1907 return EXIT_SUCCESS;
1908}
1909
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001910static int dex2oat(int argc, char** argv) {
1911 b13564922();
1912
1913 TimingLogger timings("compiler", false, false);
1914
1915 Dex2Oat dex2oat(&timings);
1916
1917 // Parse arguments. Argument mistakes will lead to exit(EXIT_FAILURE) in UsageError.
1918 dex2oat.ParseArgs(argc, argv);
1919
1920 // Check early that the result of compilation can be written
1921 if (!dex2oat.OpenFile()) {
1922 return EXIT_FAILURE;
1923 }
1924
1925 LOG(INFO) << CommandLine();
1926
1927 if (!dex2oat.Setup()) {
Andreas Gampea650e702014-12-03 14:28:02 -08001928 dex2oat.EraseOatFile();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001929 return EXIT_FAILURE;
1930 }
1931
Andreas Gampe10e477d2014-11-19 12:57:42 -08001932 if (dex2oat.IsImage()) {
1933 return CompileImage(dex2oat);
1934 } else {
1935 return CompileApp(dex2oat);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001936 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001937}
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001938} // namespace art
Brian Carlstrom7940e442013-07-12 13:46:57 -07001939
1940int main(int argc, char** argv) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001941 int result = art::dex2oat(argc, argv);
1942 // Everything was done, do an explicit exit here to avoid running Runtime destructors that take
1943 // time (bug 10645725) unless we're a debug build or running on valgrind. Note: The Dex2Oat class
1944 // should not destruct the runtime in this case.
1945 if (!art::kIsDebugBuild && (RUNNING_ON_VALGRIND == 0)) {
1946 exit(result);
1947 }
1948 return result;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001949}