blob: 3cf458ab5b76b5b0ca87855128a599af2f8ab6fb [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"
44#include "base/timing_logger.h"
45#include "base/unix_file/fd_file.h"
46#include "class_linker.h"
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +000047#include "compiler.h"
Vladimir Marko2b5eaa22013-12-13 13:59:30 +000048#include "compiler_callbacks.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070049#include "dex_file-inl.h"
Mathieu Chartier5bdab122015-01-26 18:30:19 -080050#include "dex/pass_manager.h"
Vladimir Markoc7f83202014-01-24 17:55:18 +000051#include "dex/verification_results.h"
Ian Rogerse63db272014-07-15 15:36:11 -070052#include "dex/quick_compiler_callbacks.h"
53#include "dex/quick/dex_file_to_method_inliner_map.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070054#include "driver/compiler_driver.h"
Brian Carlstrom6449c622014-02-10 23:48:36 -080055#include "driver/compiler_options.h"
Andreas Gampe88ec7f42014-11-05 10:18:32 -080056#include "elf_file.h"
Tong Shen62d1ca32014-09-03 17:24:56 -070057#include "elf_writer.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070058#include "gc/space/image_space.h"
59#include "gc/space/space-inl.h"
60#include "image_writer.h"
Andreas Gampe2969bcd2015-03-09 12:57:41 -070061#include "interpreter/unstarted_runtime.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070062#include "leb128.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070063#include "mirror/art_method-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070064#include "mirror/class-inl.h"
65#include "mirror/class_loader.h"
66#include "mirror/object-inl.h"
67#include "mirror/object_array-inl.h"
68#include "oat_writer.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070069#include "os.h"
70#include "runtime.h"
71#include "ScopedLocalRef.h"
72#include "scoped_thread_state_change.h"
Alex Light53cb16b2014-06-12 11:26:29 -070073#include "utils.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070074#include "vector_output_stream.h"
75#include "well_known_classes.h"
76#include "zip_archive.h"
77
78namespace art {
79
Brian Carlstrom6449c622014-02-10 23:48:36 -080080static int original_argc;
81static char** original_argv;
82
83static std::string CommandLine() {
84 std::vector<std::string> command;
85 for (int i = 0; i < original_argc; ++i) {
86 command.push_back(original_argv[i]);
87 }
88 return Join(command, ' ');
89}
90
Brian Carlstrom7940e442013-07-12 13:46:57 -070091static void UsageErrorV(const char* fmt, va_list ap) {
92 std::string error;
93 StringAppendV(&error, fmt, ap);
94 LOG(ERROR) << error;
95}
96
97static void UsageError(const char* fmt, ...) {
98 va_list ap;
99 va_start(ap, fmt);
100 UsageErrorV(fmt, ap);
101 va_end(ap);
102}
103
Andreas Gampe794ad762015-02-23 08:12:24 -0800104NO_RETURN static void Usage(const char* fmt, ...) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700105 va_list ap;
106 va_start(ap, fmt);
107 UsageErrorV(fmt, ap);
108 va_end(ap);
109
Brian Carlstrom6449c622014-02-10 23:48:36 -0800110 UsageError("Command: %s", CommandLine().c_str());
111
Brian Carlstrom7940e442013-07-12 13:46:57 -0700112 UsageError("Usage: dex2oat [options]...");
113 UsageError("");
Jean-Philippe Halimi3d329d72015-03-23 14:09:48 +0100114 UsageError(" -j<number>: specifies the number of threads used for compilation.");
115 UsageError(" Default is the number of detected hardware threads available on the");
116 UsageError(" host system.");
117 UsageError(" Example: -j12");
118 UsageError("");
Richard Uhlere934df22015-03-17 11:26:16 -0700119 UsageError(" --dex-file=<dex-file>: specifies a .dex, .jar, or .apk file to compile.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700120 UsageError(" Example: --dex-file=/system/framework/core.jar");
121 UsageError("");
Richard Uhlere934df22015-03-17 11:26:16 -0700122 UsageError(" --dex-location=<dex-location>: specifies an alternative dex location to");
123 UsageError(" encode in the oat file for the corresponding --dex-file argument.");
124 UsageError(" Example: --dex-file=/home/build/out/system/framework/core.jar");
125 UsageError(" --dex-location=/system/framework/core.jar");
126 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700127 UsageError(" --zip-fd=<file-descriptor>: specifies a file descriptor of a zip file");
128 UsageError(" containing a classes.dex file to compile.");
129 UsageError(" Example: --zip-fd=5");
130 UsageError("");
Brian Carlstrom45602482013-07-21 22:07:55 -0700131 UsageError(" --zip-location=<zip-location>: specifies a symbolic name for the file");
132 UsageError(" corresponding to the file descriptor specified by --zip-fd.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700133 UsageError(" Example: --zip-location=/system/app/Calculator.apk");
134 UsageError("");
135 UsageError(" --oat-file=<file.oat>: specifies the oat output destination via a filename.");
136 UsageError(" Example: --oat-file=/system/framework/boot.oat");
137 UsageError("");
138 UsageError(" --oat-fd=<number>: specifies the oat output destination via a file descriptor.");
Wonil Kim9cb554a2014-04-28 11:26:55 +0900139 UsageError(" Example: --oat-fd=6");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700140 UsageError("");
141 UsageError(" --oat-location=<oat-name>: specifies a symbolic name for the file corresponding");
142 UsageError(" to the file descriptor specified by --oat-fd.");
143 UsageError(" Example: --oat-location=/data/dalvik-cache/system@app@Calculator.apk.oat");
144 UsageError("");
145 UsageError(" --oat-symbols=<file.oat>: specifies the oat output destination with full symbols.");
146 UsageError(" Example: --oat-symbols=/symbols/system/framework/boot.oat");
147 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700148 UsageError(" --image=<file.art>: specifies the output image filename.");
149 UsageError(" Example: --image=/system/framework/boot.art");
150 UsageError("");
151 UsageError(" --image-classes=<classname-file>: specifies classes to include in an image.");
152 UsageError(" Example: --image=frameworks/base/preloaded-classes");
153 UsageError("");
154 UsageError(" --base=<hex-address>: specifies the base address when creating a boot image.");
155 UsageError(" Example: --base=0x50000000");
156 UsageError("");
157 UsageError(" --boot-image=<file.art>: provide the image file for the boot class path.");
158 UsageError(" Example: --boot-image=/system/framework/boot.art");
Nicolas Geoffray9583fbc2014-02-28 15:21:07 +0000159 UsageError(" Default: $ANDROID_ROOT/system/framework/boot.art");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700160 UsageError("");
161 UsageError(" --android-root=<path>: used to locate libraries for portable linking.");
162 UsageError(" Example: --android-root=out/host/linux-x86");
163 UsageError(" Default: $ANDROID_ROOT");
164 UsageError("");
Andreas Gampe57b34292015-01-14 15:45:59 -0800165 UsageError(" --instruction-set=(arm|arm64|mips|mips64|x86|x86_64): compile for a particular");
Alex Light53cb16b2014-06-12 11:26:29 -0700166 UsageError(" instruction set.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700167 UsageError(" Example: --instruction-set=x86");
168 UsageError(" Default: arm");
169 UsageError("");
Dave Allison70202782013-10-22 17:52:19 -0700170 UsageError(" --instruction-set-features=...,: Specify instruction set features");
171 UsageError(" Example: --instruction-set-features=div");
172 UsageError(" Default: default");
173 UsageError("");
Igor Murashkin46774762014-10-22 11:37:02 -0700174 UsageError(" --compile-pic: Force indirect use of code, methods, and classes");
175 UsageError(" Default: disabled");
176 UsageError("");
Elliott Hughes956af0f2014-12-11 14:34:28 -0800177 UsageError(" --compiler-backend=(Quick|Optimizing): select compiler backend");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700178 UsageError(" set.");
Elliott Hughes956af0f2014-12-11 14:34:28 -0800179 UsageError(" Example: --compiler-backend=Optimizing");
180 if (kUseOptimizingCompiler) {
Nicolas Geoffray4586fb62014-11-28 16:22:11 +0000181 UsageError(" Default: Optimizing");
182 } else {
183 UsageError(" Default: Quick");
184 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700185 UsageError("");
Nicolas Geoffray88157ef2014-09-12 10:29:53 +0100186 UsageError(" --compiler-filter="
187 "(verify-none"
188 "|interpret-only"
189 "|space"
190 "|balanced"
191 "|speed"
192 "|everything"
193 "|time):");
Jeff Hao4a200f52014-04-01 14:58:49 -0700194 UsageError(" select compiler filter.");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800195 UsageError(" Example: --compiler-filter=everything");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800196 UsageError(" Default: speed");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800197 UsageError("");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800198 UsageError(" --huge-method-max=<method-instruction-count>: threshold size for a huge");
199 UsageError(" method for compiler filter tuning.");
200 UsageError(" Example: --huge-method-max=%d", CompilerOptions::kDefaultHugeMethodThreshold);
201 UsageError(" Default: %d", CompilerOptions::kDefaultHugeMethodThreshold);
202 UsageError("");
203 UsageError(" --large-method-max=<method-instruction-count>: threshold size for a large");
204 UsageError(" method for compiler filter tuning.");
205 UsageError(" Example: --large-method-max=%d", CompilerOptions::kDefaultLargeMethodThreshold);
206 UsageError(" Default: %d", CompilerOptions::kDefaultLargeMethodThreshold);
207 UsageError("");
208 UsageError(" --small-method-max=<method-instruction-count>: threshold size for a small");
209 UsageError(" method for compiler filter tuning.");
210 UsageError(" Example: --small-method-max=%d", CompilerOptions::kDefaultSmallMethodThreshold);
211 UsageError(" Default: %d", CompilerOptions::kDefaultSmallMethodThreshold);
212 UsageError("");
213 UsageError(" --tiny-method-max=<method-instruction-count>: threshold size for a tiny");
214 UsageError(" method for compiler filter tuning.");
215 UsageError(" Example: --tiny-method-max=%d", CompilerOptions::kDefaultTinyMethodThreshold);
216 UsageError(" Default: %d", CompilerOptions::kDefaultTinyMethodThreshold);
217 UsageError("");
218 UsageError(" --num-dex-methods=<method-count>: threshold size for a small dex file for");
219 UsageError(" compiler filter tuning. If the input has fewer than this many methods");
Jeff Hao4a200f52014-04-01 14:58:49 -0700220 UsageError(" and the filter is not interpret-only or verify-none, overrides the");
221 UsageError(" filter to use speed");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800222 UsageError(" Example: --num-dex-method=%d", CompilerOptions::kDefaultNumDexMethodsThreshold);
223 UsageError(" Default: %d", CompilerOptions::kDefaultNumDexMethodsThreshold);
224 UsageError("");
Ian Rogers46398602013-08-20 07:50:36 -0700225 UsageError(" --dump-timing: display a breakdown of where time was spent");
226 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700227 UsageError(" --include-patch-information: Include patching information so the generated code");
228 UsageError(" can have its base address moved without full recompilation.");
229 UsageError("");
230 UsageError(" --no-include-patch-information: Do not include patching information.");
231 UsageError("");
Alex Light78382fa2014-06-06 15:45:32 -0700232 UsageError(" --include-debug-symbols: Include ELF symbols in this oat file");
233 UsageError("");
234 UsageError(" --no-include-debug-symbols: Do not include ELF symbols in this oat file");
235 UsageError("");
David Srbecky8dc73242015-04-12 11:40:39 +0100236 UsageError(" --include-cfi: Include call frame information in the .eh_frame section.");
237 UsageError(" The --include-debug-symbols option implies --include-cfi.");
238 UsageError("");
239 UsageError(" --no-include-cfi: Do not include call frame information in the .eh_frame section.");
240 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700241 UsageError(" --runtime-arg <argument>: used to specify various arguments for the runtime,");
242 UsageError(" such as initial heap size, maximum heap size, and verbose output.");
243 UsageError(" Use a separate --runtime-arg switch for each argument.");
244 UsageError(" Example: --runtime-arg -Xms256m");
Jeff Hao4a200f52014-04-01 14:58:49 -0700245 UsageError("");
Dave Allisond6ed6422014-04-09 23:36:15 +0000246 UsageError(" --profile-file=<filename>: specify profiler output file to use for compilation.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700247 UsageError("");
Chao-ying Fucd8ce662014-03-11 14:57:19 -0700248 UsageError(" --print-pass-names: print a list of pass names");
249 UsageError("");
250 UsageError(" --disable-passes=<pass-names>: disable one or more passes separated by comma.");
251 UsageError(" Example: --disable-passes=UseCount,BBOptimizations");
252 UsageError("");
Razvan A Lupusorubd25d4b2014-07-02 18:16:51 -0700253 UsageError(" --print-pass-options: print a list of passes that have configurable options along "
254 "with the setting.");
255 UsageError(" Will print default if no overridden setting exists.");
256 UsageError("");
257 UsageError(" --pass-options=Pass1Name:Pass1OptionName:Pass1Option#,"
258 "Pass2Name:Pass2OptionName:Pass2Option#");
259 UsageError(" Used to specify a pass specific option. The setting itself must be integer.");
260 UsageError(" Separator used between options is a comma.");
261 UsageError("");
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800262 UsageError(" --swap-file=<file-name>: specifies a file to use for swap.");
263 UsageError(" Example: --swap-file=/data/tmp/swap.001");
264 UsageError("");
265 UsageError(" --swap-fd=<file-descriptor>: specifies a file to use for swap (by descriptor).");
266 UsageError(" Example: --swap-fd=10");
267 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700268 std::cerr << "See log for usage error information\n";
269 exit(EXIT_FAILURE);
270}
271
Brian Carlstrom7940e442013-07-12 13:46:57 -0700272// The primary goal of the watchdog is to prevent stuck build servers
273// during development when fatal aborts lead to a cascade of failures
274// that result in a deadlock.
275class WatchDog {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800276// WatchDog defines its own CHECK_PTHREAD_CALL to avoid using LOG which uses locks
Brian Carlstrom7940e442013-07-12 13:46:57 -0700277#undef CHECK_PTHREAD_CALL
278#define CHECK_WATCH_DOG_PTHREAD_CALL(call, args, what) \
279 do { \
280 int rc = call args; \
281 if (rc != 0) { \
282 errno = rc; \
283 std::string message(# call); \
284 message += " failed for "; \
285 message += reason; \
286 Fatal(message); \
287 } \
288 } while (false)
289
290 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -0700291 explicit WatchDog(bool is_watch_dog_enabled) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700292 is_watch_dog_enabled_ = is_watch_dog_enabled;
293 if (!is_watch_dog_enabled_) {
294 return;
295 }
296 shutting_down_ = false;
297 const char* reason = "dex2oat watch dog thread startup";
Kenny Root51316382014-05-13 14:59:37 -0700298 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_init, (&mutex_, nullptr), reason);
299 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_init, (&cond_, nullptr), reason);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700300 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_init, (&attr_), reason);
301 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_create, (&pthread_, &attr_, &CallBack, this), reason);
302 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_destroy, (&attr_), reason);
303 }
304 ~WatchDog() {
305 if (!is_watch_dog_enabled_) {
306 return;
307 }
308 const char* reason = "dex2oat watch dog thread shutdown";
309 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
310 shutting_down_ = true;
311 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_signal, (&cond_), reason);
312 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
313
Kenny Root51316382014-05-13 14:59:37 -0700314 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_join, (pthread_, nullptr), reason);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700315
316 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_destroy, (&cond_), reason);
317 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_destroy, (&mutex_), reason);
318 }
319
320 private:
321 static void* CallBack(void* arg) {
322 WatchDog* self = reinterpret_cast<WatchDog*>(arg);
323 ::art::SetThreadName("dex2oat watch dog");
324 self->Wait();
Kenny Root51316382014-05-13 14:59:37 -0700325 return nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700326 }
327
Andreas Gampe794ad762015-02-23 08:12:24 -0800328 NO_RETURN static void Fatal(const std::string& message) {
Andreas Gamped687e372015-04-28 23:16:03 -0700329 // TODO: When we can guarantee it won't prevent shutdown in error cases, move to LOG. However,
330 // it's rather easy to hang in unwinding.
331 // LogLine also avoids ART logging lock issues, as it's really only a wrapper around
332 // logcat logging or stderr output.
333 LogMessage::LogLine(__FILE__, __LINE__, LogSeverity::FATAL, message.c_str());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700334 exit(1);
335 }
336
337 void Wait() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700338 // TODO: tune the multiplier for GC verification, the following is just to make the timeout
339 // large.
Andreas Gamped687e372015-04-28 23:16:03 -0700340 constexpr int64_t multiplier = kVerifyObjectSupport > kVerifyObjectModeFast ? 100 : 1;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700341 timespec timeout_ts;
342 InitTimeSpec(true, CLOCK_REALTIME, multiplier * kWatchDogTimeoutSeconds * 1000, 0, &timeout_ts);
343 const char* reason = "dex2oat watch dog thread waiting";
344 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
345 while (!shutting_down_) {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800346 int rc = TEMP_FAILURE_RETRY(pthread_cond_timedwait(&cond_, &mutex_, &timeout_ts));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700347 if (rc == ETIMEDOUT) {
Andreas Gamped687e372015-04-28 23:16:03 -0700348 Fatal(StringPrintf("dex2oat did not finish after %" PRId64 " seconds",
349 kWatchDogTimeoutSeconds));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700350 } else if (rc != 0) {
351 std::string message(StringPrintf("pthread_cond_timedwait failed: %s",
352 strerror(errno)));
353 Fatal(message.c_str());
354 }
355 }
356 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
357 }
358
359 // 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 -0700360 // Debug builds are slower so they have larger timeouts.
Andreas Gamped687e372015-04-28 23:16:03 -0700361 static constexpr int64_t kSlowdownFactor = kIsDebugBuild ? 5U : 1U;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800362
Andreas Gamped687e372015-04-28 23:16:03 -0700363 // 10 minutes scaled by kSlowdownFactor.
364 static constexpr int64_t kWatchDogTimeoutSeconds = kSlowdownFactor * 10 * 60;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700365
366 bool is_watch_dog_enabled_;
367 bool shutting_down_;
368 // TODO: Switch to Mutex when we can guarantee it won't prevent shutdown in error cases.
369 pthread_mutex_t mutex_;
370 pthread_cond_t cond_;
371 pthread_attr_t attr_;
372 pthread_t pthread_;
373};
Brian Carlstrom7940e442013-07-12 13:46:57 -0700374
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800375static void ParseStringAfterChar(const std::string& s, char c, std::string* parsed_value) {
Calin Juravlec1b643c2014-05-30 23:44:11 +0100376 std::string::size_type colon = s.find(c);
377 if (colon == std::string::npos) {
378 Usage("Missing char %c in option %s\n", c, s.c_str());
379 }
380 // Add one to remove the char we were trimming until.
381 *parsed_value = s.substr(colon + 1);
382}
383
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800384static void ParseDouble(const std::string& option, char after_char, double min, double max,
385 double* parsed_value) {
Calin Juravlec1b643c2014-05-30 23:44:11 +0100386 std::string substring;
387 ParseStringAfterChar(option, after_char, &substring);
388 bool sane_val = true;
389 double value;
390 if (false) {
391 // TODO: this doesn't seem to work on the emulator. b/15114595
392 std::stringstream iss(substring);
393 iss >> value;
394 // Ensure that we have a value, there was no cruft after it and it satisfies a sensible range.
395 sane_val = iss.eof() && (value >= min) && (value <= max);
396 } else {
397 char* end = nullptr;
398 value = strtod(substring.c_str(), &end);
399 sane_val = *end == '\0' && value >= min && value <= max;
400 }
401 if (!sane_val) {
402 Usage("Invalid double value %s for option %s\n", substring.c_str(), option.c_str());
403 }
404 *parsed_value = value;
405}
406
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800407static constexpr size_t kMinDexFilesForSwap = 2;
408static constexpr size_t kMinDexFileCumulativeSizeForSwap = 20 * MB;
409
410static bool UseSwap(bool is_image, std::vector<const DexFile*>& dex_files) {
411 if (is_image) {
412 // Don't use swap, we know generation should succeed, and we don't want to slow it down.
413 return false;
414 }
415 if (dex_files.size() < kMinDexFilesForSwap) {
416 // If there are less dex files than the threshold, assume it's gonna be fine.
417 return false;
418 }
419 size_t dex_files_size = 0;
420 for (const auto* dex_file : dex_files) {
421 dex_files_size += dex_file->GetHeader().file_size_;
422 }
423 return dex_files_size >= kMinDexFileCumulativeSizeForSwap;
424}
425
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800426class Dex2Oat FINAL {
427 public:
428 explicit Dex2Oat(TimingLogger* timings) :
Elliott Hughes956af0f2014-12-11 14:34:28 -0800429 compiler_kind_(kUseOptimizingCompiler ? Compiler::kOptimizing : Compiler::kQuick),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800430 instruction_set_(kRuntimeISA),
431 // Take the default set of instruction features from the build.
432 method_inliner_map_(),
433 runtime_(nullptr),
434 thread_count_(sysconf(_SC_NPROCESSORS_CONF)),
435 start_ns_(NanoTime()),
436 oat_fd_(-1),
437 zip_fd_(-1),
438 image_base_(0U),
439 image_classes_zip_filename_(nullptr),
440 image_classes_filename_(nullptr),
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800441 compiled_classes_zip_filename_(nullptr),
442 compiled_classes_filename_(nullptr),
Andreas Gampe70bef0d2015-04-15 02:37:28 -0700443 compiled_methods_zip_filename_(nullptr),
444 compiled_methods_filename_(nullptr),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800445 image_(false),
446 is_host_(false),
447 dump_stats_(false),
448 dump_passes_(false),
449 dump_timing_(false),
450 dump_slow_timing_(kIsDebugBuild),
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800451 swap_fd_(-1),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800452 timings_(timings) {}
453
454 ~Dex2Oat() {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800455 // Free opened dex files before deleting the runtime_, because ~DexFile
456 // uses MemMap, which is shut down by ~Runtime.
457 class_path_files_.clear();
458 opened_dex_files_.clear();
459
460 // Log completion time before deleting the runtime_, because this accesses
461 // the runtime.
462 LogCompletionTime();
463
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800464 if (kIsDebugBuild || (RUNNING_ON_VALGRIND != 0)) {
465 delete runtime_; // See field declaration for why this is manual.
Vladimir Markof94b7812014-06-05 15:48:04 +0100466 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700467 }
468
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800469 // Parse the arguments from the command line. In case of an unrecognized option or impossible
470 // values/combinations, a usage error will be displayed and exit() is called. Thus, if the method
471 // returns, arguments have been successfully parsed.
472 void ParseArgs(int argc, char** argv) {
473 original_argc = argc;
474 original_argv = argv;
Dave Allison70202782013-10-22 17:52:19 -0700475
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800476 InitLogging(argv);
Dave Allison70202782013-10-22 17:52:19 -0700477
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800478 // Skip over argv[0].
479 argv++;
480 argc--;
Dave Allison70202782013-10-22 17:52:19 -0700481
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800482 if (argc == 0) {
483 Usage("No arguments specified");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700484 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800485
486 std::string oat_symbols;
487 std::string boot_image_filename;
488 const char* compiler_filter_string = nullptr;
489 bool compile_pic = false;
490 int huge_method_threshold = CompilerOptions::kDefaultHugeMethodThreshold;
491 int large_method_threshold = CompilerOptions::kDefaultLargeMethodThreshold;
492 int small_method_threshold = CompilerOptions::kDefaultSmallMethodThreshold;
493 int tiny_method_threshold = CompilerOptions::kDefaultTinyMethodThreshold;
494 int num_dex_methods_threshold = CompilerOptions::kDefaultNumDexMethodsThreshold;
495
496 // Profile file to use
497 double top_k_profile_threshold = CompilerOptions::kDefaultTopKProfileThreshold;
498
Andreas Gampe7b2f09e2015-03-02 14:07:33 -0800499 bool debuggable = false;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800500 bool include_patch_information = CompilerOptions::kDefaultIncludePatchInformation;
501 bool include_debug_symbols = kIsDebugBuild;
David Srbecky8dc73242015-04-12 11:40:39 +0100502 bool include_cfi = kIsDebugBuild;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800503 bool watch_dog_enabled = true;
Andreas Gampe6cf49e52015-03-05 13:08:45 -0800504 bool abort_on_hard_verifier_error = false;
Nicolas Geoffray1412dfa2015-03-20 14:48:13 +0000505 bool requested_specific_compiler = false;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800506
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800507 PassManagerOptions pass_manager_options;
508
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800509 std::string error_msg;
510
511 for (int i = 0; i < argc; i++) {
512 const StringPiece option(argv[i]);
513 const bool log_options = false;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700514 if (log_options) {
515 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
516 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800517 if (option.starts_with("--dex-file=")) {
518 dex_filenames_.push_back(option.substr(strlen("--dex-file=")).data());
519 } else if (option.starts_with("--dex-location=")) {
520 dex_locations_.push_back(option.substr(strlen("--dex-location=")).data());
521 } else if (option.starts_with("--zip-fd=")) {
522 const char* zip_fd_str = option.substr(strlen("--zip-fd=")).data();
523 if (!ParseInt(zip_fd_str, &zip_fd_)) {
524 Usage("Failed to parse --zip-fd argument '%s' as an integer", zip_fd_str);
525 }
526 if (zip_fd_ < 0) {
527 Usage("--zip-fd passed a negative value %d", zip_fd_);
528 }
529 } else if (option.starts_with("--zip-location=")) {
530 zip_location_ = option.substr(strlen("--zip-location=")).data();
531 } else if (option.starts_with("--oat-file=")) {
532 oat_filename_ = option.substr(strlen("--oat-file=")).data();
533 } else if (option.starts_with("--oat-symbols=")) {
534 oat_symbols = option.substr(strlen("--oat-symbols=")).data();
535 } else if (option.starts_with("--oat-fd=")) {
536 const char* oat_fd_str = option.substr(strlen("--oat-fd=")).data();
537 if (!ParseInt(oat_fd_str, &oat_fd_)) {
538 Usage("Failed to parse --oat-fd argument '%s' as an integer", oat_fd_str);
539 }
540 if (oat_fd_ < 0) {
541 Usage("--oat-fd passed a negative value %d", oat_fd_);
542 }
543 } else if (option == "--watch-dog") {
544 watch_dog_enabled = true;
545 } else if (option == "--no-watch-dog") {
546 watch_dog_enabled = false;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800547 } else if (option.starts_with("-j")) {
548 const char* thread_count_str = option.substr(strlen("-j")).data();
549 if (!ParseUint(thread_count_str, &thread_count_)) {
550 Usage("Failed to parse -j argument '%s' as an integer", thread_count_str);
551 }
552 } else if (option.starts_with("--oat-location=")) {
553 oat_location_ = option.substr(strlen("--oat-location=")).data();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800554 } else if (option.starts_with("--image=")) {
555 image_filename_ = option.substr(strlen("--image=")).data();
556 } else if (option.starts_with("--image-classes=")) {
557 image_classes_filename_ = option.substr(strlen("--image-classes=")).data();
558 } else if (option.starts_with("--image-classes-zip=")) {
559 image_classes_zip_filename_ = option.substr(strlen("--image-classes-zip=")).data();
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800560 } else if (option.starts_with("--compiled-classes=")) {
561 compiled_classes_filename_ = option.substr(strlen("--compiled-classes=")).data();
562 } else if (option.starts_with("--compiled-classes-zip=")) {
563 compiled_classes_zip_filename_ = option.substr(strlen("--compiled-classes-zip=")).data();
Andreas Gampe70bef0d2015-04-15 02:37:28 -0700564 } else if (option.starts_with("--compiled-methods=")) {
565 compiled_methods_filename_ = option.substr(strlen("--compiled-methods=")).data();
566 } else if (option.starts_with("--compiled-methods-zip=")) {
567 compiled_methods_zip_filename_ = option.substr(strlen("--compiled-methods-zip=")).data();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800568 } else if (option.starts_with("--base=")) {
569 const char* image_base_str = option.substr(strlen("--base=")).data();
570 char* end;
571 image_base_ = strtoul(image_base_str, &end, 16);
572 if (end == image_base_str || *end != '\0') {
573 Usage("Failed to parse hexadecimal value for option %s", option.data());
574 }
575 } else if (option.starts_with("--boot-image=")) {
576 boot_image_filename = option.substr(strlen("--boot-image=")).data();
577 } else if (option.starts_with("--android-root=")) {
578 android_root_ = option.substr(strlen("--android-root=")).data();
579 } else if (option.starts_with("--instruction-set=")) {
580 StringPiece instruction_set_str = option.substr(strlen("--instruction-set=")).data();
581 // StringPiece is not necessarily zero-terminated, so need to make a copy and ensure it.
Dan Albert6fc59ab2014-12-11 14:09:51 -0800582 std::unique_ptr<char[]> buf(new char[instruction_set_str.length() + 1]);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800583 strncpy(buf.get(), instruction_set_str.data(), instruction_set_str.length());
584 buf.get()[instruction_set_str.length()] = 0;
585 instruction_set_ = GetInstructionSetFromString(buf.get());
586 // arm actually means thumb2.
587 if (instruction_set_ == InstructionSet::kArm) {
588 instruction_set_ = InstructionSet::kThumb2;
589 }
590 } else if (option.starts_with("--instruction-set-variant=")) {
591 StringPiece str = option.substr(strlen("--instruction-set-variant=")).data();
592 instruction_set_features_.reset(
593 InstructionSetFeatures::FromVariant(instruction_set_, str.as_string(), &error_msg));
594 if (instruction_set_features_.get() == nullptr) {
595 Usage("%s", error_msg.c_str());
596 }
597 } else if (option.starts_with("--instruction-set-features=")) {
598 StringPiece str = option.substr(strlen("--instruction-set-features=")).data();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800599 if (instruction_set_features_.get() == nullptr) {
Ian Rogersd582fa42014-11-05 23:46:43 -0800600 instruction_set_features_.reset(
601 InstructionSetFeatures::FromVariant(instruction_set_, "default", &error_msg));
602 if (instruction_set_features_.get() == nullptr) {
603 Usage("Problem initializing default instruction set features variant: %s",
604 error_msg.c_str());
605 }
606 }
607 instruction_set_features_.reset(
608 instruction_set_features_->AddFeaturesFromString(str.as_string(), &error_msg));
609 if (instruction_set_features_.get() == nullptr) {
610 Usage("Error parsing '%s': %s", option.data(), error_msg.c_str());
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800611 }
612 } else if (option.starts_with("--compiler-backend=")) {
Nicolas Geoffray1412dfa2015-03-20 14:48:13 +0000613 requested_specific_compiler = true;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800614 StringPiece backend_str = option.substr(strlen("--compiler-backend=")).data();
615 if (backend_str == "Quick") {
616 compiler_kind_ = Compiler::kQuick;
617 } else if (backend_str == "Optimizing") {
618 compiler_kind_ = Compiler::kOptimizing;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800619 } else {
620 Usage("Unknown compiler backend: %s", backend_str.data());
621 }
622 } else if (option.starts_with("--compiler-filter=")) {
623 compiler_filter_string = option.substr(strlen("--compiler-filter=")).data();
624 } else if (option == "--compile-pic") {
625 compile_pic = true;
626 } else if (option.starts_with("--huge-method-max=")) {
627 const char* threshold = option.substr(strlen("--huge-method-max=")).data();
628 if (!ParseInt(threshold, &huge_method_threshold)) {
629 Usage("Failed to parse --huge-method-max '%s' as an integer", threshold);
630 }
631 if (huge_method_threshold < 0) {
632 Usage("--huge-method-max passed a negative value %s", huge_method_threshold);
633 }
634 } else if (option.starts_with("--large-method-max=")) {
635 const char* threshold = option.substr(strlen("--large-method-max=")).data();
636 if (!ParseInt(threshold, &large_method_threshold)) {
637 Usage("Failed to parse --large-method-max '%s' as an integer", threshold);
638 }
639 if (large_method_threshold < 0) {
640 Usage("--large-method-max passed a negative value %s", large_method_threshold);
641 }
642 } else if (option.starts_with("--small-method-max=")) {
643 const char* threshold = option.substr(strlen("--small-method-max=")).data();
644 if (!ParseInt(threshold, &small_method_threshold)) {
645 Usage("Failed to parse --small-method-max '%s' as an integer", threshold);
646 }
647 if (small_method_threshold < 0) {
648 Usage("--small-method-max passed a negative value %s", small_method_threshold);
649 }
650 } else if (option.starts_with("--tiny-method-max=")) {
651 const char* threshold = option.substr(strlen("--tiny-method-max=")).data();
652 if (!ParseInt(threshold, &tiny_method_threshold)) {
653 Usage("Failed to parse --tiny-method-max '%s' as an integer", threshold);
654 }
655 if (tiny_method_threshold < 0) {
656 Usage("--tiny-method-max passed a negative value %s", tiny_method_threshold);
657 }
658 } else if (option.starts_with("--num-dex-methods=")) {
659 const char* threshold = option.substr(strlen("--num-dex-methods=")).data();
660 if (!ParseInt(threshold, &num_dex_methods_threshold)) {
661 Usage("Failed to parse --num-dex-methods '%s' as an integer", threshold);
662 }
663 if (num_dex_methods_threshold < 0) {
664 Usage("--num-dex-methods passed a negative value %s", num_dex_methods_threshold);
665 }
666 } else if (option == "--host") {
667 is_host_ = true;
668 } else if (option == "--runtime-arg") {
669 if (++i >= argc) {
670 Usage("Missing required argument for --runtime-arg");
671 }
672 if (log_options) {
673 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
674 }
675 runtime_args_.push_back(argv[i]);
676 } else if (option == "--dump-timing") {
677 dump_timing_ = true;
678 } else if (option == "--dump-passes") {
679 dump_passes_ = true;
David Brazdil866c0312015-01-13 21:21:31 +0000680 } else if (option.starts_with("--dump-cfg=")) {
681 dump_cfg_file_name_ = option.substr(strlen("--dump-cfg=")).data();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800682 } else if (option == "--dump-stats") {
683 dump_stats_ = true;
684 } else if (option == "--include-debug-symbols" || option == "--no-strip-symbols") {
685 include_debug_symbols = true;
686 } else if (option == "--no-include-debug-symbols" || option == "--strip-symbols") {
687 include_debug_symbols = false;
David Srbecky8dc73242015-04-12 11:40:39 +0100688 } else if (option == "--include-cfi") {
689 include_cfi = true;
690 } else if (option == "--no-include-cfi") {
691 include_cfi = false;
Andreas Gampe7b2f09e2015-03-02 14:07:33 -0800692 } else if (option == "--debuggable") {
693 debuggable = true;
Andreas Gampef307f8c2015-05-04 08:33:31 -0700694 include_debug_symbols = true;
695 include_cfi = true;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800696 } else if (option.starts_with("--profile-file=")) {
697 profile_file_ = option.substr(strlen("--profile-file=")).data();
698 VLOG(compiler) << "dex2oat: profile file is " << profile_file_;
699 } else if (option == "--no-profile-file") {
700 // No profile
701 } else if (option.starts_with("--top-k-profile-threshold=")) {
702 ParseDouble(option.data(), '=', 0.0, 100.0, &top_k_profile_threshold);
703 } else if (option == "--print-pass-names") {
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800704 pass_manager_options.SetPrintPassNames(true);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800705 } else if (option.starts_with("--disable-passes=")) {
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800706 const std::string disable_passes = option.substr(strlen("--disable-passes=")).data();
707 pass_manager_options.SetDisablePassList(disable_passes);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800708 } else if (option.starts_with("--print-passes=")) {
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800709 const std::string print_passes = option.substr(strlen("--print-passes=")).data();
710 pass_manager_options.SetPrintPassList(print_passes);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800711 } else if (option == "--print-all-passes") {
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800712 pass_manager_options.SetPrintAllPasses();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800713 } else if (option.starts_with("--dump-cfg-passes=")) {
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800714 const std::string dump_passes_string = option.substr(strlen("--dump-cfg-passes=")).data();
715 pass_manager_options.SetDumpPassList(dump_passes_string);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800716 } else if (option == "--print-pass-options") {
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800717 pass_manager_options.SetPrintPassOptions(true);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800718 } else if (option.starts_with("--pass-options=")) {
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800719 const std::string options = option.substr(strlen("--pass-options=")).data();
720 pass_manager_options.SetOverriddenPassOptions(options);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800721 } else if (option == "--include-patch-information") {
722 include_patch_information = true;
723 } else if (option == "--no-include-patch-information") {
724 include_patch_information = false;
725 } else if (option.starts_with("--verbose-methods=")) {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800726 // TODO: rather than switch off compiler logging, make all VLOG(compiler) messages
727 // conditional on having verbost methods.
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800728 gLogVerbosity.compiler = false;
729 Split(option.substr(strlen("--verbose-methods=")).ToString(), ',', &verbose_methods_);
Andreas Gampedbfe2542014-11-25 22:21:42 -0800730 } else if (option.starts_with("--dump-init-failures=")) {
731 std::string file_name = option.substr(strlen("--dump-init-failures=")).data();
732 init_failure_output_.reset(new std::ofstream(file_name));
733 if (init_failure_output_.get() == nullptr) {
734 LOG(ERROR) << "Failed to allocate ofstream";
735 } else if (init_failure_output_->fail()) {
736 LOG(ERROR) << "Failed to open " << file_name << " for writing the initialization "
737 << "failures.";
738 init_failure_output_.reset();
739 }
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800740 } else if (option.starts_with("--swap-file=")) {
741 swap_file_name_ = option.substr(strlen("--swap-file=")).data();
742 } else if (option.starts_with("--swap-fd=")) {
743 const char* swap_fd_str = option.substr(strlen("--swap-fd=")).data();
744 if (!ParseInt(swap_fd_str, &swap_fd_)) {
745 Usage("Failed to parse --swap-fd argument '%s' as an integer", swap_fd_str);
746 }
747 if (swap_fd_ < 0) {
748 Usage("--swap-fd passed a negative value %d", swap_fd_);
749 }
Andreas Gampe6cf49e52015-03-05 13:08:45 -0800750 } else if (option == "--abort-on-hard-verifier-error") {
751 abort_on_hard_verifier_error = true;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800752 } else {
753 Usage("Unknown argument %s", option.data());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700754 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800755 }
756
Nicolas Geoffray1412dfa2015-03-20 14:48:13 +0000757 image_ = (!image_filename_.empty());
758 if (!requested_specific_compiler && !kUseOptimizingCompiler) {
759 // If no specific compiler is requested, the current behavior is
760 // to compile the boot image with Quick, and the rest with Optimizing.
761 compiler_kind_ = image_ ? Compiler::kQuick : Compiler::kOptimizing;
762 }
763
Nicolas Geoffray9bb492a2014-11-25 23:42:00 +0000764 if (compiler_kind_ == Compiler::kOptimizing) {
765 // Optimizing only supports PIC mode.
766 compile_pic = true;
767 }
768
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800769 if (oat_filename_.empty() && oat_fd_ == -1) {
770 Usage("Output must be supplied with either --oat-file or --oat-fd");
771 }
772
773 if (!oat_filename_.empty() && oat_fd_ != -1) {
774 Usage("--oat-file should not be used with --oat-fd");
775 }
776
777 if (!oat_symbols.empty() && oat_fd_ != -1) {
778 Usage("--oat-symbols should not be used with --oat-fd");
779 }
780
781 if (!oat_symbols.empty() && is_host_) {
782 Usage("--oat-symbols should not be used with --host");
783 }
784
785 if (oat_fd_ != -1 && !image_filename_.empty()) {
786 Usage("--oat-fd should not be used with --image");
787 }
788
789 if (android_root_.empty()) {
790 const char* android_root_env_var = getenv("ANDROID_ROOT");
791 if (android_root_env_var == nullptr) {
792 Usage("--android-root unspecified and ANDROID_ROOT not set");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700793 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800794 android_root_ += android_root_env_var;
795 }
796
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800797 if (!image_ && boot_image_filename.empty()) {
798 boot_image_filename += android_root_;
799 boot_image_filename += "/framework/boot.art";
800 }
801 if (!boot_image_filename.empty()) {
802 boot_image_option_ += "-Ximage:";
803 boot_image_option_ += boot_image_filename;
804 }
805
806 if (image_classes_filename_ != nullptr && !image_) {
807 Usage("--image-classes should only be used with --image");
808 }
809
810 if (image_classes_filename_ != nullptr && !boot_image_option_.empty()) {
811 Usage("--image-classes should not be used with --boot-image");
812 }
813
814 if (image_classes_zip_filename_ != nullptr && image_classes_filename_ == nullptr) {
815 Usage("--image-classes-zip should be used with --image-classes");
816 }
817
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800818 if (compiled_classes_filename_ != nullptr && !image_) {
819 Usage("--compiled-classes should only be used with --image");
820 }
821
822 if (compiled_classes_filename_ != nullptr && !boot_image_option_.empty()) {
823 Usage("--compiled-classes should not be used with --boot-image");
824 }
825
826 if (compiled_classes_zip_filename_ != nullptr && compiled_classes_filename_ == nullptr) {
827 Usage("--compiled-classes-zip should be used with --compiled-classes");
828 }
829
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800830 if (dex_filenames_.empty() && zip_fd_ == -1) {
831 Usage("Input must be supplied with either --dex-file or --zip-fd");
832 }
833
834 if (!dex_filenames_.empty() && zip_fd_ != -1) {
835 Usage("--dex-file should not be used with --zip-fd");
836 }
837
838 if (!dex_filenames_.empty() && !zip_location_.empty()) {
839 Usage("--dex-file should not be used with --zip-location");
840 }
841
842 if (dex_locations_.empty()) {
843 for (const char* dex_file_name : dex_filenames_) {
844 dex_locations_.push_back(dex_file_name);
845 }
846 } else if (dex_locations_.size() != dex_filenames_.size()) {
847 Usage("--dex-location arguments do not match --dex-file arguments");
848 }
849
850 if (zip_fd_ != -1 && zip_location_.empty()) {
851 Usage("--zip-location should be supplied with --zip-fd");
852 }
853
854 if (boot_image_option_.empty()) {
855 if (image_base_ == 0) {
856 Usage("Non-zero --base not specified");
857 }
858 }
859
860 oat_stripped_ = oat_filename_;
861 if (!oat_symbols.empty()) {
862 oat_unstripped_ = oat_symbols;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700863 } else {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800864 oat_unstripped_ = oat_filename_;
865 }
866
867 // If no instruction set feature was given, use the default one for the target
868 // instruction set.
869 if (instruction_set_features_.get() == nullptr) {
870 instruction_set_features_.reset(
Ian Rogersd582fa42014-11-05 23:46:43 -0800871 InstructionSetFeatures::FromVariant(instruction_set_, "default", &error_msg));
872 if (instruction_set_features_.get() == nullptr) {
873 Usage("Problem initializing default instruction set features variant: %s",
874 error_msg.c_str());
875 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800876 }
877
878 if (instruction_set_ == kRuntimeISA) {
879 std::unique_ptr<const InstructionSetFeatures> runtime_features(
880 InstructionSetFeatures::FromCppDefines());
881 if (!instruction_set_features_->Equals(runtime_features.get())) {
882 LOG(WARNING) << "Mismatch between dex2oat instruction set features ("
883 << *instruction_set_features_ << ") and those of dex2oat executable ("
884 << *runtime_features <<") for the command line:\n"
885 << CommandLine();
886 }
887 }
888
889 if (compiler_filter_string == nullptr) {
Douglas Leung027f0ff2015-02-27 19:05:03 -0800890 compiler_filter_string = "speed";
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800891 }
Maja Gagic6ea651f2015-02-24 16:55:04 +0100892
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800893 CHECK(compiler_filter_string != nullptr);
894 CompilerOptions::CompilerFilter compiler_filter = CompilerOptions::kDefaultCompilerFilter;
895 if (strcmp(compiler_filter_string, "verify-none") == 0) {
896 compiler_filter = CompilerOptions::kVerifyNone;
897 } else if (strcmp(compiler_filter_string, "interpret-only") == 0) {
898 compiler_filter = CompilerOptions::kInterpretOnly;
Mathieu Chartiere86deef2015-03-19 13:43:37 -0700899 } else if (strcmp(compiler_filter_string, "verify-at-runtime") == 0) {
900 compiler_filter = CompilerOptions::kVerifyAtRuntime;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800901 } else if (strcmp(compiler_filter_string, "space") == 0) {
902 compiler_filter = CompilerOptions::kSpace;
903 } else if (strcmp(compiler_filter_string, "balanced") == 0) {
904 compiler_filter = CompilerOptions::kBalanced;
905 } else if (strcmp(compiler_filter_string, "speed") == 0) {
906 compiler_filter = CompilerOptions::kSpeed;
907 } else if (strcmp(compiler_filter_string, "everything") == 0) {
908 compiler_filter = CompilerOptions::kEverything;
909 } else if (strcmp(compiler_filter_string, "time") == 0) {
910 compiler_filter = CompilerOptions::kTime;
911 } else {
912 Usage("Unknown --compiler-filter value %s", compiler_filter_string);
913 }
914
915 // Checks are all explicit until we know the architecture.
916 bool implicit_null_checks = false;
917 bool implicit_so_checks = false;
918 bool implicit_suspend_checks = false;
919 // Set the compilation target's implicit checks options.
920 switch (instruction_set_) {
921 case kArm:
922 case kThumb2:
923 case kArm64:
924 case kX86:
925 case kX86_64:
926 implicit_null_checks = true;
927 implicit_so_checks = true;
928 break;
929
930 default:
931 // Defaults are correct.
932 break;
933 }
934
Andreas Gampe7b2f09e2015-03-02 14:07:33 -0800935 if (debuggable) {
936 // TODO: Consider adding CFI info and symbols here.
937 }
938
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800939 compiler_options_.reset(new CompilerOptions(compiler_filter,
940 huge_method_threshold,
941 large_method_threshold,
942 small_method_threshold,
943 tiny_method_threshold,
944 num_dex_methods_threshold,
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800945 include_patch_information,
946 top_k_profile_threshold,
Andreas Gampe7b2f09e2015-03-02 14:07:33 -0800947 debuggable,
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800948 include_debug_symbols,
David Srbecky8dc73242015-04-12 11:40:39 +0100949 include_cfi,
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800950 implicit_null_checks,
951 implicit_so_checks,
952 implicit_suspend_checks,
953 compile_pic,
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800954 verbose_methods_.empty() ?
955 nullptr :
Andreas Gampedbfe2542014-11-25 22:21:42 -0800956 &verbose_methods_,
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800957 new PassManagerOptions(pass_manager_options),
Andreas Gampe6cf49e52015-03-05 13:08:45 -0800958 init_failure_output_.get(),
959 abort_on_hard_verifier_error));
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800960
961 // Done with usage checks, enable watchdog if requested
962 if (watch_dog_enabled) {
963 watchdog_.reset(new WatchDog(true));
964 }
965
966 // Fill some values into the key-value store for the oat header.
967 key_value_store_.reset(new SafeMap<std::string, std::string>());
968
969 // Insert some compiler things.
970 {
971 std::ostringstream oss;
972 for (int i = 0; i < argc; ++i) {
973 if (i > 0) {
974 oss << ' ';
975 }
976 oss << argv[i];
977 }
978 key_value_store_->Put(OatHeader::kDex2OatCmdLineKey, oss.str());
979 oss.str(""); // Reset.
980 oss << kRuntimeISA;
981 key_value_store_->Put(OatHeader::kDex2OatHostKey, oss.str());
Sebastien Hertz0de11332015-05-13 12:14:05 +0200982 key_value_store_->Put(OatHeader::kPicKey,
983 compile_pic ? OatHeader::kTrueValue : OatHeader::kFalseValue);
984 key_value_store_->Put(OatHeader::kDebuggableKey,
985 debuggable ? OatHeader::kTrueValue : OatHeader::kFalseValue);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800986 }
987 }
988
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800989 // Check whether the oat output file is writable, and open it for later. Also open a swap file,
990 // if a name is given.
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800991 bool OpenFile() {
992 bool create_file = !oat_unstripped_.empty(); // as opposed to using open file descriptor
993 if (create_file) {
994 oat_file_.reset(OS::CreateEmptyFile(oat_unstripped_.c_str()));
995 if (oat_location_.empty()) {
996 oat_location_ = oat_filename_;
997 }
998 } else {
Andreas Gampe4303ba92014-11-06 01:00:46 -0800999 oat_file_.reset(new File(oat_fd_, oat_location_, true));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001000 oat_file_->DisableAutoClose();
Andreas Gampe4303ba92014-11-06 01:00:46 -08001001 if (oat_file_->SetLength(0) != 0) {
1002 PLOG(WARNING) << "Truncating oat file " << oat_location_ << " failed.";
1003 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001004 }
1005 if (oat_file_.get() == nullptr) {
1006 PLOG(ERROR) << "Failed to create oat file: " << oat_location_;
1007 return false;
1008 }
1009 if (create_file && fchmod(oat_file_->Fd(), 0644) != 0) {
1010 PLOG(ERROR) << "Failed to make oat file world readable: " << oat_location_;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001011 oat_file_->Erase();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001012 return false;
1013 }
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001014
1015 // Swap file handling.
1016 //
1017 // If the swap fd is not -1, we assume this is the file descriptor of an open but unlinked file
1018 // that we can use for swap.
1019 //
1020 // If the swap fd is -1 and we have a swap-file string, open the given file as a swap file. We
1021 // will immediately unlink to satisfy the swap fd assumption.
1022 if (swap_fd_ == -1 && !swap_file_name_.empty()) {
1023 std::unique_ptr<File> swap_file(OS::CreateEmptyFile(swap_file_name_.c_str()));
1024 if (swap_file.get() == nullptr) {
1025 PLOG(ERROR) << "Failed to create swap file: " << swap_file_name_;
1026 return false;
1027 }
1028 swap_fd_ = swap_file->Fd();
1029 swap_file->MarkUnchecked(); // We don't we to track this, it will be unlinked immediately.
1030 swap_file->DisableAutoClose(); // We'll handle it ourselves, the File object will be
1031 // released immediately.
1032 unlink(swap_file_name_.c_str());
1033 }
1034
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001035 return true;
1036 }
1037
Andreas Gampea650e702014-12-03 14:28:02 -08001038 void EraseOatFile() {
1039 DCHECK(oat_file_.get() != nullptr);
1040 oat_file_->Erase();
1041 oat_file_.reset();
1042 }
1043
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001044 // Set up the environment for compilation. Includes starting the runtime and loading/opening the
1045 // boot class path.
1046 bool Setup() {
1047 TimingLogger::ScopedTiming t("dex2oat Setup", timings_);
1048 RuntimeOptions runtime_options;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001049 art::MemMap::Init(); // For ZipEntry::ExtractToMemMap.
1050 if (boot_image_option_.empty()) {
Richard Uhlerc2752592015-01-02 13:28:22 -08001051 std::string boot_class_path = "-Xbootclasspath:";
1052 boot_class_path += Join(dex_filenames_, ':');
1053 runtime_options.push_back(std::make_pair(boot_class_path, nullptr));
1054 std::string boot_class_path_locations = "-Xbootclasspath-locations:";
1055 boot_class_path_locations += Join(dex_locations_, ':');
1056 runtime_options.push_back(std::make_pair(boot_class_path_locations, nullptr));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001057 } else {
Richard Uhlerc2752592015-01-02 13:28:22 -08001058 runtime_options.push_back(std::make_pair(boot_image_option_, nullptr));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001059 }
1060 for (size_t i = 0; i < runtime_args_.size(); i++) {
1061 runtime_options.push_back(std::make_pair(runtime_args_[i], nullptr));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001062 }
Brian Carlstromd76e0832013-08-29 15:17:42 -07001063
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001064 verification_results_.reset(new VerificationResults(compiler_options_.get()));
Andreas Gampe4585f872015-03-27 23:45:15 -07001065 callbacks_.reset(new QuickCompilerCallbacks(
1066 verification_results_.get(),
1067 &method_inliner_map_,
1068 image_ ?
1069 CompilerCallbacks::CallbackMode::kCompileBootImage :
1070 CompilerCallbacks::CallbackMode::kCompileApp));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001071 runtime_options.push_back(std::make_pair("compilercallbacks", callbacks_.get()));
1072 runtime_options.push_back(
1073 std::make_pair("imageinstructionset", GetInstructionSetString(instruction_set_)));
1074
Andreas Gampe1d00add2015-02-27 19:35:46 -08001075 // Only allow no boot image for the runtime if we're compiling one. When we compile an app,
1076 // we don't want fallback mode, it will abort as we do not push a boot classpath (it might
1077 // have been stripped in preopting, anyways).
1078 if (!image_) {
1079 runtime_options.push_back(std::make_pair("-Xno-dex-file-fallback", nullptr));
1080 }
1081
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001082 if (!CreateRuntime(runtime_options)) {
1083 return false;
1084 }
1085
1086 // Runtime::Create acquired the mutator_lock_ that is normally given away when we
1087 // Runtime::Start, give it away now so that we don't starve GC.
1088 Thread* self = Thread::Current();
1089 self->TransitionFromRunnableToSuspended(kNative);
1090 // If we're doing the image, override the compiler filter to force full compilation. Must be
1091 // done ahead of WellKnownClasses::Init that causes verification. Note: doesn't force
1092 // compilation of class initializers.
1093 // Whilst we're in native take the opportunity to initialize well known classes.
1094 WellKnownClasses::Init(self->GetJniEnv());
1095
1096 // If --image-classes was specified, calculate the full list of classes to include in the image
1097 if (image_classes_filename_ != nullptr) {
1098 std::string error_msg;
1099 if (image_classes_zip_filename_ != nullptr) {
1100 image_classes_.reset(ReadImageClassesFromZip(image_classes_zip_filename_,
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001101 image_classes_filename_,
1102 &error_msg));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001103 } else {
1104 image_classes_.reset(ReadImageClassesFromFile(image_classes_filename_));
1105 }
1106 if (image_classes_.get() == nullptr) {
1107 LOG(ERROR) << "Failed to create list of image classes from '" << image_classes_filename_ <<
1108 "': " << error_msg;
1109 return false;
1110 }
1111 } else if (image_) {
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001112 image_classes_.reset(new std::unordered_set<std::string>);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001113 }
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001114 // If --compiled-classes was specified, calculate the full list of classes to compile in the
1115 // image.
1116 if (compiled_classes_filename_ != nullptr) {
1117 std::string error_msg;
1118 if (compiled_classes_zip_filename_ != nullptr) {
1119 compiled_classes_.reset(ReadImageClassesFromZip(compiled_classes_zip_filename_,
1120 compiled_classes_filename_,
1121 &error_msg));
1122 } else {
1123 compiled_classes_.reset(ReadImageClassesFromFile(compiled_classes_filename_));
1124 }
1125 if (compiled_classes_.get() == nullptr) {
1126 LOG(ERROR) << "Failed to create list of compiled classes from '"
1127 << compiled_classes_filename_ << "': " << error_msg;
1128 return false;
1129 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001130 } else {
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001131 compiled_classes_.reset(nullptr); // By default compile everything.
1132 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001133 // If --compiled-methods was specified, read the methods to compile from the given file(s).
1134 if (compiled_methods_filename_ != nullptr) {
1135 std::string error_msg;
1136 if (compiled_methods_zip_filename_ != nullptr) {
1137 compiled_methods_.reset(ReadCommentedInputFromZip(compiled_methods_zip_filename_,
1138 compiled_methods_filename_,
1139 nullptr, // No post-processing.
1140 &error_msg));
1141 } else {
1142 compiled_methods_.reset(ReadCommentedInputFromFile(compiled_methods_filename_,
1143 nullptr)); // No post-processing.
1144 }
1145 if (compiled_methods_.get() == nullptr) {
1146 LOG(ERROR) << "Failed to create list of compiled methods from '"
1147 << compiled_methods_filename_ << "': " << error_msg;
1148 return false;
1149 }
1150 } else {
1151 compiled_methods_.reset(nullptr); // By default compile everything.
1152 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001153
1154 if (boot_image_option_.empty()) {
1155 dex_files_ = Runtime::Current()->GetClassLinker()->GetBootClassPath();
1156 } else {
1157 if (dex_filenames_.empty()) {
1158 ATRACE_BEGIN("Opening zip archive from file descriptor");
1159 std::string error_msg;
1160 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(zip_fd_,
1161 zip_location_.c_str(),
1162 &error_msg));
1163 if (zip_archive.get() == nullptr) {
1164 LOG(ERROR) << "Failed to open zip from file descriptor for '" << zip_location_ << "': "
1165 << error_msg;
1166 return false;
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001167 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001168 if (!DexFile::OpenFromZip(*zip_archive.get(), zip_location_, &error_msg, &opened_dex_files_)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001169 LOG(ERROR) << "Failed to open dex from file descriptor for zip file '" << zip_location_
1170 << "': " << error_msg;
1171 return false;
1172 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001173 for (auto& dex_file : opened_dex_files_) {
1174 dex_files_.push_back(dex_file.get());
1175 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001176 ATRACE_END();
1177 } else {
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001178 size_t failure_count = OpenDexFiles(dex_filenames_, dex_locations_, &opened_dex_files_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001179 if (failure_count > 0) {
1180 LOG(ERROR) << "Failed to open some dex files: " << failure_count;
1181 return false;
1182 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001183 for (auto& dex_file : opened_dex_files_) {
1184 dex_files_.push_back(dex_file.get());
1185 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001186 }
1187
1188 constexpr bool kSaveDexInput = false;
1189 if (kSaveDexInput) {
1190 for (size_t i = 0; i < dex_files_.size(); ++i) {
1191 const DexFile* dex_file = dex_files_[i];
Brian Carlstrom95b033b2014-12-03 22:29:37 -08001192 std::string tmp_file_name(StringPrintf("/data/local/tmp/dex2oat.%d.%zd.dex",
1193 getpid(), i));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001194 std::unique_ptr<File> tmp_file(OS::CreateEmptyFile(tmp_file_name.c_str()));
1195 if (tmp_file.get() == nullptr) {
1196 PLOG(ERROR) << "Failed to open file " << tmp_file_name
1197 << ". Try: adb shell chmod 777 /data/local/tmp";
1198 continue;
1199 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001200 // This is just dumping files for debugging. Ignore errors, and leave remnants.
1201 UNUSED(tmp_file->WriteFully(dex_file->Begin(), dex_file->Size()));
1202 UNUSED(tmp_file->Flush());
1203 UNUSED(tmp_file->Close());
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001204 LOG(INFO) << "Wrote input to " << tmp_file_name;
1205 }
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001206 }
1207 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001208 // Ensure opened dex files are writable for dex-to-dex transformations.
1209 for (const auto& dex_file : dex_files_) {
1210 if (!dex_file->EnableWrite()) {
1211 PLOG(ERROR) << "Failed to make .dex file writeable '" << dex_file->GetLocation() << "'\n";
Andreas Gampe7ba64962014-10-23 11:37:40 -07001212 }
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001213 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001214
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001215 // If we use a swap file, ensure we are above the threshold to make it necessary.
1216 if (swap_fd_ != -1) {
1217 if (!UseSwap(image_, dex_files_)) {
1218 close(swap_fd_);
1219 swap_fd_ = -1;
Andreas Gampef99bcd22015-04-24 16:22:18 -07001220 VLOG(compiler) << "Decided to run without swap.";
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001221 } else {
Andreas Gampef99bcd22015-04-24 16:22:18 -07001222 LOG(INFO) << "Large app, accepted running with swap.";
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001223 }
1224 }
1225 // Note that dex2oat won't close the swap_fd_. The compiler driver's swap space will do that.
1226
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001227 /*
1228 * If we're not in interpret-only or verify-none mode, go ahead and compile small applications.
1229 * Don't bother to check if we're doing the image.
1230 */
Brian Carlstrom95b033b2014-12-03 22:29:37 -08001231 if (!image_ &&
1232 compiler_options_->IsCompilationEnabled() &&
1233 compiler_kind_ == Compiler::kQuick) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001234 size_t num_methods = 0;
1235 for (size_t i = 0; i != dex_files_.size(); ++i) {
1236 const DexFile* dex_file = dex_files_[i];
1237 CHECK(dex_file != nullptr);
1238 num_methods += dex_file->NumMethodIds();
1239 }
1240 if (num_methods <= compiler_options_->GetNumDexMethodsThreshold()) {
1241 compiler_options_->SetCompilerFilter(CompilerOptions::kSpeed);
1242 VLOG(compiler) << "Below method threshold, compiling anyways";
1243 }
1244 }
1245
1246 return true;
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001247 }
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001248
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001249 // Create and invoke the compiler driver. This will compile all the dex files.
1250 void Compile() {
1251 TimingLogger::ScopedTiming t("dex2oat Compile", timings_);
1252 compiler_phases_timings_.reset(new CumulativeLogger("compilation times"));
Vladimir Markof4da6752014-08-01 19:04:18 +01001253
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001254 // Handle and ClassLoader creation needs to come after Runtime::Create
1255 jobject class_loader = nullptr;
1256 Thread* self = Thread::Current();
1257 if (!boot_image_option_.empty()) {
1258 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001259 OpenClassPathFiles(runtime_->GetClassPathString(), dex_files_, &class_path_files_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001260 ScopedObjectAccess soa(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07001261
1262 // Classpath: first the class-path given.
1263 std::vector<const DexFile*> class_path_files;
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001264 for (auto& class_path_file : class_path_files_) {
1265 class_path_files.push_back(class_path_file.get());
1266 }
Andreas Gampe7848da42015-04-09 11:15:04 -07001267
1268 // Store the classpath we have right now.
1269 key_value_store_->Put(OatHeader::kClassPathKey,
1270 OatFile::EncodeDexFileDependencies(class_path_files));
1271
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07001272 // Then the dex files we'll compile. Thus we'll resolve the class-path first.
1273 class_path_files.insert(class_path_files.end(), dex_files_.begin(), dex_files_.end());
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001274
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07001275 class_loader = class_linker->CreatePathClassLoader(self, class_path_files);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001276 }
1277
1278 driver_.reset(new CompilerDriver(compiler_options_.get(),
1279 verification_results_.get(),
1280 &method_inliner_map_,
1281 compiler_kind_,
1282 instruction_set_,
1283 instruction_set_features_.get(),
1284 image_,
1285 image_classes_.release(),
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001286 compiled_classes_.release(),
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001287 nullptr,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001288 thread_count_,
1289 dump_stats_,
1290 dump_passes_,
David Brazdil866c0312015-01-13 21:21:31 +00001291 dump_cfg_file_name_,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001292 compiler_phases_timings_.get(),
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001293 swap_fd_,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001294 profile_file_));
1295
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001296 driver_->CompileAll(class_loader, dex_files_, timings_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001297 }
1298
Brian Carlstrom7940e442013-07-12 13:46:57 -07001299 // Notes on the interleaving of creating the image and oat file to
1300 // ensure the references between the two are correct.
1301 //
1302 // Currently we have a memory layout that looks something like this:
1303 //
1304 // +--------------+
1305 // | image |
1306 // +--------------+
1307 // | boot oat |
1308 // +--------------+
1309 // | alloc spaces |
1310 // +--------------+
1311 //
Brian Carlstrom45602482013-07-21 22:07:55 -07001312 // There are several constraints on the loading of the image and boot.oat.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001313 //
1314 // 1. The image is expected to be loaded at an absolute address and
1315 // contains Objects with absolute pointers within the image.
1316 //
1317 // 2. There are absolute pointers from Methods in the image to their
1318 // code in the oat.
1319 //
1320 // 3. There are absolute pointers from the code in the oat to Methods
1321 // in the image.
1322 //
1323 // 4. There are absolute pointers from code in the oat to other code
1324 // in the oat.
1325 //
1326 // To get this all correct, we go through several steps.
1327 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001328 // 1. We prepare offsets for all data in the oat file and calculate
1329 // the oat data size and code size. During this stage, we also set
1330 // oat code offsets in methods for use by the image writer.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001331 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001332 // 2. We prepare offsets for the objects in the image and calculate
1333 // the image size.
1334 //
1335 // 3. We create the oat file. Originally this was just our own proprietary
1336 // file but now it is contained within an ELF dynamic object (aka an .so
1337 // file). Since we know the image size and oat data size and code size we
1338 // can prepare the ELF headers and we then know the ELF memory segment
1339 // layout and we can now resolve all references. The compiler provides
1340 // LinkerPatch information in each CompiledMethod and we resolve these,
1341 // using the layout information and image object locations provided by
1342 // image writer, as we're writing the method code.
1343 //
1344 // 4. We create the image file. It needs to know where the oat file
Brian Carlstrom7940e442013-07-12 13:46:57 -07001345 // will be loaded after itself. Originally when oat file was simply
1346 // memory mapped so we could predict where its contents were based
1347 // on the file size. Now that it is an ELF file, we need to inspect
1348 // the ELF file to understand the in memory segment layout including
Vladimir Markof4da6752014-08-01 19:04:18 +01001349 // where the oat header is located within.
1350 // TODO: We could just remember this information from step 3.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001351 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001352 // 5. We fixup the ELF program headers so that dlopen will try to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001353 // load the .so at the desired location at runtime by offsetting the
1354 // Elf32_Phdr.p_vaddr values by the desired base address.
Vladimir Markof4da6752014-08-01 19:04:18 +01001355 // TODO: Do this in step 3. We already know the layout there.
1356 //
1357 // Steps 1.-3. are done by the CreateOatFile() above, steps 4.-5.
1358 // are done by the CreateImageFile() below.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001359
1360
1361 // Write out the generated code part. Calls the OatWriter and ElfBuilder. Also prepares the
1362 // ImageWriter, if necessary.
Andreas Gampe10e477d2014-11-19 12:57:42 -08001363 // Note: Flushing (and closing) the file is the caller's responsibility, except for the failure
1364 // case (when the file will be explicitly erased).
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001365 bool CreateOatFile() {
1366 CHECK(key_value_store_.get() != nullptr);
1367
1368 TimingLogger::ScopedTiming t("dex2oat Oat", timings_);
1369
1370 std::unique_ptr<OatWriter> oat_writer;
1371 {
1372 TimingLogger::ScopedTiming t2("dex2oat OatWriter", timings_);
1373 std::string image_file_location;
1374 uint32_t image_file_location_oat_checksum = 0;
1375 uintptr_t image_file_location_oat_data_begin = 0;
1376 int32_t image_patch_delta = 0;
1377 if (image_) {
1378 PrepareImageWriter(image_base_);
1379 } else {
1380 TimingLogger::ScopedTiming t3("Loading image checksum", timings_);
1381 gc::space::ImageSpace* image_space = Runtime::Current()->GetHeap()->GetImageSpace();
1382 image_file_location_oat_checksum = image_space->GetImageHeader().GetOatChecksum();
1383 image_file_location_oat_data_begin =
1384 reinterpret_cast<uintptr_t>(image_space->GetImageHeader().GetOatDataBegin());
1385 image_file_location = image_space->GetImageFilename();
1386 image_patch_delta = image_space->GetImageHeader().GetPatchDelta();
1387 }
1388
1389 if (!image_file_location.empty()) {
1390 key_value_store_->Put(OatHeader::kImageLocationKey, image_file_location);
1391 }
1392
1393 oat_writer.reset(new OatWriter(dex_files_, image_file_location_oat_checksum,
1394 image_file_location_oat_data_begin,
1395 image_patch_delta,
1396 driver_.get(),
1397 image_writer_.get(),
1398 timings_,
1399 key_value_store_.get()));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001400 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001401
1402 if (image_) {
1403 // The OatWriter constructor has already updated offsets in methods and we need to
1404 // prepare method offsets in the image address space for direct method patching.
1405 TimingLogger::ScopedTiming t2("dex2oat Prepare image address space", timings_);
1406 if (!image_writer_->PrepareImageAddressSpace()) {
1407 LOG(ERROR) << "Failed to prepare image address space.";
1408 return false;
1409 }
1410 }
1411
1412 {
1413 TimingLogger::ScopedTiming t2("dex2oat Write ELF", timings_);
1414 if (!driver_->WriteElf(android_root_, is_host_, dex_files_, oat_writer.get(),
1415 oat_file_.get())) {
1416 LOG(ERROR) << "Failed to write ELF file " << oat_file_->GetPath();
1417 return false;
1418 }
1419 }
1420
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001421 VLOG(compiler) << "Oat file written successfully (unstripped): " << oat_location_;
1422 return true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001423 }
1424
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001425 // If we are compiling an image, invoke the image creation routine. Else just skip.
1426 bool HandleImage() {
1427 if (image_) {
1428 TimingLogger::ScopedTiming t("dex2oat ImageWriter", timings_);
1429 if (!CreateImageFile()) {
1430 return false;
1431 }
1432 VLOG(compiler) << "Image written successfully: " << image_filename_;
Brian Carlstrom45602482013-07-21 22:07:55 -07001433 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001434 return true;
1435 }
1436
Andreas Gampe10e477d2014-11-19 12:57:42 -08001437 // Create a copy from unstripped to stripped.
1438 bool CopyUnstrippedToStripped() {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001439 // If we don't want to strip in place, copy from unstripped location to stripped location.
1440 // We need to strip after image creation because FixupElf needs to use .strtab.
1441 if (oat_unstripped_ != oat_stripped_) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08001442 // If the oat file is still open, flush it.
1443 if (oat_file_.get() != nullptr && oat_file_->IsOpened()) {
1444 if (!FlushCloseOatFile()) {
1445 return false;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001446 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001447 }
Andreas Gampe10e477d2014-11-19 12:57:42 -08001448
1449 TimingLogger::ScopedTiming t("dex2oat OatFile copy", timings_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001450 std::unique_ptr<File> in(OS::OpenFileForReading(oat_unstripped_.c_str()));
1451 std::unique_ptr<File> out(OS::CreateEmptyFile(oat_stripped_.c_str()));
1452 size_t buffer_size = 8192;
Dan Albert6fc59ab2014-12-11 14:09:51 -08001453 std::unique_ptr<uint8_t[]> buffer(new uint8_t[buffer_size]);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001454 while (true) {
1455 int bytes_read = TEMP_FAILURE_RETRY(read(in->Fd(), buffer.get(), buffer_size));
1456 if (bytes_read <= 0) {
1457 break;
1458 }
1459 bool write_ok = out->WriteFully(buffer.get(), bytes_read);
1460 CHECK(write_ok);
1461 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08001462 if (out->FlushCloseOrErase() != 0) {
1463 PLOG(ERROR) << "Failed to flush and close copied oat file: " << oat_stripped_;
1464 return false;
Andreas Gampe10e477d2014-11-19 12:57:42 -08001465 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001466 VLOG(compiler) << "Oat file copied successfully (stripped): " << oat_stripped_;
Nicolas Geoffrayea3fa0b2014-02-10 11:59:41 +00001467 }
Andreas Gampe10e477d2014-11-19 12:57:42 -08001468 return true;
1469 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001470
Andreas Gampe10e477d2014-11-19 12:57:42 -08001471 bool FlushOatFile() {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001472 if (oat_file_.get() != nullptr) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08001473 TimingLogger::ScopedTiming t2("dex2oat Flush ELF", timings_);
1474 if (oat_file_->Flush() != 0) {
1475 PLOG(ERROR) << "Failed to flush oat file: " << oat_location_ << " / "
1476 << oat_filename_;
1477 oat_file_->Erase();
1478 return false;
1479 }
1480 }
1481 return true;
1482 }
1483
1484 bool FlushCloseOatFile() {
1485 if (oat_file_.get() != nullptr) {
1486 std::unique_ptr<File> tmp(oat_file_.release());
1487 if (tmp->FlushCloseOrErase() != 0) {
1488 PLOG(ERROR) << "Failed to flush and close oat file: " << oat_location_ << " / "
1489 << oat_filename_;
1490 return false;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001491 }
1492 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001493 return true;
1494 }
1495
1496 void DumpTiming() {
1497 if (dump_timing_ || (dump_slow_timing_ && timings_->GetTotalNs() > MsToNs(1000))) {
1498 LOG(INFO) << Dumpable<TimingLogger>(*timings_);
1499 }
1500 if (dump_passes_) {
1501 LOG(INFO) << Dumpable<CumulativeLogger>(*driver_->GetTimingsLogger());
1502 }
1503 }
1504
1505 CompilerOptions* GetCompilerOptions() const {
1506 return compiler_options_.get();
1507 }
1508
Andreas Gampe10e477d2014-11-19 12:57:42 -08001509 bool IsImage() const {
1510 return image_;
1511 }
1512
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001513 bool IsHost() const {
1514 return is_host_;
1515 }
1516
1517 private:
1518 static size_t OpenDexFiles(const std::vector<const char*>& dex_filenames,
1519 const std::vector<const char*>& dex_locations,
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001520 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001521 DCHECK(dex_files != nullptr) << "OpenDexFiles out-param is nullptr";
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001522 size_t failure_count = 0;
1523 for (size_t i = 0; i < dex_filenames.size(); i++) {
1524 const char* dex_filename = dex_filenames[i];
1525 const char* dex_location = dex_locations[i];
1526 ATRACE_BEGIN(StringPrintf("Opening dex file '%s'", dex_filenames[i]).c_str());
1527 std::string error_msg;
1528 if (!OS::FileExists(dex_filename)) {
1529 LOG(WARNING) << "Skipping non-existent dex file '" << dex_filename << "'";
1530 continue;
1531 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001532 if (!DexFile::Open(dex_filename, dex_location, &error_msg, dex_files)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001533 LOG(WARNING) << "Failed to open .dex from file '" << dex_filename << "': " << error_msg;
1534 ++failure_count;
1535 }
1536 ATRACE_END();
1537 }
1538 return failure_count;
1539 }
1540
Andreas Gampee3712d02015-04-09 14:46:31 -07001541 // Returns true if dex_files has a dex with the named location. We compare canonical locations,
1542 // so that relative and absolute paths will match. Not caching for the dex_files isn't very
1543 // efficient, but under normal circumstances the list is neither large nor is this part too
1544 // sensitive.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001545 static bool DexFilesContains(const std::vector<const DexFile*>& dex_files,
1546 const std::string& location) {
Andreas Gampee3712d02015-04-09 14:46:31 -07001547 std::string canonical_location(DexFile::GetDexCanonicalLocation(location.c_str()));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001548 for (size_t i = 0; i < dex_files.size(); ++i) {
Andreas Gampee3712d02015-04-09 14:46:31 -07001549 if (DexFile::GetDexCanonicalLocation(dex_files[i]->GetLocation().c_str()) ==
1550 canonical_location) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001551 return true;
1552 }
1553 }
1554 return false;
1555 }
1556
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001557 // Appends to opened_dex_files any elements of class_path that dex_files
1558 // doesn't already contain. This will open those dex files as necessary.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001559 static void OpenClassPathFiles(const std::string& class_path,
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001560 std::vector<const DexFile*> dex_files,
1561 std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001562 DCHECK(opened_dex_files != nullptr) << "OpenClassPathFiles out-param is nullptr";
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001563 std::vector<std::string> parsed;
1564 Split(class_path, ':', &parsed);
1565 // Take Locks::mutator_lock_ so that lock ordering on the ClassLinker::dex_lock_ is maintained.
1566 ScopedObjectAccess soa(Thread::Current());
1567 for (size_t i = 0; i < parsed.size(); ++i) {
1568 if (DexFilesContains(dex_files, parsed[i])) {
1569 continue;
1570 }
1571 std::string error_msg;
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001572 if (!DexFile::Open(parsed[i].c_str(), parsed[i].c_str(), &error_msg, opened_dex_files)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001573 LOG(WARNING) << "Failed to open dex file '" << parsed[i] << "': " << error_msg;
1574 }
1575 }
1576 }
1577
1578 // Create a runtime necessary for compilation.
1579 bool CreateRuntime(const RuntimeOptions& runtime_options)
1580 SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_) {
1581 if (!Runtime::Create(runtime_options, false)) {
1582 LOG(ERROR) << "Failed to create runtime";
1583 return false;
1584 }
1585 Runtime* runtime = Runtime::Current();
1586 runtime->SetInstructionSet(instruction_set_);
1587 for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
1588 Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i);
1589 if (!runtime->HasCalleeSaveMethod(type)) {
1590 runtime->SetCalleeSaveMethod(runtime->CreateCalleeSaveMethod(), type);
1591 }
1592 }
1593 runtime->GetClassLinker()->FixupDexCaches(runtime->GetResolutionMethod());
Andreas Gampe2969bcd2015-03-09 12:57:41 -07001594
1595 // Initialize maps for unstarted runtime. This needs to be here, as running clinits needs this
1596 // set up.
1597 interpreter::UnstartedRuntimeInitialize();
1598
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001599 runtime->GetClassLinker()->RunRootClinits();
1600 runtime_ = runtime;
Andreas Gampe2969bcd2015-03-09 12:57:41 -07001601
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001602 return true;
1603 }
1604
1605 void PrepareImageWriter(uintptr_t image_base) {
1606 image_writer_.reset(new ImageWriter(*driver_, image_base, compiler_options_->GetCompilePic()));
1607 }
1608
1609 // Let the ImageWriter write the image file. If we do not compile PIC, also fix up the oat file.
1610 bool CreateImageFile()
1611 LOCKS_EXCLUDED(Locks::mutator_lock_) {
1612 CHECK(image_writer_ != nullptr);
1613 if (!image_writer_->Write(image_filename_, oat_unstripped_, oat_location_)) {
1614 LOG(ERROR) << "Failed to create image file " << image_filename_;
1615 return false;
1616 }
1617 uintptr_t oat_data_begin = image_writer_->GetOatDataBegin();
1618
1619 // Destroy ImageWriter before doing FixupElf.
1620 image_writer_.reset();
1621
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001622 // Do not fix up the ELF file if we are --compile-pic
1623 if (!compiler_options_->GetCompilePic()) {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001624 std::unique_ptr<File> oat_file(OS::OpenFileReadWrite(oat_unstripped_.c_str()));
1625 if (oat_file.get() == nullptr) {
1626 PLOG(ERROR) << "Failed to open ELF file: " << oat_unstripped_;
1627 return false;
1628 }
1629
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001630 if (!ElfWriter::Fixup(oat_file.get(), oat_data_begin)) {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001631 oat_file->Erase();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001632 LOG(ERROR) << "Failed to fixup ELF file " << oat_file->GetPath();
1633 return false;
1634 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001635
1636 if (oat_file->FlushCloseOrErase()) {
1637 PLOG(ERROR) << "Failed to flush and close fixed ELF file " << oat_file->GetPath();
1638 return false;
1639 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001640 }
1641
1642 return true;
1643 }
1644
1645 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001646 static std::unordered_set<std::string>* ReadImageClassesFromFile(
1647 const char* image_classes_filename) {
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001648 std::function<std::string(const char*)> process = DotToDescriptor;
1649 return ReadCommentedInputFromFile(image_classes_filename, &process);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001650 }
1651
1652 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001653 static std::unordered_set<std::string>* ReadImageClassesFromZip(
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001654 const char* zip_filename,
1655 const char* image_classes_filename,
1656 std::string* error_msg) {
1657 std::function<std::string(const char*)> process = DotToDescriptor;
1658 return ReadCommentedInputFromZip(zip_filename, image_classes_filename, &process, error_msg);
1659 }
1660
1661 // Read lines from the given file, dropping comments and empty lines. Post-process each line with
1662 // the given function.
1663 static std::unordered_set<std::string>* ReadCommentedInputFromFile(
1664 const char* input_filename, std::function<std::string(const char*)>* process) {
1665 std::unique_ptr<std::ifstream> input_file(new std::ifstream(input_filename, std::ifstream::in));
1666 if (input_file.get() == nullptr) {
1667 LOG(ERROR) << "Failed to open input file " << input_filename;
1668 return nullptr;
1669 }
1670 std::unique_ptr<std::unordered_set<std::string>> result(
1671 ReadCommentedInputStream(*input_file, process));
1672 input_file->close();
1673 return result.release();
1674 }
1675
1676 // Read lines from the given file from the given zip file, dropping comments and empty lines.
1677 // Post-process each line with the given function.
1678 static std::unordered_set<std::string>* ReadCommentedInputFromZip(
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001679 const char* zip_filename,
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001680 const char* input_filename,
1681 std::function<std::string(const char*)>* process,
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001682 std::string* error_msg) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001683 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::Open(zip_filename, error_msg));
1684 if (zip_archive.get() == nullptr) {
1685 return nullptr;
1686 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001687 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(input_filename, error_msg));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001688 if (zip_entry.get() == nullptr) {
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001689 *error_msg = StringPrintf("Failed to find '%s' within '%s': %s", input_filename,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001690 zip_filename, error_msg->c_str());
1691 return nullptr;
1692 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001693 std::unique_ptr<MemMap> input_file(zip_entry->ExtractToMemMap(zip_filename,
1694 input_filename,
1695 error_msg));
1696 if (input_file.get() == nullptr) {
1697 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", input_filename,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001698 zip_filename, error_msg->c_str());
1699 return nullptr;
1700 }
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001701 const std::string input_string(reinterpret_cast<char*>(input_file->Begin()),
1702 input_file->Size());
1703 std::istringstream input_stream(input_string);
1704 return ReadCommentedInputStream(input_stream, process);
1705 }
1706
1707 // Read lines from the given stream, dropping comments and empty lines. Post-process each line
1708 // with the given function.
1709 static std::unordered_set<std::string>* ReadCommentedInputStream(
1710 std::istream& in_stream,
1711 std::function<std::string(const char*)>* process) {
1712 std::unique_ptr<std::unordered_set<std::string>> image_classes(
1713 new std::unordered_set<std::string>);
1714 while (in_stream.good()) {
1715 std::string dot;
1716 std::getline(in_stream, dot);
1717 if (StartsWith(dot, "#") || dot.empty()) {
1718 continue;
1719 }
1720 if (process != nullptr) {
1721 std::string descriptor((*process)(dot.c_str()));
1722 image_classes->insert(descriptor);
1723 } else {
1724 image_classes->insert(dot);
1725 }
1726 }
1727 return image_classes.release();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001728 }
1729
Mathieu Chartier49285c52014-12-02 15:43:48 -08001730 void LogCompletionTime() {
Andreas Gampe1d00add2015-02-27 19:35:46 -08001731 // Note: when creation of a runtime fails, e.g., when trying to compile an app but when there
1732 // is no image, there won't be a Runtime::Current().
Brian Carlstroma11a34c2015-03-06 08:44:45 -08001733 // Note: driver creation can fail when loading an invalid dex file.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001734 LOG(INFO) << "dex2oat took " << PrettyDuration(NanoTime() - start_ns_)
Mathieu Chartierab972ef2014-12-03 17:38:22 -08001735 << " (threads: " << thread_count_ << ") "
Brian Carlstroma11a34c2015-03-06 08:44:45 -08001736 << ((Runtime::Current() != nullptr && driver_.get() != nullptr) ?
Andreas Gampe1d00add2015-02-27 19:35:46 -08001737 driver_->GetMemoryUsageString(kIsDebugBuild || VLOG_IS_ON(compiler)) :
1738 "");
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001739 }
1740
1741 std::unique_ptr<CompilerOptions> compiler_options_;
1742 Compiler::Kind compiler_kind_;
1743
1744 InstructionSet instruction_set_;
1745 std::unique_ptr<const InstructionSetFeatures> instruction_set_features_;
1746
1747 std::unique_ptr<SafeMap<std::string, std::string> > key_value_store_;
1748
1749 std::unique_ptr<VerificationResults> verification_results_;
1750 DexFileToMethodInlinerMap method_inliner_map_;
1751 std::unique_ptr<QuickCompilerCallbacks> callbacks_;
1752
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001753 // Ownership for the class path files.
1754 std::vector<std::unique_ptr<const DexFile>> class_path_files_;
1755
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001756 // Not a unique_ptr as we want to just exit on non-debug builds, not bringing the runtime down
1757 // in an orderly fashion. The destructor takes care of deleting this.
1758 Runtime* runtime_;
1759
1760 size_t thread_count_;
1761 uint64_t start_ns_;
1762 std::unique_ptr<WatchDog> watchdog_;
1763 std::unique_ptr<File> oat_file_;
1764 std::string oat_stripped_;
1765 std::string oat_unstripped_;
1766 std::string oat_location_;
1767 std::string oat_filename_;
1768 int oat_fd_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001769 std::vector<const char*> dex_filenames_;
1770 std::vector<const char*> dex_locations_;
1771 int zip_fd_;
1772 std::string zip_location_;
1773 std::string boot_image_option_;
1774 std::vector<const char*> runtime_args_;
1775 std::string image_filename_;
1776 uintptr_t image_base_;
1777 const char* image_classes_zip_filename_;
1778 const char* image_classes_filename_;
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001779 const char* compiled_classes_zip_filename_;
1780 const char* compiled_classes_filename_;
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001781 const char* compiled_methods_zip_filename_;
1782 const char* compiled_methods_filename_;
Andreas Gampeb1fcead2015-04-20 18:53:51 -07001783 std::unique_ptr<std::unordered_set<std::string>> image_classes_;
1784 std::unique_ptr<std::unordered_set<std::string>> compiled_classes_;
Andreas Gampe70bef0d2015-04-15 02:37:28 -07001785 std::unique_ptr<std::unordered_set<std::string>> compiled_methods_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001786 bool image_;
1787 std::unique_ptr<ImageWriter> image_writer_;
1788 bool is_host_;
1789 std::string android_root_;
1790 std::vector<const DexFile*> dex_files_;
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001791 std::vector<std::unique_ptr<const DexFile>> opened_dex_files_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001792 std::unique_ptr<CompilerDriver> driver_;
1793 std::vector<std::string> verbose_methods_;
1794 bool dump_stats_;
1795 bool dump_passes_;
1796 bool dump_timing_;
1797 bool dump_slow_timing_;
David Brazdil866c0312015-01-13 21:21:31 +00001798 std::string dump_cfg_file_name_;
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001799 std::string swap_file_name_;
1800 int swap_fd_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001801 std::string profile_file_; // Profile file to use
1802 TimingLogger* timings_;
1803 std::unique_ptr<CumulativeLogger> compiler_phases_timings_;
Andreas Gampedbfe2542014-11-25 22:21:42 -08001804 std::unique_ptr<std::ostream> init_failure_output_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001805
1806 DISALLOW_IMPLICIT_CONSTRUCTORS(Dex2Oat);
1807};
1808
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001809static void b13564922() {
1810#if defined(__linux__) && defined(__arm__)
1811 int major, minor;
1812 struct utsname uts;
1813 if (uname(&uts) != -1 &&
1814 sscanf(uts.release, "%d.%d", &major, &minor) == 2 &&
1815 ((major < 3) || ((major == 3) && (minor < 4)))) {
1816 // Kernels before 3.4 don't handle the ASLR well and we can run out of address
1817 // space (http://b/13564922). Work around the issue by inhibiting further mmap() randomization.
1818 int old_personality = personality(0xffffffff);
1819 if ((old_personality & ADDR_NO_RANDOMIZE) == 0) {
1820 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
1821 if (new_personality == -1) {
1822 LOG(WARNING) << "personality(. | ADDR_NO_RANDOMIZE) failed.";
1823 }
1824 }
1825 }
1826#endif
1827}
1828
Andreas Gampe10e477d2014-11-19 12:57:42 -08001829static int CompileImage(Dex2Oat& dex2oat) {
1830 dex2oat.Compile();
1831
1832 // Create the boot.oat.
1833 if (!dex2oat.CreateOatFile()) {
Andreas Gampea650e702014-12-03 14:28:02 -08001834 dex2oat.EraseOatFile();
Andreas Gampe10e477d2014-11-19 12:57:42 -08001835 return EXIT_FAILURE;
1836 }
1837
1838 // Flush and close the boot.oat. We always expect the output file by name, and it will be
1839 // re-opened from the unstripped name.
1840 if (!dex2oat.FlushCloseOatFile()) {
1841 return EXIT_FAILURE;
1842 }
1843
1844 // Creates the boot.art and patches the boot.oat.
1845 if (!dex2oat.HandleImage()) {
1846 return EXIT_FAILURE;
1847 }
1848
1849 // When given --host, finish early without stripping.
1850 if (dex2oat.IsHost()) {
1851 dex2oat.DumpTiming();
1852 return EXIT_SUCCESS;
1853 }
1854
1855 // Copy unstripped to stripped location, if necessary.
1856 if (!dex2oat.CopyUnstrippedToStripped()) {
1857 return EXIT_FAILURE;
1858 }
1859
Andreas Gampe10e477d2014-11-19 12:57:42 -08001860 // FlushClose again, as stripping might have re-opened the oat file.
1861 if (!dex2oat.FlushCloseOatFile()) {
1862 return EXIT_FAILURE;
1863 }
1864
1865 dex2oat.DumpTiming();
1866 return EXIT_SUCCESS;
1867}
1868
1869static int CompileApp(Dex2Oat& dex2oat) {
1870 dex2oat.Compile();
1871
1872 // Create the app oat.
1873 if (!dex2oat.CreateOatFile()) {
Andreas Gampea650e702014-12-03 14:28:02 -08001874 dex2oat.EraseOatFile();
Andreas Gampe10e477d2014-11-19 12:57:42 -08001875 return EXIT_FAILURE;
1876 }
1877
1878 // Do not close the oat file here. We might haven gotten the output file by file descriptor,
1879 // which we would lose.
1880 if (!dex2oat.FlushOatFile()) {
1881 return EXIT_FAILURE;
1882 }
1883
1884 // When given --host, finish early without stripping.
1885 if (dex2oat.IsHost()) {
1886 if (!dex2oat.FlushCloseOatFile()) {
1887 return EXIT_FAILURE;
1888 }
1889
1890 dex2oat.DumpTiming();
1891 return EXIT_SUCCESS;
1892 }
1893
1894 // Copy unstripped to stripped location, if necessary. This will implicitly flush & close the
1895 // unstripped version. If this is given, we expect to be able to open writable files by name.
1896 if (!dex2oat.CopyUnstrippedToStripped()) {
1897 return EXIT_FAILURE;
1898 }
1899
Andreas Gampe10e477d2014-11-19 12:57:42 -08001900 // Flush and close the file.
1901 if (!dex2oat.FlushCloseOatFile()) {
1902 return EXIT_FAILURE;
1903 }
1904
1905 dex2oat.DumpTiming();
1906 return EXIT_SUCCESS;
1907}
1908
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001909static int dex2oat(int argc, char** argv) {
1910 b13564922();
1911
1912 TimingLogger timings("compiler", false, false);
1913
1914 Dex2Oat dex2oat(&timings);
1915
1916 // Parse arguments. Argument mistakes will lead to exit(EXIT_FAILURE) in UsageError.
1917 dex2oat.ParseArgs(argc, argv);
1918
1919 // Check early that the result of compilation can be written
1920 if (!dex2oat.OpenFile()) {
1921 return EXIT_FAILURE;
1922 }
1923
1924 LOG(INFO) << CommandLine();
1925
1926 if (!dex2oat.Setup()) {
Andreas Gampea650e702014-12-03 14:28:02 -08001927 dex2oat.EraseOatFile();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001928 return EXIT_FAILURE;
1929 }
1930
Andreas Gampe10e477d2014-11-19 12:57:42 -08001931 if (dex2oat.IsImage()) {
1932 return CompileImage(dex2oat);
1933 } else {
1934 return CompileApp(dex2oat);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001935 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001936}
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001937} // namespace art
Brian Carlstrom7940e442013-07-12 13:46:57 -07001938
1939int main(int argc, char** argv) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001940 int result = art::dex2oat(argc, argv);
1941 // Everything was done, do an explicit exit here to avoid running Runtime destructors that take
1942 // time (bug 10645725) unless we're a debug build or running on valgrind. Note: The Dex2Oat class
1943 // should not destruct the runtime in this case.
1944 if (!art::kIsDebugBuild && (RUNNING_ON_VALGRIND == 0)) {
1945 exit(result);
1946 }
1947 return result;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001948}