blob: 128f6238a9fa88dde9e5e483778b81c10e1d56fb [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
17#include <stdio.h>
18#include <stdlib.h>
19#include <sys/stat.h>
Ian Rogers2672a9f2013-09-05 17:24:22 -070020#include <valgrind.h>
Brian Carlstrom7940e442013-07-12 13:46:57 -070021
22#include <fstream>
23#include <iostream>
24#include <sstream>
25#include <string>
26#include <vector>
27
Vladimir Markof94b7812014-06-05 15:48:04 +010028#if defined(__linux__) && defined(__arm__)
29#include <sys/personality.h>
30#include <sys/utsname.h>
31#endif
32
Ian Rogerscf7f1912014-10-22 22:06:39 -070033#define ATRACE_TAG ATRACE_TAG_DALVIK
Ian Rogersd582fa42014-11-05 23:46:43 -080034#include <cutils/trace.h>
Ian Rogerscf7f1912014-10-22 22:06:39 -070035
Ian Rogersd582fa42014-11-05 23:46:43 -080036#include "arch/instruction_set_features.h"
Andreas Gampec5a3ea72015-01-13 16:41:53 -080037#include "arch/mips/instruction_set_features_mips.h"
Ian Rogersc7dd2952014-10-21 23:31:19 -070038#include "base/dumpable.h"
Andreas Gampe794ad762015-02-23 08:12:24 -080039#include "base/macros.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070040#include "base/stl_util.h"
41#include "base/stringpiece.h"
42#include "base/timing_logger.h"
43#include "base/unix_file/fd_file.h"
44#include "class_linker.h"
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +000045#include "compiler.h"
Vladimir Marko2b5eaa22013-12-13 13:59:30 +000046#include "compiler_callbacks.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070047#include "dex_file-inl.h"
Mathieu Chartier5bdab122015-01-26 18:30:19 -080048#include "dex/pass_manager.h"
Vladimir Markoc7f83202014-01-24 17:55:18 +000049#include "dex/verification_results.h"
Ian Rogerse63db272014-07-15 15:36:11 -070050#include "dex/quick_compiler_callbacks.h"
51#include "dex/quick/dex_file_to_method_inliner_map.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070052#include "driver/compiler_driver.h"
Brian Carlstrom6449c622014-02-10 23:48:36 -080053#include "driver/compiler_options.h"
Andreas Gampe88ec7f42014-11-05 10:18:32 -080054#include "elf_file.h"
Tong Shen62d1ca32014-09-03 17:24:56 -070055#include "elf_writer.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070056#include "gc/space/image_space.h"
57#include "gc/space/space-inl.h"
58#include "image_writer.h"
59#include "leb128.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070060#include "mirror/art_method-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070061#include "mirror/class-inl.h"
62#include "mirror/class_loader.h"
63#include "mirror/object-inl.h"
64#include "mirror/object_array-inl.h"
65#include "oat_writer.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070066#include "os.h"
67#include "runtime.h"
68#include "ScopedLocalRef.h"
69#include "scoped_thread_state_change.h"
Alex Light53cb16b2014-06-12 11:26:29 -070070#include "utils.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070071#include "vector_output_stream.h"
72#include "well_known_classes.h"
73#include "zip_archive.h"
74
75namespace art {
76
Brian Carlstrom6449c622014-02-10 23:48:36 -080077static int original_argc;
78static char** original_argv;
79
80static std::string CommandLine() {
81 std::vector<std::string> command;
82 for (int i = 0; i < original_argc; ++i) {
83 command.push_back(original_argv[i]);
84 }
85 return Join(command, ' ');
86}
87
Brian Carlstrom7940e442013-07-12 13:46:57 -070088static void UsageErrorV(const char* fmt, va_list ap) {
89 std::string error;
90 StringAppendV(&error, fmt, ap);
91 LOG(ERROR) << error;
92}
93
94static void UsageError(const char* fmt, ...) {
95 va_list ap;
96 va_start(ap, fmt);
97 UsageErrorV(fmt, ap);
98 va_end(ap);
99}
100
Andreas Gampe794ad762015-02-23 08:12:24 -0800101NO_RETURN static void Usage(const char* fmt, ...) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700102 va_list ap;
103 va_start(ap, fmt);
104 UsageErrorV(fmt, ap);
105 va_end(ap);
106
Brian Carlstrom6449c622014-02-10 23:48:36 -0800107 UsageError("Command: %s", CommandLine().c_str());
108
Brian Carlstrom7940e442013-07-12 13:46:57 -0700109 UsageError("Usage: dex2oat [options]...");
110 UsageError("");
111 UsageError(" --dex-file=<dex-file>: specifies a .dex file to compile.");
112 UsageError(" Example: --dex-file=/system/framework/core.jar");
113 UsageError("");
114 UsageError(" --zip-fd=<file-descriptor>: specifies a file descriptor of a zip file");
115 UsageError(" containing a classes.dex file to compile.");
116 UsageError(" Example: --zip-fd=5");
117 UsageError("");
Brian Carlstrom45602482013-07-21 22:07:55 -0700118 UsageError(" --zip-location=<zip-location>: specifies a symbolic name for the file");
119 UsageError(" corresponding to the file descriptor specified by --zip-fd.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700120 UsageError(" Example: --zip-location=/system/app/Calculator.apk");
121 UsageError("");
122 UsageError(" --oat-file=<file.oat>: specifies the oat output destination via a filename.");
123 UsageError(" Example: --oat-file=/system/framework/boot.oat");
124 UsageError("");
125 UsageError(" --oat-fd=<number>: specifies the oat output destination via a file descriptor.");
Wonil Kim9cb554a2014-04-28 11:26:55 +0900126 UsageError(" Example: --oat-fd=6");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700127 UsageError("");
128 UsageError(" --oat-location=<oat-name>: specifies a symbolic name for the file corresponding");
129 UsageError(" to the file descriptor specified by --oat-fd.");
130 UsageError(" Example: --oat-location=/data/dalvik-cache/system@app@Calculator.apk.oat");
131 UsageError("");
132 UsageError(" --oat-symbols=<file.oat>: specifies the oat output destination with full symbols.");
133 UsageError(" Example: --oat-symbols=/symbols/system/framework/boot.oat");
134 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700135 UsageError(" --image=<file.art>: specifies the output image filename.");
136 UsageError(" Example: --image=/system/framework/boot.art");
137 UsageError("");
138 UsageError(" --image-classes=<classname-file>: specifies classes to include in an image.");
139 UsageError(" Example: --image=frameworks/base/preloaded-classes");
140 UsageError("");
141 UsageError(" --base=<hex-address>: specifies the base address when creating a boot image.");
142 UsageError(" Example: --base=0x50000000");
143 UsageError("");
144 UsageError(" --boot-image=<file.art>: provide the image file for the boot class path.");
145 UsageError(" Example: --boot-image=/system/framework/boot.art");
Nicolas Geoffray9583fbc2014-02-28 15:21:07 +0000146 UsageError(" Default: $ANDROID_ROOT/system/framework/boot.art");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700147 UsageError("");
148 UsageError(" --android-root=<path>: used to locate libraries for portable linking.");
149 UsageError(" Example: --android-root=out/host/linux-x86");
150 UsageError(" Default: $ANDROID_ROOT");
151 UsageError("");
Andreas Gampe57b34292015-01-14 15:45:59 -0800152 UsageError(" --instruction-set=(arm|arm64|mips|mips64|x86|x86_64): compile for a particular");
Alex Light53cb16b2014-06-12 11:26:29 -0700153 UsageError(" instruction set.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700154 UsageError(" Example: --instruction-set=x86");
155 UsageError(" Default: arm");
156 UsageError("");
Dave Allison70202782013-10-22 17:52:19 -0700157 UsageError(" --instruction-set-features=...,: Specify instruction set features");
158 UsageError(" Example: --instruction-set-features=div");
159 UsageError(" Default: default");
160 UsageError("");
Igor Murashkin46774762014-10-22 11:37:02 -0700161 UsageError(" --compile-pic: Force indirect use of code, methods, and classes");
162 UsageError(" Default: disabled");
163 UsageError("");
Elliott Hughes956af0f2014-12-11 14:34:28 -0800164 UsageError(" --compiler-backend=(Quick|Optimizing): select compiler backend");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700165 UsageError(" set.");
Elliott Hughes956af0f2014-12-11 14:34:28 -0800166 UsageError(" Example: --compiler-backend=Optimizing");
167 if (kUseOptimizingCompiler) {
Nicolas Geoffray4586fb62014-11-28 16:22:11 +0000168 UsageError(" Default: Optimizing");
169 } else {
170 UsageError(" Default: Quick");
171 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700172 UsageError("");
Nicolas Geoffray88157ef2014-09-12 10:29:53 +0100173 UsageError(" --compiler-filter="
174 "(verify-none"
175 "|interpret-only"
176 "|space"
177 "|balanced"
178 "|speed"
179 "|everything"
180 "|time):");
Jeff Hao4a200f52014-04-01 14:58:49 -0700181 UsageError(" select compiler filter.");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800182 UsageError(" Example: --compiler-filter=everything");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800183 UsageError(" Default: speed");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800184 UsageError("");
185 UsageError(" --huge-method-max=<method-instruction-count>: the threshold size for a huge");
186 UsageError(" method for compiler filter tuning.");
187 UsageError(" Example: --huge-method-max=%d", CompilerOptions::kDefaultHugeMethodThreshold);
188 UsageError(" Default: %d", CompilerOptions::kDefaultHugeMethodThreshold);
189 UsageError("");
190 UsageError(" --huge-method-max=<method-instruction-count>: threshold size for a huge");
191 UsageError(" method for compiler filter tuning.");
192 UsageError(" Example: --huge-method-max=%d", CompilerOptions::kDefaultHugeMethodThreshold);
193 UsageError(" Default: %d", CompilerOptions::kDefaultHugeMethodThreshold);
194 UsageError("");
195 UsageError(" --large-method-max=<method-instruction-count>: threshold size for a large");
196 UsageError(" method for compiler filter tuning.");
197 UsageError(" Example: --large-method-max=%d", CompilerOptions::kDefaultLargeMethodThreshold);
198 UsageError(" Default: %d", CompilerOptions::kDefaultLargeMethodThreshold);
199 UsageError("");
200 UsageError(" --small-method-max=<method-instruction-count>: threshold size for a small");
201 UsageError(" method for compiler filter tuning.");
202 UsageError(" Example: --small-method-max=%d", CompilerOptions::kDefaultSmallMethodThreshold);
203 UsageError(" Default: %d", CompilerOptions::kDefaultSmallMethodThreshold);
204 UsageError("");
205 UsageError(" --tiny-method-max=<method-instruction-count>: threshold size for a tiny");
206 UsageError(" method for compiler filter tuning.");
207 UsageError(" Example: --tiny-method-max=%d", CompilerOptions::kDefaultTinyMethodThreshold);
208 UsageError(" Default: %d", CompilerOptions::kDefaultTinyMethodThreshold);
209 UsageError("");
210 UsageError(" --num-dex-methods=<method-count>: threshold size for a small dex file for");
211 UsageError(" compiler filter tuning. If the input has fewer than this many methods");
Jeff Hao4a200f52014-04-01 14:58:49 -0700212 UsageError(" and the filter is not interpret-only or verify-none, overrides the");
213 UsageError(" filter to use speed");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800214 UsageError(" Example: --num-dex-method=%d", CompilerOptions::kDefaultNumDexMethodsThreshold);
215 UsageError(" Default: %d", CompilerOptions::kDefaultNumDexMethodsThreshold);
216 UsageError("");
Ian Rogers46398602013-08-20 07:50:36 -0700217 UsageError(" --dump-timing: display a breakdown of where time was spent");
218 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700219 UsageError(" --include-patch-information: Include patching information so the generated code");
220 UsageError(" can have its base address moved without full recompilation.");
221 UsageError("");
222 UsageError(" --no-include-patch-information: Do not include patching information.");
223 UsageError("");
Alex Light78382fa2014-06-06 15:45:32 -0700224 UsageError(" --include-debug-symbols: Include ELF symbols in this oat file");
225 UsageError("");
226 UsageError(" --no-include-debug-symbols: Do not include ELF symbols in this oat file");
227 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700228 UsageError(" --runtime-arg <argument>: used to specify various arguments for the runtime,");
229 UsageError(" such as initial heap size, maximum heap size, and verbose output.");
230 UsageError(" Use a separate --runtime-arg switch for each argument.");
231 UsageError(" Example: --runtime-arg -Xms256m");
Jeff Hao4a200f52014-04-01 14:58:49 -0700232 UsageError("");
Dave Allisond6ed6422014-04-09 23:36:15 +0000233 UsageError(" --profile-file=<filename>: specify profiler output file to use for compilation.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700234 UsageError("");
Chao-ying Fucd8ce662014-03-11 14:57:19 -0700235 UsageError(" --print-pass-names: print a list of pass names");
236 UsageError("");
237 UsageError(" --disable-passes=<pass-names>: disable one or more passes separated by comma.");
238 UsageError(" Example: --disable-passes=UseCount,BBOptimizations");
239 UsageError("");
Razvan A Lupusorubd25d4b2014-07-02 18:16:51 -0700240 UsageError(" --print-pass-options: print a list of passes that have configurable options along "
241 "with the setting.");
242 UsageError(" Will print default if no overridden setting exists.");
243 UsageError("");
244 UsageError(" --pass-options=Pass1Name:Pass1OptionName:Pass1Option#,"
245 "Pass2Name:Pass2OptionName:Pass2Option#");
246 UsageError(" Used to specify a pass specific option. The setting itself must be integer.");
247 UsageError(" Separator used between options is a comma.");
248 UsageError("");
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800249 UsageError(" --swap-file=<file-name>: specifies a file to use for swap.");
250 UsageError(" Example: --swap-file=/data/tmp/swap.001");
251 UsageError("");
252 UsageError(" --swap-fd=<file-descriptor>: specifies a file to use for swap (by descriptor).");
253 UsageError(" Example: --swap-fd=10");
254 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700255 std::cerr << "See log for usage error information\n";
256 exit(EXIT_FAILURE);
257}
258
Brian Carlstrom7940e442013-07-12 13:46:57 -0700259// The primary goal of the watchdog is to prevent stuck build servers
260// during development when fatal aborts lead to a cascade of failures
261// that result in a deadlock.
262class WatchDog {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800263// WatchDog defines its own CHECK_PTHREAD_CALL to avoid using LOG which uses locks
Brian Carlstrom7940e442013-07-12 13:46:57 -0700264#undef CHECK_PTHREAD_CALL
265#define CHECK_WATCH_DOG_PTHREAD_CALL(call, args, what) \
266 do { \
267 int rc = call args; \
268 if (rc != 0) { \
269 errno = rc; \
270 std::string message(# call); \
271 message += " failed for "; \
272 message += reason; \
273 Fatal(message); \
274 } \
275 } while (false)
276
277 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -0700278 explicit WatchDog(bool is_watch_dog_enabled) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700279 is_watch_dog_enabled_ = is_watch_dog_enabled;
280 if (!is_watch_dog_enabled_) {
281 return;
282 }
283 shutting_down_ = false;
284 const char* reason = "dex2oat watch dog thread startup";
Kenny Root51316382014-05-13 14:59:37 -0700285 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_init, (&mutex_, nullptr), reason);
286 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_init, (&cond_, nullptr), reason);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700287 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_init, (&attr_), reason);
288 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_create, (&pthread_, &attr_, &CallBack, this), reason);
289 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_destroy, (&attr_), reason);
290 }
291 ~WatchDog() {
292 if (!is_watch_dog_enabled_) {
293 return;
294 }
295 const char* reason = "dex2oat watch dog thread shutdown";
296 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
297 shutting_down_ = true;
298 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_signal, (&cond_), reason);
299 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
300
Kenny Root51316382014-05-13 14:59:37 -0700301 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_join, (pthread_, nullptr), reason);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700302
303 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_destroy, (&cond_), reason);
304 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_destroy, (&mutex_), reason);
305 }
306
307 private:
308 static void* CallBack(void* arg) {
309 WatchDog* self = reinterpret_cast<WatchDog*>(arg);
310 ::art::SetThreadName("dex2oat watch dog");
311 self->Wait();
Kenny Root51316382014-05-13 14:59:37 -0700312 return nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700313 }
314
315 static void Message(char severity, const std::string& message) {
316 // TODO: Remove when we switch to LOG when we can guarantee it won't prevent shutdown in error
317 // cases.
318 fprintf(stderr, "dex2oat%s %c %d %d %s\n",
319 kIsDebugBuild ? "d" : "",
320 severity,
321 getpid(),
322 GetTid(),
323 message.c_str());
324 }
325
Andreas Gampe794ad762015-02-23 08:12:24 -0800326 NO_RETURN static void Fatal(const std::string& message) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700327 Message('F', message);
328 exit(1);
329 }
330
331 void Wait() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700332 // TODO: tune the multiplier for GC verification, the following is just to make the timeout
333 // large.
Mathieu Chartier4e305412014-02-19 10:54:44 -0800334 int64_t multiplier = kVerifyObjectSupport > kVerifyObjectModeFast ? 100 : 1;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700335 timespec timeout_ts;
336 InitTimeSpec(true, CLOCK_REALTIME, multiplier * kWatchDogTimeoutSeconds * 1000, 0, &timeout_ts);
337 const char* reason = "dex2oat watch dog thread waiting";
338 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
339 while (!shutting_down_) {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800340 int rc = TEMP_FAILURE_RETRY(pthread_cond_timedwait(&cond_, &mutex_, &timeout_ts));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700341 if (rc == ETIMEDOUT) {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800342 Fatal(StringPrintf("dex2oat did not finish after %d seconds", kWatchDogTimeoutSeconds));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700343 } else if (rc != 0) {
344 std::string message(StringPrintf("pthread_cond_timedwait failed: %s",
345 strerror(errno)));
346 Fatal(message.c_str());
347 }
348 }
349 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
350 }
351
352 // 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 -0700353 // Debug builds are slower so they have larger timeouts.
354 static const unsigned int kSlowdownFactor = kIsDebugBuild ? 5U : 1U;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800355
Elliott Hughes956af0f2014-12-11 14:34:28 -0800356 // 6 minutes scaled by kSlowdownFactor.
357 static const unsigned int kWatchDogTimeoutSeconds = kSlowdownFactor * 6 * 60;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700358
359 bool is_watch_dog_enabled_;
360 bool shutting_down_;
361 // TODO: Switch to Mutex when we can guarantee it won't prevent shutdown in error cases.
362 pthread_mutex_t mutex_;
363 pthread_cond_t cond_;
364 pthread_attr_t attr_;
365 pthread_t pthread_;
366};
Brian Carlstrom7940e442013-07-12 13:46:57 -0700367
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800368static void ParseStringAfterChar(const std::string& s, char c, std::string* parsed_value) {
Calin Juravlec1b643c2014-05-30 23:44:11 +0100369 std::string::size_type colon = s.find(c);
370 if (colon == std::string::npos) {
371 Usage("Missing char %c in option %s\n", c, s.c_str());
372 }
373 // Add one to remove the char we were trimming until.
374 *parsed_value = s.substr(colon + 1);
375}
376
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800377static void ParseDouble(const std::string& option, char after_char, double min, double max,
378 double* parsed_value) {
Calin Juravlec1b643c2014-05-30 23:44:11 +0100379 std::string substring;
380 ParseStringAfterChar(option, after_char, &substring);
381 bool sane_val = true;
382 double value;
383 if (false) {
384 // TODO: this doesn't seem to work on the emulator. b/15114595
385 std::stringstream iss(substring);
386 iss >> value;
387 // Ensure that we have a value, there was no cruft after it and it satisfies a sensible range.
388 sane_val = iss.eof() && (value >= min) && (value <= max);
389 } else {
390 char* end = nullptr;
391 value = strtod(substring.c_str(), &end);
392 sane_val = *end == '\0' && value >= min && value <= max;
393 }
394 if (!sane_val) {
395 Usage("Invalid double value %s for option %s\n", substring.c_str(), option.c_str());
396 }
397 *parsed_value = value;
398}
399
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800400static constexpr size_t kMinDexFilesForSwap = 2;
401static constexpr size_t kMinDexFileCumulativeSizeForSwap = 20 * MB;
402
403static bool UseSwap(bool is_image, std::vector<const DexFile*>& dex_files) {
404 if (is_image) {
405 // Don't use swap, we know generation should succeed, and we don't want to slow it down.
406 return false;
407 }
408 if (dex_files.size() < kMinDexFilesForSwap) {
409 // If there are less dex files than the threshold, assume it's gonna be fine.
410 return false;
411 }
412 size_t dex_files_size = 0;
413 for (const auto* dex_file : dex_files) {
414 dex_files_size += dex_file->GetHeader().file_size_;
415 }
416 return dex_files_size >= kMinDexFileCumulativeSizeForSwap;
417}
418
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800419class Dex2Oat FINAL {
420 public:
421 explicit Dex2Oat(TimingLogger* timings) :
Elliott Hughes956af0f2014-12-11 14:34:28 -0800422 compiler_kind_(kUseOptimizingCompiler ? Compiler::kOptimizing : Compiler::kQuick),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800423 instruction_set_(kRuntimeISA),
424 // Take the default set of instruction features from the build.
425 method_inliner_map_(),
426 runtime_(nullptr),
427 thread_count_(sysconf(_SC_NPROCESSORS_CONF)),
428 start_ns_(NanoTime()),
429 oat_fd_(-1),
430 zip_fd_(-1),
431 image_base_(0U),
432 image_classes_zip_filename_(nullptr),
433 image_classes_filename_(nullptr),
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800434 compiled_classes_zip_filename_(nullptr),
435 compiled_classes_filename_(nullptr),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800436 image_(false),
437 is_host_(false),
438 dump_stats_(false),
439 dump_passes_(false),
440 dump_timing_(false),
441 dump_slow_timing_(kIsDebugBuild),
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800442 swap_fd_(-1),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800443 timings_(timings) {}
444
445 ~Dex2Oat() {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800446 // Free opened dex files before deleting the runtime_, because ~DexFile
447 // uses MemMap, which is shut down by ~Runtime.
448 class_path_files_.clear();
449 opened_dex_files_.clear();
450
451 // Log completion time before deleting the runtime_, because this accesses
452 // the runtime.
453 LogCompletionTime();
454
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800455 if (kIsDebugBuild || (RUNNING_ON_VALGRIND != 0)) {
456 delete runtime_; // See field declaration for why this is manual.
Vladimir Markof94b7812014-06-05 15:48:04 +0100457 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700458 }
459
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800460 // Parse the arguments from the command line. In case of an unrecognized option or impossible
461 // values/combinations, a usage error will be displayed and exit() is called. Thus, if the method
462 // returns, arguments have been successfully parsed.
463 void ParseArgs(int argc, char** argv) {
464 original_argc = argc;
465 original_argv = argv;
Dave Allison70202782013-10-22 17:52:19 -0700466
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800467 InitLogging(argv);
Dave Allison70202782013-10-22 17:52:19 -0700468
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800469 // Skip over argv[0].
470 argv++;
471 argc--;
Dave Allison70202782013-10-22 17:52:19 -0700472
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800473 if (argc == 0) {
474 Usage("No arguments specified");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700475 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800476
477 std::string oat_symbols;
478 std::string boot_image_filename;
479 const char* compiler_filter_string = nullptr;
480 bool compile_pic = false;
481 int huge_method_threshold = CompilerOptions::kDefaultHugeMethodThreshold;
482 int large_method_threshold = CompilerOptions::kDefaultLargeMethodThreshold;
483 int small_method_threshold = CompilerOptions::kDefaultSmallMethodThreshold;
484 int tiny_method_threshold = CompilerOptions::kDefaultTinyMethodThreshold;
485 int num_dex_methods_threshold = CompilerOptions::kDefaultNumDexMethodsThreshold;
486
487 // Profile file to use
488 double top_k_profile_threshold = CompilerOptions::kDefaultTopKProfileThreshold;
489
Andreas Gampe7b2f09e2015-03-02 14:07:33 -0800490 bool debuggable = false;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800491 bool include_patch_information = CompilerOptions::kDefaultIncludePatchInformation;
492 bool include_debug_symbols = kIsDebugBuild;
493 bool watch_dog_enabled = true;
494 bool generate_gdb_information = kIsDebugBuild;
Andreas Gampe6cf49e52015-03-05 13:08:45 -0800495 bool abort_on_hard_verifier_error = false;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800496
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800497 PassManagerOptions pass_manager_options;
498
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800499 std::string error_msg;
500
501 for (int i = 0; i < argc; i++) {
502 const StringPiece option(argv[i]);
503 const bool log_options = false;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700504 if (log_options) {
505 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
506 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800507 if (option.starts_with("--dex-file=")) {
508 dex_filenames_.push_back(option.substr(strlen("--dex-file=")).data());
509 } else if (option.starts_with("--dex-location=")) {
510 dex_locations_.push_back(option.substr(strlen("--dex-location=")).data());
511 } else if (option.starts_with("--zip-fd=")) {
512 const char* zip_fd_str = option.substr(strlen("--zip-fd=")).data();
513 if (!ParseInt(zip_fd_str, &zip_fd_)) {
514 Usage("Failed to parse --zip-fd argument '%s' as an integer", zip_fd_str);
515 }
516 if (zip_fd_ < 0) {
517 Usage("--zip-fd passed a negative value %d", zip_fd_);
518 }
519 } else if (option.starts_with("--zip-location=")) {
520 zip_location_ = option.substr(strlen("--zip-location=")).data();
521 } else if (option.starts_with("--oat-file=")) {
522 oat_filename_ = option.substr(strlen("--oat-file=")).data();
523 } else if (option.starts_with("--oat-symbols=")) {
524 oat_symbols = option.substr(strlen("--oat-symbols=")).data();
525 } else if (option.starts_with("--oat-fd=")) {
526 const char* oat_fd_str = option.substr(strlen("--oat-fd=")).data();
527 if (!ParseInt(oat_fd_str, &oat_fd_)) {
528 Usage("Failed to parse --oat-fd argument '%s' as an integer", oat_fd_str);
529 }
530 if (oat_fd_ < 0) {
531 Usage("--oat-fd passed a negative value %d", oat_fd_);
532 }
533 } else if (option == "--watch-dog") {
534 watch_dog_enabled = true;
535 } else if (option == "--no-watch-dog") {
536 watch_dog_enabled = false;
537 } else if (option == "--gen-gdb-info") {
538 generate_gdb_information = true;
539 // Debug symbols are needed for gdb information.
540 include_debug_symbols = true;
541 } else if (option == "--no-gen-gdb-info") {
542 generate_gdb_information = false;
543 } else if (option.starts_with("-j")) {
544 const char* thread_count_str = option.substr(strlen("-j")).data();
545 if (!ParseUint(thread_count_str, &thread_count_)) {
546 Usage("Failed to parse -j argument '%s' as an integer", thread_count_str);
547 }
548 } else if (option.starts_with("--oat-location=")) {
549 oat_location_ = option.substr(strlen("--oat-location=")).data();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800550 } else if (option.starts_with("--image=")) {
551 image_filename_ = option.substr(strlen("--image=")).data();
552 } else if (option.starts_with("--image-classes=")) {
553 image_classes_filename_ = option.substr(strlen("--image-classes=")).data();
554 } else if (option.starts_with("--image-classes-zip=")) {
555 image_classes_zip_filename_ = option.substr(strlen("--image-classes-zip=")).data();
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800556 } else if (option.starts_with("--compiled-classes=")) {
557 compiled_classes_filename_ = option.substr(strlen("--compiled-classes=")).data();
558 } else if (option.starts_with("--compiled-classes-zip=")) {
559 compiled_classes_zip_filename_ = option.substr(strlen("--compiled-classes-zip=")).data();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800560 } else if (option.starts_with("--base=")) {
561 const char* image_base_str = option.substr(strlen("--base=")).data();
562 char* end;
563 image_base_ = strtoul(image_base_str, &end, 16);
564 if (end == image_base_str || *end != '\0') {
565 Usage("Failed to parse hexadecimal value for option %s", option.data());
566 }
567 } else if (option.starts_with("--boot-image=")) {
568 boot_image_filename = option.substr(strlen("--boot-image=")).data();
569 } else if (option.starts_with("--android-root=")) {
570 android_root_ = option.substr(strlen("--android-root=")).data();
571 } else if (option.starts_with("--instruction-set=")) {
572 StringPiece instruction_set_str = option.substr(strlen("--instruction-set=")).data();
573 // StringPiece is not necessarily zero-terminated, so need to make a copy and ensure it.
Dan Albert6fc59ab2014-12-11 14:09:51 -0800574 std::unique_ptr<char[]> buf(new char[instruction_set_str.length() + 1]);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800575 strncpy(buf.get(), instruction_set_str.data(), instruction_set_str.length());
576 buf.get()[instruction_set_str.length()] = 0;
577 instruction_set_ = GetInstructionSetFromString(buf.get());
578 // arm actually means thumb2.
579 if (instruction_set_ == InstructionSet::kArm) {
580 instruction_set_ = InstructionSet::kThumb2;
581 }
582 } else if (option.starts_with("--instruction-set-variant=")) {
583 StringPiece str = option.substr(strlen("--instruction-set-variant=")).data();
584 instruction_set_features_.reset(
585 InstructionSetFeatures::FromVariant(instruction_set_, str.as_string(), &error_msg));
586 if (instruction_set_features_.get() == nullptr) {
587 Usage("%s", error_msg.c_str());
588 }
589 } else if (option.starts_with("--instruction-set-features=")) {
590 StringPiece str = option.substr(strlen("--instruction-set-features=")).data();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800591 if (instruction_set_features_.get() == nullptr) {
Ian Rogersd582fa42014-11-05 23:46:43 -0800592 instruction_set_features_.reset(
593 InstructionSetFeatures::FromVariant(instruction_set_, "default", &error_msg));
594 if (instruction_set_features_.get() == nullptr) {
595 Usage("Problem initializing default instruction set features variant: %s",
596 error_msg.c_str());
597 }
598 }
599 instruction_set_features_.reset(
600 instruction_set_features_->AddFeaturesFromString(str.as_string(), &error_msg));
601 if (instruction_set_features_.get() == nullptr) {
602 Usage("Error parsing '%s': %s", option.data(), error_msg.c_str());
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800603 }
604 } else if (option.starts_with("--compiler-backend=")) {
605 StringPiece backend_str = option.substr(strlen("--compiler-backend=")).data();
606 if (backend_str == "Quick") {
607 compiler_kind_ = Compiler::kQuick;
608 } else if (backend_str == "Optimizing") {
609 compiler_kind_ = Compiler::kOptimizing;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800610 } else {
611 Usage("Unknown compiler backend: %s", backend_str.data());
612 }
613 } else if (option.starts_with("--compiler-filter=")) {
614 compiler_filter_string = option.substr(strlen("--compiler-filter=")).data();
615 } else if (option == "--compile-pic") {
616 compile_pic = true;
617 } else if (option.starts_with("--huge-method-max=")) {
618 const char* threshold = option.substr(strlen("--huge-method-max=")).data();
619 if (!ParseInt(threshold, &huge_method_threshold)) {
620 Usage("Failed to parse --huge-method-max '%s' as an integer", threshold);
621 }
622 if (huge_method_threshold < 0) {
623 Usage("--huge-method-max passed a negative value %s", huge_method_threshold);
624 }
625 } else if (option.starts_with("--large-method-max=")) {
626 const char* threshold = option.substr(strlen("--large-method-max=")).data();
627 if (!ParseInt(threshold, &large_method_threshold)) {
628 Usage("Failed to parse --large-method-max '%s' as an integer", threshold);
629 }
630 if (large_method_threshold < 0) {
631 Usage("--large-method-max passed a negative value %s", large_method_threshold);
632 }
633 } else if (option.starts_with("--small-method-max=")) {
634 const char* threshold = option.substr(strlen("--small-method-max=")).data();
635 if (!ParseInt(threshold, &small_method_threshold)) {
636 Usage("Failed to parse --small-method-max '%s' as an integer", threshold);
637 }
638 if (small_method_threshold < 0) {
639 Usage("--small-method-max passed a negative value %s", small_method_threshold);
640 }
641 } else if (option.starts_with("--tiny-method-max=")) {
642 const char* threshold = option.substr(strlen("--tiny-method-max=")).data();
643 if (!ParseInt(threshold, &tiny_method_threshold)) {
644 Usage("Failed to parse --tiny-method-max '%s' as an integer", threshold);
645 }
646 if (tiny_method_threshold < 0) {
647 Usage("--tiny-method-max passed a negative value %s", tiny_method_threshold);
648 }
649 } else if (option.starts_with("--num-dex-methods=")) {
650 const char* threshold = option.substr(strlen("--num-dex-methods=")).data();
651 if (!ParseInt(threshold, &num_dex_methods_threshold)) {
652 Usage("Failed to parse --num-dex-methods '%s' as an integer", threshold);
653 }
654 if (num_dex_methods_threshold < 0) {
655 Usage("--num-dex-methods passed a negative value %s", num_dex_methods_threshold);
656 }
657 } else if (option == "--host") {
658 is_host_ = true;
659 } else if (option == "--runtime-arg") {
660 if (++i >= argc) {
661 Usage("Missing required argument for --runtime-arg");
662 }
663 if (log_options) {
664 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
665 }
666 runtime_args_.push_back(argv[i]);
667 } else if (option == "--dump-timing") {
668 dump_timing_ = true;
669 } else if (option == "--dump-passes") {
670 dump_passes_ = true;
David Brazdil866c0312015-01-13 21:21:31 +0000671 } else if (option.starts_with("--dump-cfg=")) {
672 dump_cfg_file_name_ = option.substr(strlen("--dump-cfg=")).data();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800673 } else if (option == "--dump-stats") {
674 dump_stats_ = true;
675 } else if (option == "--include-debug-symbols" || option == "--no-strip-symbols") {
676 include_debug_symbols = true;
677 } else if (option == "--no-include-debug-symbols" || option == "--strip-symbols") {
678 include_debug_symbols = false;
679 generate_gdb_information = false; // Depends on debug symbols, see above.
Andreas Gampe7b2f09e2015-03-02 14:07:33 -0800680 } else if (option == "--debuggable") {
681 debuggable = true;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800682 } else if (option.starts_with("--profile-file=")) {
683 profile_file_ = option.substr(strlen("--profile-file=")).data();
684 VLOG(compiler) << "dex2oat: profile file is " << profile_file_;
685 } else if (option == "--no-profile-file") {
686 // No profile
687 } else if (option.starts_with("--top-k-profile-threshold=")) {
688 ParseDouble(option.data(), '=', 0.0, 100.0, &top_k_profile_threshold);
689 } else if (option == "--print-pass-names") {
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800690 pass_manager_options.SetPrintPassNames(true);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800691 } else if (option.starts_with("--disable-passes=")) {
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800692 const std::string disable_passes = option.substr(strlen("--disable-passes=")).data();
693 pass_manager_options.SetDisablePassList(disable_passes);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800694 } else if (option.starts_with("--print-passes=")) {
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800695 const std::string print_passes = option.substr(strlen("--print-passes=")).data();
696 pass_manager_options.SetPrintPassList(print_passes);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800697 } else if (option == "--print-all-passes") {
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800698 pass_manager_options.SetPrintAllPasses();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800699 } else if (option.starts_with("--dump-cfg-passes=")) {
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800700 const std::string dump_passes_string = option.substr(strlen("--dump-cfg-passes=")).data();
701 pass_manager_options.SetDumpPassList(dump_passes_string);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800702 } else if (option == "--print-pass-options") {
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800703 pass_manager_options.SetPrintPassOptions(true);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800704 } else if (option.starts_with("--pass-options=")) {
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800705 const std::string options = option.substr(strlen("--pass-options=")).data();
706 pass_manager_options.SetOverriddenPassOptions(options);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800707 } else if (option == "--include-patch-information") {
708 include_patch_information = true;
709 } else if (option == "--no-include-patch-information") {
710 include_patch_information = false;
711 } else if (option.starts_with("--verbose-methods=")) {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800712 // TODO: rather than switch off compiler logging, make all VLOG(compiler) messages
713 // conditional on having verbost methods.
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800714 gLogVerbosity.compiler = false;
715 Split(option.substr(strlen("--verbose-methods=")).ToString(), ',', &verbose_methods_);
Andreas Gampedbfe2542014-11-25 22:21:42 -0800716 } else if (option.starts_with("--dump-init-failures=")) {
717 std::string file_name = option.substr(strlen("--dump-init-failures=")).data();
718 init_failure_output_.reset(new std::ofstream(file_name));
719 if (init_failure_output_.get() == nullptr) {
720 LOG(ERROR) << "Failed to allocate ofstream";
721 } else if (init_failure_output_->fail()) {
722 LOG(ERROR) << "Failed to open " << file_name << " for writing the initialization "
723 << "failures.";
724 init_failure_output_.reset();
725 }
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800726 } else if (option.starts_with("--swap-file=")) {
727 swap_file_name_ = option.substr(strlen("--swap-file=")).data();
728 } else if (option.starts_with("--swap-fd=")) {
729 const char* swap_fd_str = option.substr(strlen("--swap-fd=")).data();
730 if (!ParseInt(swap_fd_str, &swap_fd_)) {
731 Usage("Failed to parse --swap-fd argument '%s' as an integer", swap_fd_str);
732 }
733 if (swap_fd_ < 0) {
734 Usage("--swap-fd passed a negative value %d", swap_fd_);
735 }
Andreas Gampe6cf49e52015-03-05 13:08:45 -0800736 } else if (option == "--abort-on-hard-verifier-error") {
737 abort_on_hard_verifier_error = true;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800738 } else {
739 Usage("Unknown argument %s", option.data());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700740 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800741 }
742
Nicolas Geoffray9bb492a2014-11-25 23:42:00 +0000743 if (compiler_kind_ == Compiler::kOptimizing) {
744 // Optimizing only supports PIC mode.
745 compile_pic = true;
746 }
747
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800748 if (oat_filename_.empty() && oat_fd_ == -1) {
749 Usage("Output must be supplied with either --oat-file or --oat-fd");
750 }
751
752 if (!oat_filename_.empty() && oat_fd_ != -1) {
753 Usage("--oat-file should not be used with --oat-fd");
754 }
755
756 if (!oat_symbols.empty() && oat_fd_ != -1) {
757 Usage("--oat-symbols should not be used with --oat-fd");
758 }
759
760 if (!oat_symbols.empty() && is_host_) {
761 Usage("--oat-symbols should not be used with --host");
762 }
763
764 if (oat_fd_ != -1 && !image_filename_.empty()) {
765 Usage("--oat-fd should not be used with --image");
766 }
767
768 if (android_root_.empty()) {
769 const char* android_root_env_var = getenv("ANDROID_ROOT");
770 if (android_root_env_var == nullptr) {
771 Usage("--android-root unspecified and ANDROID_ROOT not set");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700772 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800773 android_root_ += android_root_env_var;
774 }
775
776 image_ = (!image_filename_.empty());
777 if (!image_ && boot_image_filename.empty()) {
778 boot_image_filename += android_root_;
779 boot_image_filename += "/framework/boot.art";
780 }
781 if (!boot_image_filename.empty()) {
782 boot_image_option_ += "-Ximage:";
783 boot_image_option_ += boot_image_filename;
784 }
785
786 if (image_classes_filename_ != nullptr && !image_) {
787 Usage("--image-classes should only be used with --image");
788 }
789
790 if (image_classes_filename_ != nullptr && !boot_image_option_.empty()) {
791 Usage("--image-classes should not be used with --boot-image");
792 }
793
794 if (image_classes_zip_filename_ != nullptr && image_classes_filename_ == nullptr) {
795 Usage("--image-classes-zip should be used with --image-classes");
796 }
797
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800798 if (compiled_classes_filename_ != nullptr && !image_) {
799 Usage("--compiled-classes should only be used with --image");
800 }
801
802 if (compiled_classes_filename_ != nullptr && !boot_image_option_.empty()) {
803 Usage("--compiled-classes should not be used with --boot-image");
804 }
805
806 if (compiled_classes_zip_filename_ != nullptr && compiled_classes_filename_ == nullptr) {
807 Usage("--compiled-classes-zip should be used with --compiled-classes");
808 }
809
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800810 if (dex_filenames_.empty() && zip_fd_ == -1) {
811 Usage("Input must be supplied with either --dex-file or --zip-fd");
812 }
813
814 if (!dex_filenames_.empty() && zip_fd_ != -1) {
815 Usage("--dex-file should not be used with --zip-fd");
816 }
817
818 if (!dex_filenames_.empty() && !zip_location_.empty()) {
819 Usage("--dex-file should not be used with --zip-location");
820 }
821
822 if (dex_locations_.empty()) {
823 for (const char* dex_file_name : dex_filenames_) {
824 dex_locations_.push_back(dex_file_name);
825 }
826 } else if (dex_locations_.size() != dex_filenames_.size()) {
827 Usage("--dex-location arguments do not match --dex-file arguments");
828 }
829
830 if (zip_fd_ != -1 && zip_location_.empty()) {
831 Usage("--zip-location should be supplied with --zip-fd");
832 }
833
834 if (boot_image_option_.empty()) {
835 if (image_base_ == 0) {
836 Usage("Non-zero --base not specified");
837 }
838 }
839
840 oat_stripped_ = oat_filename_;
841 if (!oat_symbols.empty()) {
842 oat_unstripped_ = oat_symbols;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700843 } else {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800844 oat_unstripped_ = oat_filename_;
845 }
846
847 // If no instruction set feature was given, use the default one for the target
848 // instruction set.
849 if (instruction_set_features_.get() == nullptr) {
850 instruction_set_features_.reset(
Ian Rogersd582fa42014-11-05 23:46:43 -0800851 InstructionSetFeatures::FromVariant(instruction_set_, "default", &error_msg));
852 if (instruction_set_features_.get() == nullptr) {
853 Usage("Problem initializing default instruction set features variant: %s",
854 error_msg.c_str());
855 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800856 }
857
858 if (instruction_set_ == kRuntimeISA) {
859 std::unique_ptr<const InstructionSetFeatures> runtime_features(
860 InstructionSetFeatures::FromCppDefines());
861 if (!instruction_set_features_->Equals(runtime_features.get())) {
862 LOG(WARNING) << "Mismatch between dex2oat instruction set features ("
863 << *instruction_set_features_ << ") and those of dex2oat executable ("
864 << *runtime_features <<") for the command line:\n"
865 << CommandLine();
866 }
867 }
868
869 if (compiler_filter_string == nullptr) {
Andreas Gampec5a3ea72015-01-13 16:41:53 -0800870 if (instruction_set_ == kMips &&
871 reinterpret_cast<const MipsInstructionSetFeatures*>(instruction_set_features_.get())->
872 IsR6()) {
873 // For R6, only interpreter mode is working.
874 // TODO: fix compiler for Mips32r6.
875 compiler_filter_string = "interpret-only";
876 } else if (instruction_set_ == kMips64) {
Andreas Gampe57b34292015-01-14 15:45:59 -0800877 // For Mips64, can only compile in interpreter mode.
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800878 // TODO: fix compiler for Mips64.
879 compiler_filter_string = "interpret-only";
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800880 } else {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800881 compiler_filter_string = "speed";
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800882 }
883 }
884 CHECK(compiler_filter_string != nullptr);
885 CompilerOptions::CompilerFilter compiler_filter = CompilerOptions::kDefaultCompilerFilter;
886 if (strcmp(compiler_filter_string, "verify-none") == 0) {
887 compiler_filter = CompilerOptions::kVerifyNone;
888 } else if (strcmp(compiler_filter_string, "interpret-only") == 0) {
889 compiler_filter = CompilerOptions::kInterpretOnly;
890 } else if (strcmp(compiler_filter_string, "space") == 0) {
891 compiler_filter = CompilerOptions::kSpace;
892 } else if (strcmp(compiler_filter_string, "balanced") == 0) {
893 compiler_filter = CompilerOptions::kBalanced;
894 } else if (strcmp(compiler_filter_string, "speed") == 0) {
895 compiler_filter = CompilerOptions::kSpeed;
896 } else if (strcmp(compiler_filter_string, "everything") == 0) {
897 compiler_filter = CompilerOptions::kEverything;
898 } else if (strcmp(compiler_filter_string, "time") == 0) {
899 compiler_filter = CompilerOptions::kTime;
900 } else {
901 Usage("Unknown --compiler-filter value %s", compiler_filter_string);
902 }
903
904 // Checks are all explicit until we know the architecture.
905 bool implicit_null_checks = false;
906 bool implicit_so_checks = false;
907 bool implicit_suspend_checks = false;
908 // Set the compilation target's implicit checks options.
909 switch (instruction_set_) {
910 case kArm:
911 case kThumb2:
912 case kArm64:
913 case kX86:
914 case kX86_64:
915 implicit_null_checks = true;
916 implicit_so_checks = true;
917 break;
918
919 default:
920 // Defaults are correct.
921 break;
922 }
923
Andreas Gampe7b2f09e2015-03-02 14:07:33 -0800924 if (debuggable) {
925 // TODO: Consider adding CFI info and symbols here.
926 }
927
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800928 compiler_options_.reset(new CompilerOptions(compiler_filter,
929 huge_method_threshold,
930 large_method_threshold,
931 small_method_threshold,
932 tiny_method_threshold,
933 num_dex_methods_threshold,
934 generate_gdb_information,
935 include_patch_information,
936 top_k_profile_threshold,
Andreas Gampe7b2f09e2015-03-02 14:07:33 -0800937 debuggable,
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800938 include_debug_symbols,
939 implicit_null_checks,
940 implicit_so_checks,
941 implicit_suspend_checks,
942 compile_pic,
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800943 verbose_methods_.empty() ?
944 nullptr :
Andreas Gampedbfe2542014-11-25 22:21:42 -0800945 &verbose_methods_,
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800946 new PassManagerOptions(pass_manager_options),
Andreas Gampe6cf49e52015-03-05 13:08:45 -0800947 init_failure_output_.get(),
948 abort_on_hard_verifier_error));
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800949
950 // Done with usage checks, enable watchdog if requested
951 if (watch_dog_enabled) {
952 watchdog_.reset(new WatchDog(true));
953 }
954
955 // Fill some values into the key-value store for the oat header.
956 key_value_store_.reset(new SafeMap<std::string, std::string>());
957
958 // Insert some compiler things.
959 {
960 std::ostringstream oss;
961 for (int i = 0; i < argc; ++i) {
962 if (i > 0) {
963 oss << ' ';
964 }
965 oss << argv[i];
966 }
967 key_value_store_->Put(OatHeader::kDex2OatCmdLineKey, oss.str());
968 oss.str(""); // Reset.
969 oss << kRuntimeISA;
970 key_value_store_->Put(OatHeader::kDex2OatHostKey, oss.str());
971 key_value_store_->Put(OatHeader::kPicKey, compile_pic ? "true" : "false");
972 }
973 }
974
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800975 // Check whether the oat output file is writable, and open it for later. Also open a swap file,
976 // if a name is given.
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800977 bool OpenFile() {
978 bool create_file = !oat_unstripped_.empty(); // as opposed to using open file descriptor
979 if (create_file) {
980 oat_file_.reset(OS::CreateEmptyFile(oat_unstripped_.c_str()));
981 if (oat_location_.empty()) {
982 oat_location_ = oat_filename_;
983 }
984 } else {
Andreas Gampe4303ba92014-11-06 01:00:46 -0800985 oat_file_.reset(new File(oat_fd_, oat_location_, true));
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800986 oat_file_->DisableAutoClose();
Andreas Gampe4303ba92014-11-06 01:00:46 -0800987 if (oat_file_->SetLength(0) != 0) {
988 PLOG(WARNING) << "Truncating oat file " << oat_location_ << " failed.";
989 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800990 }
991 if (oat_file_.get() == nullptr) {
992 PLOG(ERROR) << "Failed to create oat file: " << oat_location_;
993 return false;
994 }
995 if (create_file && fchmod(oat_file_->Fd(), 0644) != 0) {
996 PLOG(ERROR) << "Failed to make oat file world readable: " << oat_location_;
Andreas Gampe4303ba92014-11-06 01:00:46 -0800997 oat_file_->Erase();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800998 return false;
999 }
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001000
1001 // Swap file handling.
1002 //
1003 // If the swap fd is not -1, we assume this is the file descriptor of an open but unlinked file
1004 // that we can use for swap.
1005 //
1006 // If the swap fd is -1 and we have a swap-file string, open the given file as a swap file. We
1007 // will immediately unlink to satisfy the swap fd assumption.
1008 if (swap_fd_ == -1 && !swap_file_name_.empty()) {
1009 std::unique_ptr<File> swap_file(OS::CreateEmptyFile(swap_file_name_.c_str()));
1010 if (swap_file.get() == nullptr) {
1011 PLOG(ERROR) << "Failed to create swap file: " << swap_file_name_;
1012 return false;
1013 }
1014 swap_fd_ = swap_file->Fd();
1015 swap_file->MarkUnchecked(); // We don't we to track this, it will be unlinked immediately.
1016 swap_file->DisableAutoClose(); // We'll handle it ourselves, the File object will be
1017 // released immediately.
1018 unlink(swap_file_name_.c_str());
1019 }
1020
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001021 return true;
1022 }
1023
Andreas Gampea650e702014-12-03 14:28:02 -08001024 void EraseOatFile() {
1025 DCHECK(oat_file_.get() != nullptr);
1026 oat_file_->Erase();
1027 oat_file_.reset();
1028 }
1029
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001030 // Set up the environment for compilation. Includes starting the runtime and loading/opening the
1031 // boot class path.
1032 bool Setup() {
1033 TimingLogger::ScopedTiming t("dex2oat Setup", timings_);
1034 RuntimeOptions runtime_options;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001035 art::MemMap::Init(); // For ZipEntry::ExtractToMemMap.
1036 if (boot_image_option_.empty()) {
Richard Uhlerc2752592015-01-02 13:28:22 -08001037 std::string boot_class_path = "-Xbootclasspath:";
1038 boot_class_path += Join(dex_filenames_, ':');
1039 runtime_options.push_back(std::make_pair(boot_class_path, nullptr));
1040 std::string boot_class_path_locations = "-Xbootclasspath-locations:";
1041 boot_class_path_locations += Join(dex_locations_, ':');
1042 runtime_options.push_back(std::make_pair(boot_class_path_locations, nullptr));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001043 } else {
Richard Uhlerc2752592015-01-02 13:28:22 -08001044 runtime_options.push_back(std::make_pair(boot_image_option_, nullptr));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001045 }
1046 for (size_t i = 0; i < runtime_args_.size(); i++) {
1047 runtime_options.push_back(std::make_pair(runtime_args_[i], nullptr));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001048 }
Brian Carlstromd76e0832013-08-29 15:17:42 -07001049
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001050 verification_results_.reset(new VerificationResults(compiler_options_.get()));
1051 callbacks_.reset(new QuickCompilerCallbacks(verification_results_.get(), &method_inliner_map_));
1052 runtime_options.push_back(std::make_pair("compilercallbacks", callbacks_.get()));
1053 runtime_options.push_back(
1054 std::make_pair("imageinstructionset", GetInstructionSetString(instruction_set_)));
1055
Andreas Gampe1d00add2015-02-27 19:35:46 -08001056 // Only allow no boot image for the runtime if we're compiling one. When we compile an app,
1057 // we don't want fallback mode, it will abort as we do not push a boot classpath (it might
1058 // have been stripped in preopting, anyways).
1059 if (!image_) {
1060 runtime_options.push_back(std::make_pair("-Xno-dex-file-fallback", nullptr));
1061 }
1062
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001063 if (!CreateRuntime(runtime_options)) {
1064 return false;
1065 }
1066
1067 // Runtime::Create acquired the mutator_lock_ that is normally given away when we
1068 // Runtime::Start, give it away now so that we don't starve GC.
1069 Thread* self = Thread::Current();
1070 self->TransitionFromRunnableToSuspended(kNative);
1071 // If we're doing the image, override the compiler filter to force full compilation. Must be
1072 // done ahead of WellKnownClasses::Init that causes verification. Note: doesn't force
1073 // compilation of class initializers.
1074 // Whilst we're in native take the opportunity to initialize well known classes.
1075 WellKnownClasses::Init(self->GetJniEnv());
1076
1077 // If --image-classes was specified, calculate the full list of classes to include in the image
1078 if (image_classes_filename_ != nullptr) {
1079 std::string error_msg;
1080 if (image_classes_zip_filename_ != nullptr) {
1081 image_classes_.reset(ReadImageClassesFromZip(image_classes_zip_filename_,
1082 image_classes_filename_,
1083 &error_msg));
1084 } else {
1085 image_classes_.reset(ReadImageClassesFromFile(image_classes_filename_));
1086 }
1087 if (image_classes_.get() == nullptr) {
1088 LOG(ERROR) << "Failed to create list of image classes from '" << image_classes_filename_ <<
1089 "': " << error_msg;
1090 return false;
1091 }
1092 } else if (image_) {
1093 image_classes_.reset(new std::set<std::string>);
1094 }
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001095 // If --compiled-classes was specified, calculate the full list of classes to compile in the
1096 // image.
1097 if (compiled_classes_filename_ != nullptr) {
1098 std::string error_msg;
1099 if (compiled_classes_zip_filename_ != nullptr) {
1100 compiled_classes_.reset(ReadImageClassesFromZip(compiled_classes_zip_filename_,
1101 compiled_classes_filename_,
1102 &error_msg));
1103 } else {
1104 compiled_classes_.reset(ReadImageClassesFromFile(compiled_classes_filename_));
1105 }
1106 if (compiled_classes_.get() == nullptr) {
1107 LOG(ERROR) << "Failed to create list of compiled classes from '"
1108 << compiled_classes_filename_ << "': " << error_msg;
1109 return false;
1110 }
1111 } else if (image_) {
1112 compiled_classes_.reset(nullptr); // By default compile everything.
1113 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001114
1115 if (boot_image_option_.empty()) {
1116 dex_files_ = Runtime::Current()->GetClassLinker()->GetBootClassPath();
1117 } else {
1118 if (dex_filenames_.empty()) {
1119 ATRACE_BEGIN("Opening zip archive from file descriptor");
1120 std::string error_msg;
1121 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(zip_fd_,
1122 zip_location_.c_str(),
1123 &error_msg));
1124 if (zip_archive.get() == nullptr) {
1125 LOG(ERROR) << "Failed to open zip from file descriptor for '" << zip_location_ << "': "
1126 << error_msg;
1127 return false;
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001128 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001129 if (!DexFile::OpenFromZip(*zip_archive.get(), zip_location_, &error_msg, &opened_dex_files_)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001130 LOG(ERROR) << "Failed to open dex from file descriptor for zip file '" << zip_location_
1131 << "': " << error_msg;
1132 return false;
1133 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001134 for (auto& dex_file : opened_dex_files_) {
1135 dex_files_.push_back(dex_file.get());
1136 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001137 ATRACE_END();
1138 } else {
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001139 size_t failure_count = OpenDexFiles(dex_filenames_, dex_locations_, &opened_dex_files_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001140 if (failure_count > 0) {
1141 LOG(ERROR) << "Failed to open some dex files: " << failure_count;
1142 return false;
1143 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001144 for (auto& dex_file : opened_dex_files_) {
1145 dex_files_.push_back(dex_file.get());
1146 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001147 }
1148
1149 constexpr bool kSaveDexInput = false;
1150 if (kSaveDexInput) {
1151 for (size_t i = 0; i < dex_files_.size(); ++i) {
1152 const DexFile* dex_file = dex_files_[i];
Brian Carlstrom95b033b2014-12-03 22:29:37 -08001153 std::string tmp_file_name(StringPrintf("/data/local/tmp/dex2oat.%d.%zd.dex",
1154 getpid(), i));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001155 std::unique_ptr<File> tmp_file(OS::CreateEmptyFile(tmp_file_name.c_str()));
1156 if (tmp_file.get() == nullptr) {
1157 PLOG(ERROR) << "Failed to open file " << tmp_file_name
1158 << ". Try: adb shell chmod 777 /data/local/tmp";
1159 continue;
1160 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001161 // This is just dumping files for debugging. Ignore errors, and leave remnants.
1162 UNUSED(tmp_file->WriteFully(dex_file->Begin(), dex_file->Size()));
1163 UNUSED(tmp_file->Flush());
1164 UNUSED(tmp_file->Close());
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001165 LOG(INFO) << "Wrote input to " << tmp_file_name;
1166 }
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001167 }
1168 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001169 // Ensure opened dex files are writable for dex-to-dex transformations.
1170 for (const auto& dex_file : dex_files_) {
1171 if (!dex_file->EnableWrite()) {
1172 PLOG(ERROR) << "Failed to make .dex file writeable '" << dex_file->GetLocation() << "'\n";
Andreas Gampe7ba64962014-10-23 11:37:40 -07001173 }
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001174 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001175
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001176 // If we use a swap file, ensure we are above the threshold to make it necessary.
1177 if (swap_fd_ != -1) {
1178 if (!UseSwap(image_, dex_files_)) {
1179 close(swap_fd_);
1180 swap_fd_ = -1;
1181 LOG(INFO) << "Decided to run without swap.";
1182 } else {
1183 LOG(INFO) << "Accepted running with swap.";
1184 }
1185 }
1186 // Note that dex2oat won't close the swap_fd_. The compiler driver's swap space will do that.
1187
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001188 /*
1189 * If we're not in interpret-only or verify-none mode, go ahead and compile small applications.
1190 * Don't bother to check if we're doing the image.
1191 */
Brian Carlstrom95b033b2014-12-03 22:29:37 -08001192 if (!image_ &&
1193 compiler_options_->IsCompilationEnabled() &&
1194 compiler_kind_ == Compiler::kQuick) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001195 size_t num_methods = 0;
1196 for (size_t i = 0; i != dex_files_.size(); ++i) {
1197 const DexFile* dex_file = dex_files_[i];
1198 CHECK(dex_file != nullptr);
1199 num_methods += dex_file->NumMethodIds();
1200 }
1201 if (num_methods <= compiler_options_->GetNumDexMethodsThreshold()) {
1202 compiler_options_->SetCompilerFilter(CompilerOptions::kSpeed);
1203 VLOG(compiler) << "Below method threshold, compiling anyways";
1204 }
1205 }
1206
1207 return true;
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001208 }
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001209
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001210 // Create and invoke the compiler driver. This will compile all the dex files.
1211 void Compile() {
1212 TimingLogger::ScopedTiming t("dex2oat Compile", timings_);
1213 compiler_phases_timings_.reset(new CumulativeLogger("compilation times"));
Vladimir Markof4da6752014-08-01 19:04:18 +01001214
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001215 // Handle and ClassLoader creation needs to come after Runtime::Create
1216 jobject class_loader = nullptr;
1217 Thread* self = Thread::Current();
1218 if (!boot_image_option_.empty()) {
1219 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001220 OpenClassPathFiles(runtime_->GetClassPathString(), dex_files_, &class_path_files_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001221 ScopedObjectAccess soa(self);
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001222 std::vector<const DexFile*> class_path_files(dex_files_);
1223 for (auto& class_path_file : class_path_files_) {
1224 class_path_files.push_back(class_path_file.get());
1225 }
1226
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001227 for (size_t i = 0; i < class_path_files.size(); i++) {
1228 class_linker->RegisterDexFile(*class_path_files[i]);
1229 }
1230 soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader);
1231 ScopedLocalRef<jobject> class_loader_local(soa.Env(),
1232 soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader));
1233 class_loader = soa.Env()->NewGlobalRef(class_loader_local.get());
1234 Runtime::Current()->SetCompileTimeClassPath(class_loader, class_path_files);
1235 }
1236
1237 driver_.reset(new CompilerDriver(compiler_options_.get(),
1238 verification_results_.get(),
1239 &method_inliner_map_,
1240 compiler_kind_,
1241 instruction_set_,
1242 instruction_set_features_.get(),
1243 image_,
1244 image_classes_.release(),
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001245 compiled_classes_.release(),
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001246 thread_count_,
1247 dump_stats_,
1248 dump_passes_,
David Brazdil866c0312015-01-13 21:21:31 +00001249 dump_cfg_file_name_,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001250 compiler_phases_timings_.get(),
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001251 swap_fd_,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001252 profile_file_));
1253
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001254 driver_->CompileAll(class_loader, dex_files_, timings_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001255 }
1256
Brian Carlstrom7940e442013-07-12 13:46:57 -07001257 // Notes on the interleaving of creating the image and oat file to
1258 // ensure the references between the two are correct.
1259 //
1260 // Currently we have a memory layout that looks something like this:
1261 //
1262 // +--------------+
1263 // | image |
1264 // +--------------+
1265 // | boot oat |
1266 // +--------------+
1267 // | alloc spaces |
1268 // +--------------+
1269 //
Brian Carlstrom45602482013-07-21 22:07:55 -07001270 // There are several constraints on the loading of the image and boot.oat.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001271 //
1272 // 1. The image is expected to be loaded at an absolute address and
1273 // contains Objects with absolute pointers within the image.
1274 //
1275 // 2. There are absolute pointers from Methods in the image to their
1276 // code in the oat.
1277 //
1278 // 3. There are absolute pointers from the code in the oat to Methods
1279 // in the image.
1280 //
1281 // 4. There are absolute pointers from code in the oat to other code
1282 // in the oat.
1283 //
1284 // To get this all correct, we go through several steps.
1285 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001286 // 1. We prepare offsets for all data in the oat file and calculate
1287 // the oat data size and code size. During this stage, we also set
1288 // oat code offsets in methods for use by the image writer.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001289 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001290 // 2. We prepare offsets for the objects in the image and calculate
1291 // the image size.
1292 //
1293 // 3. We create the oat file. Originally this was just our own proprietary
1294 // file but now it is contained within an ELF dynamic object (aka an .so
1295 // file). Since we know the image size and oat data size and code size we
1296 // can prepare the ELF headers and we then know the ELF memory segment
1297 // layout and we can now resolve all references. The compiler provides
1298 // LinkerPatch information in each CompiledMethod and we resolve these,
1299 // using the layout information and image object locations provided by
1300 // image writer, as we're writing the method code.
1301 //
1302 // 4. We create the image file. It needs to know where the oat file
Brian Carlstrom7940e442013-07-12 13:46:57 -07001303 // will be loaded after itself. Originally when oat file was simply
1304 // memory mapped so we could predict where its contents were based
1305 // on the file size. Now that it is an ELF file, we need to inspect
1306 // the ELF file to understand the in memory segment layout including
Vladimir Markof4da6752014-08-01 19:04:18 +01001307 // where the oat header is located within.
1308 // TODO: We could just remember this information from step 3.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001309 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001310 // 5. We fixup the ELF program headers so that dlopen will try to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001311 // load the .so at the desired location at runtime by offsetting the
1312 // Elf32_Phdr.p_vaddr values by the desired base address.
Vladimir Markof4da6752014-08-01 19:04:18 +01001313 // TODO: Do this in step 3. We already know the layout there.
1314 //
1315 // Steps 1.-3. are done by the CreateOatFile() above, steps 4.-5.
1316 // are done by the CreateImageFile() below.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001317
1318
1319 // Write out the generated code part. Calls the OatWriter and ElfBuilder. Also prepares the
1320 // ImageWriter, if necessary.
Andreas Gampe10e477d2014-11-19 12:57:42 -08001321 // Note: Flushing (and closing) the file is the caller's responsibility, except for the failure
1322 // case (when the file will be explicitly erased).
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001323 bool CreateOatFile() {
1324 CHECK(key_value_store_.get() != nullptr);
1325
1326 TimingLogger::ScopedTiming t("dex2oat Oat", timings_);
1327
1328 std::unique_ptr<OatWriter> oat_writer;
1329 {
1330 TimingLogger::ScopedTiming t2("dex2oat OatWriter", timings_);
1331 std::string image_file_location;
1332 uint32_t image_file_location_oat_checksum = 0;
1333 uintptr_t image_file_location_oat_data_begin = 0;
1334 int32_t image_patch_delta = 0;
1335 if (image_) {
1336 PrepareImageWriter(image_base_);
1337 } else {
1338 TimingLogger::ScopedTiming t3("Loading image checksum", timings_);
1339 gc::space::ImageSpace* image_space = Runtime::Current()->GetHeap()->GetImageSpace();
1340 image_file_location_oat_checksum = image_space->GetImageHeader().GetOatChecksum();
1341 image_file_location_oat_data_begin =
1342 reinterpret_cast<uintptr_t>(image_space->GetImageHeader().GetOatDataBegin());
1343 image_file_location = image_space->GetImageFilename();
1344 image_patch_delta = image_space->GetImageHeader().GetPatchDelta();
1345 }
1346
1347 if (!image_file_location.empty()) {
1348 key_value_store_->Put(OatHeader::kImageLocationKey, image_file_location);
1349 }
1350
1351 oat_writer.reset(new OatWriter(dex_files_, image_file_location_oat_checksum,
1352 image_file_location_oat_data_begin,
1353 image_patch_delta,
1354 driver_.get(),
1355 image_writer_.get(),
1356 timings_,
1357 key_value_store_.get()));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001358 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001359
1360 if (image_) {
1361 // The OatWriter constructor has already updated offsets in methods and we need to
1362 // prepare method offsets in the image address space for direct method patching.
1363 TimingLogger::ScopedTiming t2("dex2oat Prepare image address space", timings_);
1364 if (!image_writer_->PrepareImageAddressSpace()) {
1365 LOG(ERROR) << "Failed to prepare image address space.";
1366 return false;
1367 }
1368 }
1369
1370 {
1371 TimingLogger::ScopedTiming t2("dex2oat Write ELF", timings_);
1372 if (!driver_->WriteElf(android_root_, is_host_, dex_files_, oat_writer.get(),
1373 oat_file_.get())) {
1374 LOG(ERROR) << "Failed to write ELF file " << oat_file_->GetPath();
1375 return false;
1376 }
1377 }
1378
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001379 VLOG(compiler) << "Oat file written successfully (unstripped): " << oat_location_;
1380 return true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001381 }
1382
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001383 // If we are compiling an image, invoke the image creation routine. Else just skip.
1384 bool HandleImage() {
1385 if (image_) {
1386 TimingLogger::ScopedTiming t("dex2oat ImageWriter", timings_);
1387 if (!CreateImageFile()) {
1388 return false;
1389 }
1390 VLOG(compiler) << "Image written successfully: " << image_filename_;
Brian Carlstrom45602482013-07-21 22:07:55 -07001391 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001392 return true;
1393 }
1394
Andreas Gampe10e477d2014-11-19 12:57:42 -08001395 // Create a copy from unstripped to stripped.
1396 bool CopyUnstrippedToStripped() {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001397 // If we don't want to strip in place, copy from unstripped location to stripped location.
1398 // We need to strip after image creation because FixupElf needs to use .strtab.
1399 if (oat_unstripped_ != oat_stripped_) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08001400 // If the oat file is still open, flush it.
1401 if (oat_file_.get() != nullptr && oat_file_->IsOpened()) {
1402 if (!FlushCloseOatFile()) {
1403 return false;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001404 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001405 }
Andreas Gampe10e477d2014-11-19 12:57:42 -08001406
1407 TimingLogger::ScopedTiming t("dex2oat OatFile copy", timings_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001408 std::unique_ptr<File> in(OS::OpenFileForReading(oat_unstripped_.c_str()));
1409 std::unique_ptr<File> out(OS::CreateEmptyFile(oat_stripped_.c_str()));
1410 size_t buffer_size = 8192;
Dan Albert6fc59ab2014-12-11 14:09:51 -08001411 std::unique_ptr<uint8_t[]> buffer(new uint8_t[buffer_size]);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001412 while (true) {
1413 int bytes_read = TEMP_FAILURE_RETRY(read(in->Fd(), buffer.get(), buffer_size));
1414 if (bytes_read <= 0) {
1415 break;
1416 }
1417 bool write_ok = out->WriteFully(buffer.get(), bytes_read);
1418 CHECK(write_ok);
1419 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08001420 if (out->FlushCloseOrErase() != 0) {
1421 PLOG(ERROR) << "Failed to flush and close copied oat file: " << oat_stripped_;
1422 return false;
Andreas Gampe10e477d2014-11-19 12:57:42 -08001423 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001424 VLOG(compiler) << "Oat file copied successfully (stripped): " << oat_stripped_;
Nicolas Geoffrayea3fa0b2014-02-10 11:59:41 +00001425 }
Andreas Gampe10e477d2014-11-19 12:57:42 -08001426 return true;
1427 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001428
Andreas Gampe10e477d2014-11-19 12:57:42 -08001429 bool FlushOatFile() {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001430 if (oat_file_.get() != nullptr) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08001431 TimingLogger::ScopedTiming t2("dex2oat Flush ELF", timings_);
1432 if (oat_file_->Flush() != 0) {
1433 PLOG(ERROR) << "Failed to flush oat file: " << oat_location_ << " / "
1434 << oat_filename_;
1435 oat_file_->Erase();
1436 return false;
1437 }
1438 }
1439 return true;
1440 }
1441
1442 bool FlushCloseOatFile() {
1443 if (oat_file_.get() != nullptr) {
1444 std::unique_ptr<File> tmp(oat_file_.release());
1445 if (tmp->FlushCloseOrErase() != 0) {
1446 PLOG(ERROR) << "Failed to flush and close oat file: " << oat_location_ << " / "
1447 << oat_filename_;
1448 return false;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001449 }
1450 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001451 return true;
1452 }
1453
1454 void DumpTiming() {
1455 if (dump_timing_ || (dump_slow_timing_ && timings_->GetTotalNs() > MsToNs(1000))) {
1456 LOG(INFO) << Dumpable<TimingLogger>(*timings_);
1457 }
1458 if (dump_passes_) {
1459 LOG(INFO) << Dumpable<CumulativeLogger>(*driver_->GetTimingsLogger());
1460 }
1461 }
1462
1463 CompilerOptions* GetCompilerOptions() const {
1464 return compiler_options_.get();
1465 }
1466
Andreas Gampe10e477d2014-11-19 12:57:42 -08001467 bool IsImage() const {
1468 return image_;
1469 }
1470
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001471 bool IsHost() const {
1472 return is_host_;
1473 }
1474
1475 private:
1476 static size_t OpenDexFiles(const std::vector<const char*>& dex_filenames,
1477 const std::vector<const char*>& dex_locations,
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001478 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
1479 DCHECK(dex_files != nullptr) << "OpenDexFiles out-param is NULL";
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001480 size_t failure_count = 0;
1481 for (size_t i = 0; i < dex_filenames.size(); i++) {
1482 const char* dex_filename = dex_filenames[i];
1483 const char* dex_location = dex_locations[i];
1484 ATRACE_BEGIN(StringPrintf("Opening dex file '%s'", dex_filenames[i]).c_str());
1485 std::string error_msg;
1486 if (!OS::FileExists(dex_filename)) {
1487 LOG(WARNING) << "Skipping non-existent dex file '" << dex_filename << "'";
1488 continue;
1489 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001490 if (!DexFile::Open(dex_filename, dex_location, &error_msg, dex_files)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001491 LOG(WARNING) << "Failed to open .dex from file '" << dex_filename << "': " << error_msg;
1492 ++failure_count;
1493 }
1494 ATRACE_END();
1495 }
1496 return failure_count;
1497 }
1498
1499 // Returns true if dex_files has a dex with the named location.
1500 static bool DexFilesContains(const std::vector<const DexFile*>& dex_files,
1501 const std::string& location) {
1502 for (size_t i = 0; i < dex_files.size(); ++i) {
1503 if (dex_files[i]->GetLocation() == location) {
1504 return true;
1505 }
1506 }
1507 return false;
1508 }
1509
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001510 // Appends to opened_dex_files any elements of class_path that dex_files
1511 // doesn't already contain. This will open those dex files as necessary.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001512 static void OpenClassPathFiles(const std::string& class_path,
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001513 std::vector<const DexFile*> dex_files,
1514 std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
1515 DCHECK(opened_dex_files != nullptr) << "OpenClassPathFiles out-param is NULL";
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001516 std::vector<std::string> parsed;
1517 Split(class_path, ':', &parsed);
1518 // Take Locks::mutator_lock_ so that lock ordering on the ClassLinker::dex_lock_ is maintained.
1519 ScopedObjectAccess soa(Thread::Current());
1520 for (size_t i = 0; i < parsed.size(); ++i) {
1521 if (DexFilesContains(dex_files, parsed[i])) {
1522 continue;
1523 }
1524 std::string error_msg;
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001525 if (!DexFile::Open(parsed[i].c_str(), parsed[i].c_str(), &error_msg, opened_dex_files)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001526 LOG(WARNING) << "Failed to open dex file '" << parsed[i] << "': " << error_msg;
1527 }
1528 }
1529 }
1530
1531 // Create a runtime necessary for compilation.
1532 bool CreateRuntime(const RuntimeOptions& runtime_options)
1533 SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_) {
1534 if (!Runtime::Create(runtime_options, false)) {
1535 LOG(ERROR) << "Failed to create runtime";
1536 return false;
1537 }
1538 Runtime* runtime = Runtime::Current();
1539 runtime->SetInstructionSet(instruction_set_);
1540 for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
1541 Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i);
1542 if (!runtime->HasCalleeSaveMethod(type)) {
1543 runtime->SetCalleeSaveMethod(runtime->CreateCalleeSaveMethod(), type);
1544 }
1545 }
1546 runtime->GetClassLinker()->FixupDexCaches(runtime->GetResolutionMethod());
1547 runtime->GetClassLinker()->RunRootClinits();
1548 runtime_ = runtime;
1549 return true;
1550 }
1551
1552 void PrepareImageWriter(uintptr_t image_base) {
1553 image_writer_.reset(new ImageWriter(*driver_, image_base, compiler_options_->GetCompilePic()));
1554 }
1555
1556 // Let the ImageWriter write the image file. If we do not compile PIC, also fix up the oat file.
1557 bool CreateImageFile()
1558 LOCKS_EXCLUDED(Locks::mutator_lock_) {
1559 CHECK(image_writer_ != nullptr);
1560 if (!image_writer_->Write(image_filename_, oat_unstripped_, oat_location_)) {
1561 LOG(ERROR) << "Failed to create image file " << image_filename_;
1562 return false;
1563 }
1564 uintptr_t oat_data_begin = image_writer_->GetOatDataBegin();
1565
1566 // Destroy ImageWriter before doing FixupElf.
1567 image_writer_.reset();
1568
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001569 // Do not fix up the ELF file if we are --compile-pic
1570 if (!compiler_options_->GetCompilePic()) {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001571 std::unique_ptr<File> oat_file(OS::OpenFileReadWrite(oat_unstripped_.c_str()));
1572 if (oat_file.get() == nullptr) {
1573 PLOG(ERROR) << "Failed to open ELF file: " << oat_unstripped_;
1574 return false;
1575 }
1576
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001577 if (!ElfWriter::Fixup(oat_file.get(), oat_data_begin)) {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001578 oat_file->Erase();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001579 LOG(ERROR) << "Failed to fixup ELF file " << oat_file->GetPath();
1580 return false;
1581 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001582
1583 if (oat_file->FlushCloseOrErase()) {
1584 PLOG(ERROR) << "Failed to flush and close fixed ELF file " << oat_file->GetPath();
1585 return false;
1586 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001587 }
1588
1589 return true;
1590 }
1591
1592 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
1593 static std::set<std::string>* ReadImageClassesFromFile(const char* image_classes_filename) {
1594 std::unique_ptr<std::ifstream> image_classes_file(new std::ifstream(image_classes_filename,
1595 std::ifstream::in));
1596 if (image_classes_file.get() == nullptr) {
1597 LOG(ERROR) << "Failed to open image classes file " << image_classes_filename;
1598 return nullptr;
1599 }
1600 std::unique_ptr<std::set<std::string>> result(ReadImageClasses(*image_classes_file));
1601 image_classes_file->close();
1602 return result.release();
1603 }
1604
1605 static std::set<std::string>* ReadImageClasses(std::istream& image_classes_stream) {
1606 std::unique_ptr<std::set<std::string>> image_classes(new std::set<std::string>);
1607 while (image_classes_stream.good()) {
1608 std::string dot;
1609 std::getline(image_classes_stream, dot);
1610 if (StartsWith(dot, "#") || dot.empty()) {
1611 continue;
1612 }
1613 std::string descriptor(DotToDescriptor(dot.c_str()));
1614 image_classes->insert(descriptor);
1615 }
1616 return image_classes.release();
1617 }
1618
1619 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
1620 static std::set<std::string>* ReadImageClassesFromZip(const char* zip_filename,
1621 const char* image_classes_filename,
1622 std::string* error_msg) {
1623 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::Open(zip_filename, error_msg));
1624 if (zip_archive.get() == nullptr) {
1625 return nullptr;
1626 }
1627 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(image_classes_filename, error_msg));
1628 if (zip_entry.get() == nullptr) {
1629 *error_msg = StringPrintf("Failed to find '%s' within '%s': %s", image_classes_filename,
1630 zip_filename, error_msg->c_str());
1631 return nullptr;
1632 }
1633 std::unique_ptr<MemMap> image_classes_file(zip_entry->ExtractToMemMap(zip_filename,
1634 image_classes_filename,
1635 error_msg));
1636 if (image_classes_file.get() == nullptr) {
1637 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", image_classes_filename,
1638 zip_filename, error_msg->c_str());
1639 return nullptr;
1640 }
1641 const std::string image_classes_string(reinterpret_cast<char*>(image_classes_file->Begin()),
1642 image_classes_file->Size());
1643 std::istringstream image_classes_stream(image_classes_string);
1644 return ReadImageClasses(image_classes_stream);
1645 }
1646
Mathieu Chartier49285c52014-12-02 15:43:48 -08001647 void LogCompletionTime() {
Andreas Gampe1d00add2015-02-27 19:35:46 -08001648 // Note: when creation of a runtime fails, e.g., when trying to compile an app but when there
1649 // is no image, there won't be a Runtime::Current().
Brian Carlstroma11a34c2015-03-06 08:44:45 -08001650 // Note: driver creation can fail when loading an invalid dex file.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001651 LOG(INFO) << "dex2oat took " << PrettyDuration(NanoTime() - start_ns_)
Mathieu Chartierab972ef2014-12-03 17:38:22 -08001652 << " (threads: " << thread_count_ << ") "
Brian Carlstroma11a34c2015-03-06 08:44:45 -08001653 << ((Runtime::Current() != nullptr && driver_.get() != nullptr) ?
Andreas Gampe1d00add2015-02-27 19:35:46 -08001654 driver_->GetMemoryUsageString(kIsDebugBuild || VLOG_IS_ON(compiler)) :
1655 "");
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001656 }
1657
1658 std::unique_ptr<CompilerOptions> compiler_options_;
1659 Compiler::Kind compiler_kind_;
1660
1661 InstructionSet instruction_set_;
1662 std::unique_ptr<const InstructionSetFeatures> instruction_set_features_;
1663
1664 std::unique_ptr<SafeMap<std::string, std::string> > key_value_store_;
1665
1666 std::unique_ptr<VerificationResults> verification_results_;
1667 DexFileToMethodInlinerMap method_inliner_map_;
1668 std::unique_ptr<QuickCompilerCallbacks> callbacks_;
1669
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001670 // Ownership for the class path files.
1671 std::vector<std::unique_ptr<const DexFile>> class_path_files_;
1672
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001673 // Not a unique_ptr as we want to just exit on non-debug builds, not bringing the runtime down
1674 // in an orderly fashion. The destructor takes care of deleting this.
1675 Runtime* runtime_;
1676
1677 size_t thread_count_;
1678 uint64_t start_ns_;
1679 std::unique_ptr<WatchDog> watchdog_;
1680 std::unique_ptr<File> oat_file_;
1681 std::string oat_stripped_;
1682 std::string oat_unstripped_;
1683 std::string oat_location_;
1684 std::string oat_filename_;
1685 int oat_fd_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001686 std::vector<const char*> dex_filenames_;
1687 std::vector<const char*> dex_locations_;
1688 int zip_fd_;
1689 std::string zip_location_;
1690 std::string boot_image_option_;
1691 std::vector<const char*> runtime_args_;
1692 std::string image_filename_;
1693 uintptr_t image_base_;
1694 const char* image_classes_zip_filename_;
1695 const char* image_classes_filename_;
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001696 const char* compiled_classes_zip_filename_;
1697 const char* compiled_classes_filename_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001698 std::unique_ptr<std::set<std::string>> image_classes_;
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001699 std::unique_ptr<std::set<std::string>> compiled_classes_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001700 bool image_;
1701 std::unique_ptr<ImageWriter> image_writer_;
1702 bool is_host_;
1703 std::string android_root_;
1704 std::vector<const DexFile*> dex_files_;
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001705 std::vector<std::unique_ptr<const DexFile>> opened_dex_files_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001706 std::unique_ptr<CompilerDriver> driver_;
1707 std::vector<std::string> verbose_methods_;
1708 bool dump_stats_;
1709 bool dump_passes_;
1710 bool dump_timing_;
1711 bool dump_slow_timing_;
David Brazdil866c0312015-01-13 21:21:31 +00001712 std::string dump_cfg_file_name_;
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001713 std::string swap_file_name_;
1714 int swap_fd_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001715 std::string profile_file_; // Profile file to use
1716 TimingLogger* timings_;
1717 std::unique_ptr<CumulativeLogger> compiler_phases_timings_;
Andreas Gampedbfe2542014-11-25 22:21:42 -08001718 std::unique_ptr<std::ostream> init_failure_output_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001719
1720 DISALLOW_IMPLICIT_CONSTRUCTORS(Dex2Oat);
1721};
1722
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001723const unsigned int WatchDog::kWatchDogTimeoutSeconds;
1724
1725static void b13564922() {
1726#if defined(__linux__) && defined(__arm__)
1727 int major, minor;
1728 struct utsname uts;
1729 if (uname(&uts) != -1 &&
1730 sscanf(uts.release, "%d.%d", &major, &minor) == 2 &&
1731 ((major < 3) || ((major == 3) && (minor < 4)))) {
1732 // Kernels before 3.4 don't handle the ASLR well and we can run out of address
1733 // space (http://b/13564922). Work around the issue by inhibiting further mmap() randomization.
1734 int old_personality = personality(0xffffffff);
1735 if ((old_personality & ADDR_NO_RANDOMIZE) == 0) {
1736 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
1737 if (new_personality == -1) {
1738 LOG(WARNING) << "personality(. | ADDR_NO_RANDOMIZE) failed.";
1739 }
1740 }
1741 }
1742#endif
1743}
1744
Andreas Gampe10e477d2014-11-19 12:57:42 -08001745static int CompileImage(Dex2Oat& dex2oat) {
1746 dex2oat.Compile();
1747
1748 // Create the boot.oat.
1749 if (!dex2oat.CreateOatFile()) {
Andreas Gampea650e702014-12-03 14:28:02 -08001750 dex2oat.EraseOatFile();
Andreas Gampe10e477d2014-11-19 12:57:42 -08001751 return EXIT_FAILURE;
1752 }
1753
1754 // Flush and close the boot.oat. We always expect the output file by name, and it will be
1755 // re-opened from the unstripped name.
1756 if (!dex2oat.FlushCloseOatFile()) {
1757 return EXIT_FAILURE;
1758 }
1759
1760 // Creates the boot.art and patches the boot.oat.
1761 if (!dex2oat.HandleImage()) {
1762 return EXIT_FAILURE;
1763 }
1764
1765 // When given --host, finish early without stripping.
1766 if (dex2oat.IsHost()) {
1767 dex2oat.DumpTiming();
1768 return EXIT_SUCCESS;
1769 }
1770
1771 // Copy unstripped to stripped location, if necessary.
1772 if (!dex2oat.CopyUnstrippedToStripped()) {
1773 return EXIT_FAILURE;
1774 }
1775
Andreas Gampe10e477d2014-11-19 12:57:42 -08001776 // FlushClose again, as stripping might have re-opened the oat file.
1777 if (!dex2oat.FlushCloseOatFile()) {
1778 return EXIT_FAILURE;
1779 }
1780
1781 dex2oat.DumpTiming();
1782 return EXIT_SUCCESS;
1783}
1784
1785static int CompileApp(Dex2Oat& dex2oat) {
1786 dex2oat.Compile();
1787
1788 // Create the app oat.
1789 if (!dex2oat.CreateOatFile()) {
Andreas Gampea650e702014-12-03 14:28:02 -08001790 dex2oat.EraseOatFile();
Andreas Gampe10e477d2014-11-19 12:57:42 -08001791 return EXIT_FAILURE;
1792 }
1793
1794 // Do not close the oat file here. We might haven gotten the output file by file descriptor,
1795 // which we would lose.
1796 if (!dex2oat.FlushOatFile()) {
1797 return EXIT_FAILURE;
1798 }
1799
1800 // When given --host, finish early without stripping.
1801 if (dex2oat.IsHost()) {
1802 if (!dex2oat.FlushCloseOatFile()) {
1803 return EXIT_FAILURE;
1804 }
1805
1806 dex2oat.DumpTiming();
1807 return EXIT_SUCCESS;
1808 }
1809
1810 // Copy unstripped to stripped location, if necessary. This will implicitly flush & close the
1811 // unstripped version. If this is given, we expect to be able to open writable files by name.
1812 if (!dex2oat.CopyUnstrippedToStripped()) {
1813 return EXIT_FAILURE;
1814 }
1815
Andreas Gampe10e477d2014-11-19 12:57:42 -08001816 // Flush and close the file.
1817 if (!dex2oat.FlushCloseOatFile()) {
1818 return EXIT_FAILURE;
1819 }
1820
1821 dex2oat.DumpTiming();
1822 return EXIT_SUCCESS;
1823}
1824
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001825static int dex2oat(int argc, char** argv) {
1826 b13564922();
1827
1828 TimingLogger timings("compiler", false, false);
1829
1830 Dex2Oat dex2oat(&timings);
1831
1832 // Parse arguments. Argument mistakes will lead to exit(EXIT_FAILURE) in UsageError.
1833 dex2oat.ParseArgs(argc, argv);
1834
1835 // Check early that the result of compilation can be written
1836 if (!dex2oat.OpenFile()) {
1837 return EXIT_FAILURE;
1838 }
1839
1840 LOG(INFO) << CommandLine();
1841
1842 if (!dex2oat.Setup()) {
Andreas Gampea650e702014-12-03 14:28:02 -08001843 dex2oat.EraseOatFile();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001844 return EXIT_FAILURE;
1845 }
1846
Andreas Gampe10e477d2014-11-19 12:57:42 -08001847 if (dex2oat.IsImage()) {
1848 return CompileImage(dex2oat);
1849 } else {
1850 return CompileApp(dex2oat);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001851 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001852}
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001853} // namespace art
Brian Carlstrom7940e442013-07-12 13:46:57 -07001854
1855int main(int argc, char** argv) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001856 int result = art::dex2oat(argc, argv);
1857 // Everything was done, do an explicit exit here to avoid running Runtime destructors that take
1858 // time (bug 10645725) unless we're a debug build or running on valgrind. Note: The Dex2Oat class
1859 // should not destruct the runtime in this case.
1860 if (!art::kIsDebugBuild && (RUNNING_ON_VALGRIND == 0)) {
1861 exit(result);
1862 }
1863 return result;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001864}