blob: c080453deaa005ea9a79b95564ce79f7bf3cf9c8 [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;
495
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800496 PassManagerOptions pass_manager_options;
497
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800498 std::string error_msg;
499
500 for (int i = 0; i < argc; i++) {
501 const StringPiece option(argv[i]);
502 const bool log_options = false;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700503 if (log_options) {
504 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
505 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800506 if (option.starts_with("--dex-file=")) {
507 dex_filenames_.push_back(option.substr(strlen("--dex-file=")).data());
508 } else if (option.starts_with("--dex-location=")) {
509 dex_locations_.push_back(option.substr(strlen("--dex-location=")).data());
510 } else if (option.starts_with("--zip-fd=")) {
511 const char* zip_fd_str = option.substr(strlen("--zip-fd=")).data();
512 if (!ParseInt(zip_fd_str, &zip_fd_)) {
513 Usage("Failed to parse --zip-fd argument '%s' as an integer", zip_fd_str);
514 }
515 if (zip_fd_ < 0) {
516 Usage("--zip-fd passed a negative value %d", zip_fd_);
517 }
518 } else if (option.starts_with("--zip-location=")) {
519 zip_location_ = option.substr(strlen("--zip-location=")).data();
520 } else if (option.starts_with("--oat-file=")) {
521 oat_filename_ = option.substr(strlen("--oat-file=")).data();
522 } else if (option.starts_with("--oat-symbols=")) {
523 oat_symbols = option.substr(strlen("--oat-symbols=")).data();
524 } else if (option.starts_with("--oat-fd=")) {
525 const char* oat_fd_str = option.substr(strlen("--oat-fd=")).data();
526 if (!ParseInt(oat_fd_str, &oat_fd_)) {
527 Usage("Failed to parse --oat-fd argument '%s' as an integer", oat_fd_str);
528 }
529 if (oat_fd_ < 0) {
530 Usage("--oat-fd passed a negative value %d", oat_fd_);
531 }
532 } else if (option == "--watch-dog") {
533 watch_dog_enabled = true;
534 } else if (option == "--no-watch-dog") {
535 watch_dog_enabled = false;
536 } else if (option == "--gen-gdb-info") {
537 generate_gdb_information = true;
538 // Debug symbols are needed for gdb information.
539 include_debug_symbols = true;
540 } else if (option == "--no-gen-gdb-info") {
541 generate_gdb_information = false;
542 } else if (option.starts_with("-j")) {
543 const char* thread_count_str = option.substr(strlen("-j")).data();
544 if (!ParseUint(thread_count_str, &thread_count_)) {
545 Usage("Failed to parse -j argument '%s' as an integer", thread_count_str);
546 }
547 } else if (option.starts_with("--oat-location=")) {
548 oat_location_ = option.substr(strlen("--oat-location=")).data();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800549 } else if (option.starts_with("--image=")) {
550 image_filename_ = option.substr(strlen("--image=")).data();
551 } else if (option.starts_with("--image-classes=")) {
552 image_classes_filename_ = option.substr(strlen("--image-classes=")).data();
553 } else if (option.starts_with("--image-classes-zip=")) {
554 image_classes_zip_filename_ = option.substr(strlen("--image-classes-zip=")).data();
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800555 } else if (option.starts_with("--compiled-classes=")) {
556 compiled_classes_filename_ = option.substr(strlen("--compiled-classes=")).data();
557 } else if (option.starts_with("--compiled-classes-zip=")) {
558 compiled_classes_zip_filename_ = option.substr(strlen("--compiled-classes-zip=")).data();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800559 } else if (option.starts_with("--base=")) {
560 const char* image_base_str = option.substr(strlen("--base=")).data();
561 char* end;
562 image_base_ = strtoul(image_base_str, &end, 16);
563 if (end == image_base_str || *end != '\0') {
564 Usage("Failed to parse hexadecimal value for option %s", option.data());
565 }
566 } else if (option.starts_with("--boot-image=")) {
567 boot_image_filename = option.substr(strlen("--boot-image=")).data();
568 } else if (option.starts_with("--android-root=")) {
569 android_root_ = option.substr(strlen("--android-root=")).data();
570 } else if (option.starts_with("--instruction-set=")) {
571 StringPiece instruction_set_str = option.substr(strlen("--instruction-set=")).data();
572 // StringPiece is not necessarily zero-terminated, so need to make a copy and ensure it.
Dan Albert6fc59ab2014-12-11 14:09:51 -0800573 std::unique_ptr<char[]> buf(new char[instruction_set_str.length() + 1]);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800574 strncpy(buf.get(), instruction_set_str.data(), instruction_set_str.length());
575 buf.get()[instruction_set_str.length()] = 0;
576 instruction_set_ = GetInstructionSetFromString(buf.get());
577 // arm actually means thumb2.
578 if (instruction_set_ == InstructionSet::kArm) {
579 instruction_set_ = InstructionSet::kThumb2;
580 }
581 } else if (option.starts_with("--instruction-set-variant=")) {
582 StringPiece str = option.substr(strlen("--instruction-set-variant=")).data();
583 instruction_set_features_.reset(
584 InstructionSetFeatures::FromVariant(instruction_set_, str.as_string(), &error_msg));
585 if (instruction_set_features_.get() == nullptr) {
586 Usage("%s", error_msg.c_str());
587 }
588 } else if (option.starts_with("--instruction-set-features=")) {
589 StringPiece str = option.substr(strlen("--instruction-set-features=")).data();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800590 if (instruction_set_features_.get() == nullptr) {
Ian Rogersd582fa42014-11-05 23:46:43 -0800591 instruction_set_features_.reset(
592 InstructionSetFeatures::FromVariant(instruction_set_, "default", &error_msg));
593 if (instruction_set_features_.get() == nullptr) {
594 Usage("Problem initializing default instruction set features variant: %s",
595 error_msg.c_str());
596 }
597 }
598 instruction_set_features_.reset(
599 instruction_set_features_->AddFeaturesFromString(str.as_string(), &error_msg));
600 if (instruction_set_features_.get() == nullptr) {
601 Usage("Error parsing '%s': %s", option.data(), error_msg.c_str());
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800602 }
603 } else if (option.starts_with("--compiler-backend=")) {
604 StringPiece backend_str = option.substr(strlen("--compiler-backend=")).data();
605 if (backend_str == "Quick") {
606 compiler_kind_ = Compiler::kQuick;
607 } else if (backend_str == "Optimizing") {
608 compiler_kind_ = Compiler::kOptimizing;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800609 } else {
610 Usage("Unknown compiler backend: %s", backend_str.data());
611 }
612 } else if (option.starts_with("--compiler-filter=")) {
613 compiler_filter_string = option.substr(strlen("--compiler-filter=")).data();
614 } else if (option == "--compile-pic") {
615 compile_pic = true;
616 } else if (option.starts_with("--huge-method-max=")) {
617 const char* threshold = option.substr(strlen("--huge-method-max=")).data();
618 if (!ParseInt(threshold, &huge_method_threshold)) {
619 Usage("Failed to parse --huge-method-max '%s' as an integer", threshold);
620 }
621 if (huge_method_threshold < 0) {
622 Usage("--huge-method-max passed a negative value %s", huge_method_threshold);
623 }
624 } else if (option.starts_with("--large-method-max=")) {
625 const char* threshold = option.substr(strlen("--large-method-max=")).data();
626 if (!ParseInt(threshold, &large_method_threshold)) {
627 Usage("Failed to parse --large-method-max '%s' as an integer", threshold);
628 }
629 if (large_method_threshold < 0) {
630 Usage("--large-method-max passed a negative value %s", large_method_threshold);
631 }
632 } else if (option.starts_with("--small-method-max=")) {
633 const char* threshold = option.substr(strlen("--small-method-max=")).data();
634 if (!ParseInt(threshold, &small_method_threshold)) {
635 Usage("Failed to parse --small-method-max '%s' as an integer", threshold);
636 }
637 if (small_method_threshold < 0) {
638 Usage("--small-method-max passed a negative value %s", small_method_threshold);
639 }
640 } else if (option.starts_with("--tiny-method-max=")) {
641 const char* threshold = option.substr(strlen("--tiny-method-max=")).data();
642 if (!ParseInt(threshold, &tiny_method_threshold)) {
643 Usage("Failed to parse --tiny-method-max '%s' as an integer", threshold);
644 }
645 if (tiny_method_threshold < 0) {
646 Usage("--tiny-method-max passed a negative value %s", tiny_method_threshold);
647 }
648 } else if (option.starts_with("--num-dex-methods=")) {
649 const char* threshold = option.substr(strlen("--num-dex-methods=")).data();
650 if (!ParseInt(threshold, &num_dex_methods_threshold)) {
651 Usage("Failed to parse --num-dex-methods '%s' as an integer", threshold);
652 }
653 if (num_dex_methods_threshold < 0) {
654 Usage("--num-dex-methods passed a negative value %s", num_dex_methods_threshold);
655 }
656 } else if (option == "--host") {
657 is_host_ = true;
658 } else if (option == "--runtime-arg") {
659 if (++i >= argc) {
660 Usage("Missing required argument for --runtime-arg");
661 }
662 if (log_options) {
663 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
664 }
665 runtime_args_.push_back(argv[i]);
666 } else if (option == "--dump-timing") {
667 dump_timing_ = true;
668 } else if (option == "--dump-passes") {
669 dump_passes_ = true;
David Brazdil866c0312015-01-13 21:21:31 +0000670 } else if (option.starts_with("--dump-cfg=")) {
671 dump_cfg_file_name_ = option.substr(strlen("--dump-cfg=")).data();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800672 } else if (option == "--dump-stats") {
673 dump_stats_ = true;
674 } else if (option == "--include-debug-symbols" || option == "--no-strip-symbols") {
675 include_debug_symbols = true;
676 } else if (option == "--no-include-debug-symbols" || option == "--strip-symbols") {
677 include_debug_symbols = false;
678 generate_gdb_information = false; // Depends on debug symbols, see above.
Andreas Gampe7b2f09e2015-03-02 14:07:33 -0800679 } else if (option == "--debuggable") {
680 debuggable = true;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800681 } else if (option.starts_with("--profile-file=")) {
682 profile_file_ = option.substr(strlen("--profile-file=")).data();
683 VLOG(compiler) << "dex2oat: profile file is " << profile_file_;
684 } else if (option == "--no-profile-file") {
685 // No profile
686 } else if (option.starts_with("--top-k-profile-threshold=")) {
687 ParseDouble(option.data(), '=', 0.0, 100.0, &top_k_profile_threshold);
688 } else if (option == "--print-pass-names") {
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800689 pass_manager_options.SetPrintPassNames(true);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800690 } else if (option.starts_with("--disable-passes=")) {
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800691 const std::string disable_passes = option.substr(strlen("--disable-passes=")).data();
692 pass_manager_options.SetDisablePassList(disable_passes);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800693 } else if (option.starts_with("--print-passes=")) {
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800694 const std::string print_passes = option.substr(strlen("--print-passes=")).data();
695 pass_manager_options.SetPrintPassList(print_passes);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800696 } else if (option == "--print-all-passes") {
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800697 pass_manager_options.SetPrintAllPasses();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800698 } else if (option.starts_with("--dump-cfg-passes=")) {
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800699 const std::string dump_passes_string = option.substr(strlen("--dump-cfg-passes=")).data();
700 pass_manager_options.SetDumpPassList(dump_passes_string);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800701 } else if (option == "--print-pass-options") {
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800702 pass_manager_options.SetPrintPassOptions(true);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800703 } else if (option.starts_with("--pass-options=")) {
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800704 const std::string options = option.substr(strlen("--pass-options=")).data();
705 pass_manager_options.SetOverriddenPassOptions(options);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800706 } else if (option == "--include-patch-information") {
707 include_patch_information = true;
708 } else if (option == "--no-include-patch-information") {
709 include_patch_information = false;
710 } else if (option.starts_with("--verbose-methods=")) {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800711 // TODO: rather than switch off compiler logging, make all VLOG(compiler) messages
712 // conditional on having verbost methods.
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800713 gLogVerbosity.compiler = false;
714 Split(option.substr(strlen("--verbose-methods=")).ToString(), ',', &verbose_methods_);
Andreas Gampedbfe2542014-11-25 22:21:42 -0800715 } else if (option.starts_with("--dump-init-failures=")) {
716 std::string file_name = option.substr(strlen("--dump-init-failures=")).data();
717 init_failure_output_.reset(new std::ofstream(file_name));
718 if (init_failure_output_.get() == nullptr) {
719 LOG(ERROR) << "Failed to allocate ofstream";
720 } else if (init_failure_output_->fail()) {
721 LOG(ERROR) << "Failed to open " << file_name << " for writing the initialization "
722 << "failures.";
723 init_failure_output_.reset();
724 }
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800725 } else if (option.starts_with("--swap-file=")) {
726 swap_file_name_ = option.substr(strlen("--swap-file=")).data();
727 } else if (option.starts_with("--swap-fd=")) {
728 const char* swap_fd_str = option.substr(strlen("--swap-fd=")).data();
729 if (!ParseInt(swap_fd_str, &swap_fd_)) {
730 Usage("Failed to parse --swap-fd argument '%s' as an integer", swap_fd_str);
731 }
732 if (swap_fd_ < 0) {
733 Usage("--swap-fd passed a negative value %d", swap_fd_);
734 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800735 } else {
736 Usage("Unknown argument %s", option.data());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700737 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800738 }
739
Nicolas Geoffray9bb492a2014-11-25 23:42:00 +0000740 if (compiler_kind_ == Compiler::kOptimizing) {
741 // Optimizing only supports PIC mode.
742 compile_pic = true;
743 }
744
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800745 if (oat_filename_.empty() && oat_fd_ == -1) {
746 Usage("Output must be supplied with either --oat-file or --oat-fd");
747 }
748
749 if (!oat_filename_.empty() && oat_fd_ != -1) {
750 Usage("--oat-file should not be used with --oat-fd");
751 }
752
753 if (!oat_symbols.empty() && oat_fd_ != -1) {
754 Usage("--oat-symbols should not be used with --oat-fd");
755 }
756
757 if (!oat_symbols.empty() && is_host_) {
758 Usage("--oat-symbols should not be used with --host");
759 }
760
761 if (oat_fd_ != -1 && !image_filename_.empty()) {
762 Usage("--oat-fd should not be used with --image");
763 }
764
765 if (android_root_.empty()) {
766 const char* android_root_env_var = getenv("ANDROID_ROOT");
767 if (android_root_env_var == nullptr) {
768 Usage("--android-root unspecified and ANDROID_ROOT not set");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700769 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800770 android_root_ += android_root_env_var;
771 }
772
773 image_ = (!image_filename_.empty());
774 if (!image_ && boot_image_filename.empty()) {
775 boot_image_filename += android_root_;
776 boot_image_filename += "/framework/boot.art";
777 }
778 if (!boot_image_filename.empty()) {
779 boot_image_option_ += "-Ximage:";
780 boot_image_option_ += boot_image_filename;
781 }
782
783 if (image_classes_filename_ != nullptr && !image_) {
784 Usage("--image-classes should only be used with --image");
785 }
786
787 if (image_classes_filename_ != nullptr && !boot_image_option_.empty()) {
788 Usage("--image-classes should not be used with --boot-image");
789 }
790
791 if (image_classes_zip_filename_ != nullptr && image_classes_filename_ == nullptr) {
792 Usage("--image-classes-zip should be used with --image-classes");
793 }
794
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800795 if (compiled_classes_filename_ != nullptr && !image_) {
796 Usage("--compiled-classes should only be used with --image");
797 }
798
799 if (compiled_classes_filename_ != nullptr && !boot_image_option_.empty()) {
800 Usage("--compiled-classes should not be used with --boot-image");
801 }
802
803 if (compiled_classes_zip_filename_ != nullptr && compiled_classes_filename_ == nullptr) {
804 Usage("--compiled-classes-zip should be used with --compiled-classes");
805 }
806
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800807 if (dex_filenames_.empty() && zip_fd_ == -1) {
808 Usage("Input must be supplied with either --dex-file or --zip-fd");
809 }
810
811 if (!dex_filenames_.empty() && zip_fd_ != -1) {
812 Usage("--dex-file should not be used with --zip-fd");
813 }
814
815 if (!dex_filenames_.empty() && !zip_location_.empty()) {
816 Usage("--dex-file should not be used with --zip-location");
817 }
818
819 if (dex_locations_.empty()) {
820 for (const char* dex_file_name : dex_filenames_) {
821 dex_locations_.push_back(dex_file_name);
822 }
823 } else if (dex_locations_.size() != dex_filenames_.size()) {
824 Usage("--dex-location arguments do not match --dex-file arguments");
825 }
826
827 if (zip_fd_ != -1 && zip_location_.empty()) {
828 Usage("--zip-location should be supplied with --zip-fd");
829 }
830
831 if (boot_image_option_.empty()) {
832 if (image_base_ == 0) {
833 Usage("Non-zero --base not specified");
834 }
835 }
836
837 oat_stripped_ = oat_filename_;
838 if (!oat_symbols.empty()) {
839 oat_unstripped_ = oat_symbols;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700840 } else {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800841 oat_unstripped_ = oat_filename_;
842 }
843
844 // If no instruction set feature was given, use the default one for the target
845 // instruction set.
846 if (instruction_set_features_.get() == nullptr) {
847 instruction_set_features_.reset(
Ian Rogersd582fa42014-11-05 23:46:43 -0800848 InstructionSetFeatures::FromVariant(instruction_set_, "default", &error_msg));
849 if (instruction_set_features_.get() == nullptr) {
850 Usage("Problem initializing default instruction set features variant: %s",
851 error_msg.c_str());
852 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800853 }
854
855 if (instruction_set_ == kRuntimeISA) {
856 std::unique_ptr<const InstructionSetFeatures> runtime_features(
857 InstructionSetFeatures::FromCppDefines());
858 if (!instruction_set_features_->Equals(runtime_features.get())) {
859 LOG(WARNING) << "Mismatch between dex2oat instruction set features ("
860 << *instruction_set_features_ << ") and those of dex2oat executable ("
861 << *runtime_features <<") for the command line:\n"
862 << CommandLine();
863 }
864 }
865
866 if (compiler_filter_string == nullptr) {
Andreas Gampec5a3ea72015-01-13 16:41:53 -0800867 if (instruction_set_ == kMips &&
868 reinterpret_cast<const MipsInstructionSetFeatures*>(instruction_set_features_.get())->
869 IsR6()) {
870 // For R6, only interpreter mode is working.
871 // TODO: fix compiler for Mips32r6.
872 compiler_filter_string = "interpret-only";
873 } else if (instruction_set_ == kMips64) {
Andreas Gampe57b34292015-01-14 15:45:59 -0800874 // For Mips64, can only compile in interpreter mode.
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800875 // TODO: fix compiler for Mips64.
876 compiler_filter_string = "interpret-only";
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800877 } else {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800878 compiler_filter_string = "speed";
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800879 }
880 }
881 CHECK(compiler_filter_string != nullptr);
882 CompilerOptions::CompilerFilter compiler_filter = CompilerOptions::kDefaultCompilerFilter;
883 if (strcmp(compiler_filter_string, "verify-none") == 0) {
884 compiler_filter = CompilerOptions::kVerifyNone;
885 } else if (strcmp(compiler_filter_string, "interpret-only") == 0) {
886 compiler_filter = CompilerOptions::kInterpretOnly;
887 } else if (strcmp(compiler_filter_string, "space") == 0) {
888 compiler_filter = CompilerOptions::kSpace;
889 } else if (strcmp(compiler_filter_string, "balanced") == 0) {
890 compiler_filter = CompilerOptions::kBalanced;
891 } else if (strcmp(compiler_filter_string, "speed") == 0) {
892 compiler_filter = CompilerOptions::kSpeed;
893 } else if (strcmp(compiler_filter_string, "everything") == 0) {
894 compiler_filter = CompilerOptions::kEverything;
895 } else if (strcmp(compiler_filter_string, "time") == 0) {
896 compiler_filter = CompilerOptions::kTime;
897 } else {
898 Usage("Unknown --compiler-filter value %s", compiler_filter_string);
899 }
900
901 // Checks are all explicit until we know the architecture.
902 bool implicit_null_checks = false;
903 bool implicit_so_checks = false;
904 bool implicit_suspend_checks = false;
905 // Set the compilation target's implicit checks options.
906 switch (instruction_set_) {
907 case kArm:
908 case kThumb2:
909 case kArm64:
910 case kX86:
911 case kX86_64:
912 implicit_null_checks = true;
913 implicit_so_checks = true;
914 break;
915
916 default:
917 // Defaults are correct.
918 break;
919 }
920
Andreas Gampe7b2f09e2015-03-02 14:07:33 -0800921 if (debuggable) {
922 // TODO: Consider adding CFI info and symbols here.
923 }
924
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800925 compiler_options_.reset(new CompilerOptions(compiler_filter,
926 huge_method_threshold,
927 large_method_threshold,
928 small_method_threshold,
929 tiny_method_threshold,
930 num_dex_methods_threshold,
931 generate_gdb_information,
932 include_patch_information,
933 top_k_profile_threshold,
Andreas Gampe7b2f09e2015-03-02 14:07:33 -0800934 debuggable,
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800935 include_debug_symbols,
936 implicit_null_checks,
937 implicit_so_checks,
938 implicit_suspend_checks,
939 compile_pic,
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800940 verbose_methods_.empty() ?
941 nullptr :
Andreas Gampedbfe2542014-11-25 22:21:42 -0800942 &verbose_methods_,
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800943 new PassManagerOptions(pass_manager_options),
Andreas Gampedbfe2542014-11-25 22:21:42 -0800944 init_failure_output_.get()));
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800945
946 // Done with usage checks, enable watchdog if requested
947 if (watch_dog_enabled) {
948 watchdog_.reset(new WatchDog(true));
949 }
950
951 // Fill some values into the key-value store for the oat header.
952 key_value_store_.reset(new SafeMap<std::string, std::string>());
953
954 // Insert some compiler things.
955 {
956 std::ostringstream oss;
957 for (int i = 0; i < argc; ++i) {
958 if (i > 0) {
959 oss << ' ';
960 }
961 oss << argv[i];
962 }
963 key_value_store_->Put(OatHeader::kDex2OatCmdLineKey, oss.str());
964 oss.str(""); // Reset.
965 oss << kRuntimeISA;
966 key_value_store_->Put(OatHeader::kDex2OatHostKey, oss.str());
967 key_value_store_->Put(OatHeader::kPicKey, compile_pic ? "true" : "false");
968 }
969 }
970
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800971 // Check whether the oat output file is writable, and open it for later. Also open a swap file,
972 // if a name is given.
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800973 bool OpenFile() {
974 bool create_file = !oat_unstripped_.empty(); // as opposed to using open file descriptor
975 if (create_file) {
976 oat_file_.reset(OS::CreateEmptyFile(oat_unstripped_.c_str()));
977 if (oat_location_.empty()) {
978 oat_location_ = oat_filename_;
979 }
980 } else {
Andreas Gampe4303ba92014-11-06 01:00:46 -0800981 oat_file_.reset(new File(oat_fd_, oat_location_, true));
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800982 oat_file_->DisableAutoClose();
Andreas Gampe4303ba92014-11-06 01:00:46 -0800983 if (oat_file_->SetLength(0) != 0) {
984 PLOG(WARNING) << "Truncating oat file " << oat_location_ << " failed.";
985 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800986 }
987 if (oat_file_.get() == nullptr) {
988 PLOG(ERROR) << "Failed to create oat file: " << oat_location_;
989 return false;
990 }
991 if (create_file && fchmod(oat_file_->Fd(), 0644) != 0) {
992 PLOG(ERROR) << "Failed to make oat file world readable: " << oat_location_;
Andreas Gampe4303ba92014-11-06 01:00:46 -0800993 oat_file_->Erase();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800994 return false;
995 }
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800996
997 // Swap file handling.
998 //
999 // If the swap fd is not -1, we assume this is the file descriptor of an open but unlinked file
1000 // that we can use for swap.
1001 //
1002 // If the swap fd is -1 and we have a swap-file string, open the given file as a swap file. We
1003 // will immediately unlink to satisfy the swap fd assumption.
1004 if (swap_fd_ == -1 && !swap_file_name_.empty()) {
1005 std::unique_ptr<File> swap_file(OS::CreateEmptyFile(swap_file_name_.c_str()));
1006 if (swap_file.get() == nullptr) {
1007 PLOG(ERROR) << "Failed to create swap file: " << swap_file_name_;
1008 return false;
1009 }
1010 swap_fd_ = swap_file->Fd();
1011 swap_file->MarkUnchecked(); // We don't we to track this, it will be unlinked immediately.
1012 swap_file->DisableAutoClose(); // We'll handle it ourselves, the File object will be
1013 // released immediately.
1014 unlink(swap_file_name_.c_str());
1015 }
1016
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001017 return true;
1018 }
1019
Andreas Gampea650e702014-12-03 14:28:02 -08001020 void EraseOatFile() {
1021 DCHECK(oat_file_.get() != nullptr);
1022 oat_file_->Erase();
1023 oat_file_.reset();
1024 }
1025
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001026 // Set up the environment for compilation. Includes starting the runtime and loading/opening the
1027 // boot class path.
1028 bool Setup() {
1029 TimingLogger::ScopedTiming t("dex2oat Setup", timings_);
1030 RuntimeOptions runtime_options;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001031 art::MemMap::Init(); // For ZipEntry::ExtractToMemMap.
1032 if (boot_image_option_.empty()) {
Richard Uhlerc2752592015-01-02 13:28:22 -08001033 std::string boot_class_path = "-Xbootclasspath:";
1034 boot_class_path += Join(dex_filenames_, ':');
1035 runtime_options.push_back(std::make_pair(boot_class_path, nullptr));
1036 std::string boot_class_path_locations = "-Xbootclasspath-locations:";
1037 boot_class_path_locations += Join(dex_locations_, ':');
1038 runtime_options.push_back(std::make_pair(boot_class_path_locations, nullptr));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001039 } else {
Richard Uhlerc2752592015-01-02 13:28:22 -08001040 runtime_options.push_back(std::make_pair(boot_image_option_, nullptr));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001041 }
1042 for (size_t i = 0; i < runtime_args_.size(); i++) {
1043 runtime_options.push_back(std::make_pair(runtime_args_[i], nullptr));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001044 }
Brian Carlstromd76e0832013-08-29 15:17:42 -07001045
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001046 verification_results_.reset(new VerificationResults(compiler_options_.get()));
1047 callbacks_.reset(new QuickCompilerCallbacks(verification_results_.get(), &method_inliner_map_));
1048 runtime_options.push_back(std::make_pair("compilercallbacks", callbacks_.get()));
1049 runtime_options.push_back(
1050 std::make_pair("imageinstructionset", GetInstructionSetString(instruction_set_)));
1051
Andreas Gampe1d00add2015-02-27 19:35:46 -08001052 // Only allow no boot image for the runtime if we're compiling one. When we compile an app,
1053 // we don't want fallback mode, it will abort as we do not push a boot classpath (it might
1054 // have been stripped in preopting, anyways).
1055 if (!image_) {
1056 runtime_options.push_back(std::make_pair("-Xno-dex-file-fallback", nullptr));
1057 }
1058
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001059 if (!CreateRuntime(runtime_options)) {
1060 return false;
1061 }
1062
1063 // Runtime::Create acquired the mutator_lock_ that is normally given away when we
1064 // Runtime::Start, give it away now so that we don't starve GC.
1065 Thread* self = Thread::Current();
1066 self->TransitionFromRunnableToSuspended(kNative);
1067 // If we're doing the image, override the compiler filter to force full compilation. Must be
1068 // done ahead of WellKnownClasses::Init that causes verification. Note: doesn't force
1069 // compilation of class initializers.
1070 // Whilst we're in native take the opportunity to initialize well known classes.
1071 WellKnownClasses::Init(self->GetJniEnv());
1072
1073 // If --image-classes was specified, calculate the full list of classes to include in the image
1074 if (image_classes_filename_ != nullptr) {
1075 std::string error_msg;
1076 if (image_classes_zip_filename_ != nullptr) {
1077 image_classes_.reset(ReadImageClassesFromZip(image_classes_zip_filename_,
1078 image_classes_filename_,
1079 &error_msg));
1080 } else {
1081 image_classes_.reset(ReadImageClassesFromFile(image_classes_filename_));
1082 }
1083 if (image_classes_.get() == nullptr) {
1084 LOG(ERROR) << "Failed to create list of image classes from '" << image_classes_filename_ <<
1085 "': " << error_msg;
1086 return false;
1087 }
1088 } else if (image_) {
1089 image_classes_.reset(new std::set<std::string>);
1090 }
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001091 // If --compiled-classes was specified, calculate the full list of classes to compile in the
1092 // image.
1093 if (compiled_classes_filename_ != nullptr) {
1094 std::string error_msg;
1095 if (compiled_classes_zip_filename_ != nullptr) {
1096 compiled_classes_.reset(ReadImageClassesFromZip(compiled_classes_zip_filename_,
1097 compiled_classes_filename_,
1098 &error_msg));
1099 } else {
1100 compiled_classes_.reset(ReadImageClassesFromFile(compiled_classes_filename_));
1101 }
1102 if (compiled_classes_.get() == nullptr) {
1103 LOG(ERROR) << "Failed to create list of compiled classes from '"
1104 << compiled_classes_filename_ << "': " << error_msg;
1105 return false;
1106 }
1107 } else if (image_) {
1108 compiled_classes_.reset(nullptr); // By default compile everything.
1109 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001110
1111 if (boot_image_option_.empty()) {
1112 dex_files_ = Runtime::Current()->GetClassLinker()->GetBootClassPath();
1113 } else {
1114 if (dex_filenames_.empty()) {
1115 ATRACE_BEGIN("Opening zip archive from file descriptor");
1116 std::string error_msg;
1117 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(zip_fd_,
1118 zip_location_.c_str(),
1119 &error_msg));
1120 if (zip_archive.get() == nullptr) {
1121 LOG(ERROR) << "Failed to open zip from file descriptor for '" << zip_location_ << "': "
1122 << error_msg;
1123 return false;
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001124 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001125 if (!DexFile::OpenFromZip(*zip_archive.get(), zip_location_, &error_msg, &opened_dex_files_)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001126 LOG(ERROR) << "Failed to open dex from file descriptor for zip file '" << zip_location_
1127 << "': " << error_msg;
1128 return false;
1129 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001130 for (auto& dex_file : opened_dex_files_) {
1131 dex_files_.push_back(dex_file.get());
1132 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001133 ATRACE_END();
1134 } else {
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001135 size_t failure_count = OpenDexFiles(dex_filenames_, dex_locations_, &opened_dex_files_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001136 if (failure_count > 0) {
1137 LOG(ERROR) << "Failed to open some dex files: " << failure_count;
1138 return false;
1139 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001140 for (auto& dex_file : opened_dex_files_) {
1141 dex_files_.push_back(dex_file.get());
1142 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001143 }
1144
1145 constexpr bool kSaveDexInput = false;
1146 if (kSaveDexInput) {
1147 for (size_t i = 0; i < dex_files_.size(); ++i) {
1148 const DexFile* dex_file = dex_files_[i];
Brian Carlstrom95b033b2014-12-03 22:29:37 -08001149 std::string tmp_file_name(StringPrintf("/data/local/tmp/dex2oat.%d.%zd.dex",
1150 getpid(), i));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001151 std::unique_ptr<File> tmp_file(OS::CreateEmptyFile(tmp_file_name.c_str()));
1152 if (tmp_file.get() == nullptr) {
1153 PLOG(ERROR) << "Failed to open file " << tmp_file_name
1154 << ". Try: adb shell chmod 777 /data/local/tmp";
1155 continue;
1156 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001157 // This is just dumping files for debugging. Ignore errors, and leave remnants.
1158 UNUSED(tmp_file->WriteFully(dex_file->Begin(), dex_file->Size()));
1159 UNUSED(tmp_file->Flush());
1160 UNUSED(tmp_file->Close());
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001161 LOG(INFO) << "Wrote input to " << tmp_file_name;
1162 }
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001163 }
1164 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001165 // Ensure opened dex files are writable for dex-to-dex transformations.
1166 for (const auto& dex_file : dex_files_) {
1167 if (!dex_file->EnableWrite()) {
1168 PLOG(ERROR) << "Failed to make .dex file writeable '" << dex_file->GetLocation() << "'\n";
Andreas Gampe7ba64962014-10-23 11:37:40 -07001169 }
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001170 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001171
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001172 // If we use a swap file, ensure we are above the threshold to make it necessary.
1173 if (swap_fd_ != -1) {
1174 if (!UseSwap(image_, dex_files_)) {
1175 close(swap_fd_);
1176 swap_fd_ = -1;
1177 LOG(INFO) << "Decided to run without swap.";
1178 } else {
1179 LOG(INFO) << "Accepted running with swap.";
1180 }
1181 }
1182 // Note that dex2oat won't close the swap_fd_. The compiler driver's swap space will do that.
1183
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001184 /*
1185 * If we're not in interpret-only or verify-none mode, go ahead and compile small applications.
1186 * Don't bother to check if we're doing the image.
1187 */
Brian Carlstrom95b033b2014-12-03 22:29:37 -08001188 if (!image_ &&
1189 compiler_options_->IsCompilationEnabled() &&
1190 compiler_kind_ == Compiler::kQuick) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001191 size_t num_methods = 0;
1192 for (size_t i = 0; i != dex_files_.size(); ++i) {
1193 const DexFile* dex_file = dex_files_[i];
1194 CHECK(dex_file != nullptr);
1195 num_methods += dex_file->NumMethodIds();
1196 }
1197 if (num_methods <= compiler_options_->GetNumDexMethodsThreshold()) {
1198 compiler_options_->SetCompilerFilter(CompilerOptions::kSpeed);
1199 VLOG(compiler) << "Below method threshold, compiling anyways";
1200 }
1201 }
1202
1203 return true;
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001204 }
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001205
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001206 // Create and invoke the compiler driver. This will compile all the dex files.
1207 void Compile() {
1208 TimingLogger::ScopedTiming t("dex2oat Compile", timings_);
1209 compiler_phases_timings_.reset(new CumulativeLogger("compilation times"));
Vladimir Markof4da6752014-08-01 19:04:18 +01001210
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001211 // Handle and ClassLoader creation needs to come after Runtime::Create
1212 jobject class_loader = nullptr;
1213 Thread* self = Thread::Current();
1214 if (!boot_image_option_.empty()) {
1215 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001216 OpenClassPathFiles(runtime_->GetClassPathString(), dex_files_, &class_path_files_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001217 ScopedObjectAccess soa(self);
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001218 std::vector<const DexFile*> class_path_files(dex_files_);
1219 for (auto& class_path_file : class_path_files_) {
1220 class_path_files.push_back(class_path_file.get());
1221 }
1222
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001223 for (size_t i = 0; i < class_path_files.size(); i++) {
1224 class_linker->RegisterDexFile(*class_path_files[i]);
1225 }
1226 soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader);
1227 ScopedLocalRef<jobject> class_loader_local(soa.Env(),
1228 soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader));
1229 class_loader = soa.Env()->NewGlobalRef(class_loader_local.get());
1230 Runtime::Current()->SetCompileTimeClassPath(class_loader, class_path_files);
1231 }
1232
1233 driver_.reset(new CompilerDriver(compiler_options_.get(),
1234 verification_results_.get(),
1235 &method_inliner_map_,
1236 compiler_kind_,
1237 instruction_set_,
1238 instruction_set_features_.get(),
1239 image_,
1240 image_classes_.release(),
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001241 compiled_classes_.release(),
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001242 thread_count_,
1243 dump_stats_,
1244 dump_passes_,
David Brazdil866c0312015-01-13 21:21:31 +00001245 dump_cfg_file_name_,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001246 compiler_phases_timings_.get(),
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001247 swap_fd_,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001248 profile_file_));
1249
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001250 driver_->CompileAll(class_loader, dex_files_, timings_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001251 }
1252
Brian Carlstrom7940e442013-07-12 13:46:57 -07001253 // Notes on the interleaving of creating the image and oat file to
1254 // ensure the references between the two are correct.
1255 //
1256 // Currently we have a memory layout that looks something like this:
1257 //
1258 // +--------------+
1259 // | image |
1260 // +--------------+
1261 // | boot oat |
1262 // +--------------+
1263 // | alloc spaces |
1264 // +--------------+
1265 //
Brian Carlstrom45602482013-07-21 22:07:55 -07001266 // There are several constraints on the loading of the image and boot.oat.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001267 //
1268 // 1. The image is expected to be loaded at an absolute address and
1269 // contains Objects with absolute pointers within the image.
1270 //
1271 // 2. There are absolute pointers from Methods in the image to their
1272 // code in the oat.
1273 //
1274 // 3. There are absolute pointers from the code in the oat to Methods
1275 // in the image.
1276 //
1277 // 4. There are absolute pointers from code in the oat to other code
1278 // in the oat.
1279 //
1280 // To get this all correct, we go through several steps.
1281 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001282 // 1. We prepare offsets for all data in the oat file and calculate
1283 // the oat data size and code size. During this stage, we also set
1284 // oat code offsets in methods for use by the image writer.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001285 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001286 // 2. We prepare offsets for the objects in the image and calculate
1287 // the image size.
1288 //
1289 // 3. We create the oat file. Originally this was just our own proprietary
1290 // file but now it is contained within an ELF dynamic object (aka an .so
1291 // file). Since we know the image size and oat data size and code size we
1292 // can prepare the ELF headers and we then know the ELF memory segment
1293 // layout and we can now resolve all references. The compiler provides
1294 // LinkerPatch information in each CompiledMethod and we resolve these,
1295 // using the layout information and image object locations provided by
1296 // image writer, as we're writing the method code.
1297 //
1298 // 4. We create the image file. It needs to know where the oat file
Brian Carlstrom7940e442013-07-12 13:46:57 -07001299 // will be loaded after itself. Originally when oat file was simply
1300 // memory mapped so we could predict where its contents were based
1301 // on the file size. Now that it is an ELF file, we need to inspect
1302 // the ELF file to understand the in memory segment layout including
Vladimir Markof4da6752014-08-01 19:04:18 +01001303 // where the oat header is located within.
1304 // TODO: We could just remember this information from step 3.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001305 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001306 // 5. We fixup the ELF program headers so that dlopen will try to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001307 // load the .so at the desired location at runtime by offsetting the
1308 // Elf32_Phdr.p_vaddr values by the desired base address.
Vladimir Markof4da6752014-08-01 19:04:18 +01001309 // TODO: Do this in step 3. We already know the layout there.
1310 //
1311 // Steps 1.-3. are done by the CreateOatFile() above, steps 4.-5.
1312 // are done by the CreateImageFile() below.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001313
1314
1315 // Write out the generated code part. Calls the OatWriter and ElfBuilder. Also prepares the
1316 // ImageWriter, if necessary.
Andreas Gampe10e477d2014-11-19 12:57:42 -08001317 // Note: Flushing (and closing) the file is the caller's responsibility, except for the failure
1318 // case (when the file will be explicitly erased).
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001319 bool CreateOatFile() {
1320 CHECK(key_value_store_.get() != nullptr);
1321
1322 TimingLogger::ScopedTiming t("dex2oat Oat", timings_);
1323
1324 std::unique_ptr<OatWriter> oat_writer;
1325 {
1326 TimingLogger::ScopedTiming t2("dex2oat OatWriter", timings_);
1327 std::string image_file_location;
1328 uint32_t image_file_location_oat_checksum = 0;
1329 uintptr_t image_file_location_oat_data_begin = 0;
1330 int32_t image_patch_delta = 0;
1331 if (image_) {
1332 PrepareImageWriter(image_base_);
1333 } else {
1334 TimingLogger::ScopedTiming t3("Loading image checksum", timings_);
1335 gc::space::ImageSpace* image_space = Runtime::Current()->GetHeap()->GetImageSpace();
1336 image_file_location_oat_checksum = image_space->GetImageHeader().GetOatChecksum();
1337 image_file_location_oat_data_begin =
1338 reinterpret_cast<uintptr_t>(image_space->GetImageHeader().GetOatDataBegin());
1339 image_file_location = image_space->GetImageFilename();
1340 image_patch_delta = image_space->GetImageHeader().GetPatchDelta();
1341 }
1342
1343 if (!image_file_location.empty()) {
1344 key_value_store_->Put(OatHeader::kImageLocationKey, image_file_location);
1345 }
1346
1347 oat_writer.reset(new OatWriter(dex_files_, image_file_location_oat_checksum,
1348 image_file_location_oat_data_begin,
1349 image_patch_delta,
1350 driver_.get(),
1351 image_writer_.get(),
1352 timings_,
1353 key_value_store_.get()));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001354 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001355
1356 if (image_) {
1357 // The OatWriter constructor has already updated offsets in methods and we need to
1358 // prepare method offsets in the image address space for direct method patching.
1359 TimingLogger::ScopedTiming t2("dex2oat Prepare image address space", timings_);
1360 if (!image_writer_->PrepareImageAddressSpace()) {
1361 LOG(ERROR) << "Failed to prepare image address space.";
1362 return false;
1363 }
1364 }
1365
1366 {
1367 TimingLogger::ScopedTiming t2("dex2oat Write ELF", timings_);
1368 if (!driver_->WriteElf(android_root_, is_host_, dex_files_, oat_writer.get(),
1369 oat_file_.get())) {
1370 LOG(ERROR) << "Failed to write ELF file " << oat_file_->GetPath();
1371 return false;
1372 }
1373 }
1374
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001375 VLOG(compiler) << "Oat file written successfully (unstripped): " << oat_location_;
1376 return true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001377 }
1378
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001379 // If we are compiling an image, invoke the image creation routine. Else just skip.
1380 bool HandleImage() {
1381 if (image_) {
1382 TimingLogger::ScopedTiming t("dex2oat ImageWriter", timings_);
1383 if (!CreateImageFile()) {
1384 return false;
1385 }
1386 VLOG(compiler) << "Image written successfully: " << image_filename_;
Brian Carlstrom45602482013-07-21 22:07:55 -07001387 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001388 return true;
1389 }
1390
Andreas Gampe10e477d2014-11-19 12:57:42 -08001391 // Create a copy from unstripped to stripped.
1392 bool CopyUnstrippedToStripped() {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001393 // If we don't want to strip in place, copy from unstripped location to stripped location.
1394 // We need to strip after image creation because FixupElf needs to use .strtab.
1395 if (oat_unstripped_ != oat_stripped_) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08001396 // If the oat file is still open, flush it.
1397 if (oat_file_.get() != nullptr && oat_file_->IsOpened()) {
1398 if (!FlushCloseOatFile()) {
1399 return false;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001400 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001401 }
Andreas Gampe10e477d2014-11-19 12:57:42 -08001402
1403 TimingLogger::ScopedTiming t("dex2oat OatFile copy", timings_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001404 std::unique_ptr<File> in(OS::OpenFileForReading(oat_unstripped_.c_str()));
1405 std::unique_ptr<File> out(OS::CreateEmptyFile(oat_stripped_.c_str()));
1406 size_t buffer_size = 8192;
Dan Albert6fc59ab2014-12-11 14:09:51 -08001407 std::unique_ptr<uint8_t[]> buffer(new uint8_t[buffer_size]);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001408 while (true) {
1409 int bytes_read = TEMP_FAILURE_RETRY(read(in->Fd(), buffer.get(), buffer_size));
1410 if (bytes_read <= 0) {
1411 break;
1412 }
1413 bool write_ok = out->WriteFully(buffer.get(), bytes_read);
1414 CHECK(write_ok);
1415 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08001416 if (out->FlushCloseOrErase() != 0) {
1417 PLOG(ERROR) << "Failed to flush and close copied oat file: " << oat_stripped_;
1418 return false;
Andreas Gampe10e477d2014-11-19 12:57:42 -08001419 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001420 VLOG(compiler) << "Oat file copied successfully (stripped): " << oat_stripped_;
Nicolas Geoffrayea3fa0b2014-02-10 11:59:41 +00001421 }
Andreas Gampe10e477d2014-11-19 12:57:42 -08001422 return true;
1423 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001424
Andreas Gampe10e477d2014-11-19 12:57:42 -08001425 bool FlushOatFile() {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001426 if (oat_file_.get() != nullptr) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08001427 TimingLogger::ScopedTiming t2("dex2oat Flush ELF", timings_);
1428 if (oat_file_->Flush() != 0) {
1429 PLOG(ERROR) << "Failed to flush oat file: " << oat_location_ << " / "
1430 << oat_filename_;
1431 oat_file_->Erase();
1432 return false;
1433 }
1434 }
1435 return true;
1436 }
1437
1438 bool FlushCloseOatFile() {
1439 if (oat_file_.get() != nullptr) {
1440 std::unique_ptr<File> tmp(oat_file_.release());
1441 if (tmp->FlushCloseOrErase() != 0) {
1442 PLOG(ERROR) << "Failed to flush and close oat file: " << oat_location_ << " / "
1443 << oat_filename_;
1444 return false;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001445 }
1446 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001447 return true;
1448 }
1449
1450 void DumpTiming() {
1451 if (dump_timing_ || (dump_slow_timing_ && timings_->GetTotalNs() > MsToNs(1000))) {
1452 LOG(INFO) << Dumpable<TimingLogger>(*timings_);
1453 }
1454 if (dump_passes_) {
1455 LOG(INFO) << Dumpable<CumulativeLogger>(*driver_->GetTimingsLogger());
1456 }
1457 }
1458
1459 CompilerOptions* GetCompilerOptions() const {
1460 return compiler_options_.get();
1461 }
1462
Andreas Gampe10e477d2014-11-19 12:57:42 -08001463 bool IsImage() const {
1464 return image_;
1465 }
1466
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001467 bool IsHost() const {
1468 return is_host_;
1469 }
1470
1471 private:
1472 static size_t OpenDexFiles(const std::vector<const char*>& dex_filenames,
1473 const std::vector<const char*>& dex_locations,
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001474 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
1475 DCHECK(dex_files != nullptr) << "OpenDexFiles out-param is NULL";
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001476 size_t failure_count = 0;
1477 for (size_t i = 0; i < dex_filenames.size(); i++) {
1478 const char* dex_filename = dex_filenames[i];
1479 const char* dex_location = dex_locations[i];
1480 ATRACE_BEGIN(StringPrintf("Opening dex file '%s'", dex_filenames[i]).c_str());
1481 std::string error_msg;
1482 if (!OS::FileExists(dex_filename)) {
1483 LOG(WARNING) << "Skipping non-existent dex file '" << dex_filename << "'";
1484 continue;
1485 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001486 if (!DexFile::Open(dex_filename, dex_location, &error_msg, dex_files)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001487 LOG(WARNING) << "Failed to open .dex from file '" << dex_filename << "': " << error_msg;
1488 ++failure_count;
1489 }
1490 ATRACE_END();
1491 }
1492 return failure_count;
1493 }
1494
1495 // Returns true if dex_files has a dex with the named location.
1496 static bool DexFilesContains(const std::vector<const DexFile*>& dex_files,
1497 const std::string& location) {
1498 for (size_t i = 0; i < dex_files.size(); ++i) {
1499 if (dex_files[i]->GetLocation() == location) {
1500 return true;
1501 }
1502 }
1503 return false;
1504 }
1505
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001506 // Appends to opened_dex_files any elements of class_path that dex_files
1507 // doesn't already contain. This will open those dex files as necessary.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001508 static void OpenClassPathFiles(const std::string& class_path,
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001509 std::vector<const DexFile*> dex_files,
1510 std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
1511 DCHECK(opened_dex_files != nullptr) << "OpenClassPathFiles out-param is NULL";
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001512 std::vector<std::string> parsed;
1513 Split(class_path, ':', &parsed);
1514 // Take Locks::mutator_lock_ so that lock ordering on the ClassLinker::dex_lock_ is maintained.
1515 ScopedObjectAccess soa(Thread::Current());
1516 for (size_t i = 0; i < parsed.size(); ++i) {
1517 if (DexFilesContains(dex_files, parsed[i])) {
1518 continue;
1519 }
1520 std::string error_msg;
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001521 if (!DexFile::Open(parsed[i].c_str(), parsed[i].c_str(), &error_msg, opened_dex_files)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001522 LOG(WARNING) << "Failed to open dex file '" << parsed[i] << "': " << error_msg;
1523 }
1524 }
1525 }
1526
1527 // Create a runtime necessary for compilation.
1528 bool CreateRuntime(const RuntimeOptions& runtime_options)
1529 SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_) {
1530 if (!Runtime::Create(runtime_options, false)) {
1531 LOG(ERROR) << "Failed to create runtime";
1532 return false;
1533 }
1534 Runtime* runtime = Runtime::Current();
1535 runtime->SetInstructionSet(instruction_set_);
1536 for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
1537 Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i);
1538 if (!runtime->HasCalleeSaveMethod(type)) {
1539 runtime->SetCalleeSaveMethod(runtime->CreateCalleeSaveMethod(), type);
1540 }
1541 }
1542 runtime->GetClassLinker()->FixupDexCaches(runtime->GetResolutionMethod());
1543 runtime->GetClassLinker()->RunRootClinits();
1544 runtime_ = runtime;
1545 return true;
1546 }
1547
1548 void PrepareImageWriter(uintptr_t image_base) {
1549 image_writer_.reset(new ImageWriter(*driver_, image_base, compiler_options_->GetCompilePic()));
1550 }
1551
1552 // Let the ImageWriter write the image file. If we do not compile PIC, also fix up the oat file.
1553 bool CreateImageFile()
1554 LOCKS_EXCLUDED(Locks::mutator_lock_) {
1555 CHECK(image_writer_ != nullptr);
1556 if (!image_writer_->Write(image_filename_, oat_unstripped_, oat_location_)) {
1557 LOG(ERROR) << "Failed to create image file " << image_filename_;
1558 return false;
1559 }
1560 uintptr_t oat_data_begin = image_writer_->GetOatDataBegin();
1561
1562 // Destroy ImageWriter before doing FixupElf.
1563 image_writer_.reset();
1564
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001565 // Do not fix up the ELF file if we are --compile-pic
1566 if (!compiler_options_->GetCompilePic()) {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001567 std::unique_ptr<File> oat_file(OS::OpenFileReadWrite(oat_unstripped_.c_str()));
1568 if (oat_file.get() == nullptr) {
1569 PLOG(ERROR) << "Failed to open ELF file: " << oat_unstripped_;
1570 return false;
1571 }
1572
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001573 if (!ElfWriter::Fixup(oat_file.get(), oat_data_begin)) {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001574 oat_file->Erase();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001575 LOG(ERROR) << "Failed to fixup ELF file " << oat_file->GetPath();
1576 return false;
1577 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001578
1579 if (oat_file->FlushCloseOrErase()) {
1580 PLOG(ERROR) << "Failed to flush and close fixed ELF file " << oat_file->GetPath();
1581 return false;
1582 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001583 }
1584
1585 return true;
1586 }
1587
1588 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
1589 static std::set<std::string>* ReadImageClassesFromFile(const char* image_classes_filename) {
1590 std::unique_ptr<std::ifstream> image_classes_file(new std::ifstream(image_classes_filename,
1591 std::ifstream::in));
1592 if (image_classes_file.get() == nullptr) {
1593 LOG(ERROR) << "Failed to open image classes file " << image_classes_filename;
1594 return nullptr;
1595 }
1596 std::unique_ptr<std::set<std::string>> result(ReadImageClasses(*image_classes_file));
1597 image_classes_file->close();
1598 return result.release();
1599 }
1600
1601 static std::set<std::string>* ReadImageClasses(std::istream& image_classes_stream) {
1602 std::unique_ptr<std::set<std::string>> image_classes(new std::set<std::string>);
1603 while (image_classes_stream.good()) {
1604 std::string dot;
1605 std::getline(image_classes_stream, dot);
1606 if (StartsWith(dot, "#") || dot.empty()) {
1607 continue;
1608 }
1609 std::string descriptor(DotToDescriptor(dot.c_str()));
1610 image_classes->insert(descriptor);
1611 }
1612 return image_classes.release();
1613 }
1614
1615 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
1616 static std::set<std::string>* ReadImageClassesFromZip(const char* zip_filename,
1617 const char* image_classes_filename,
1618 std::string* error_msg) {
1619 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::Open(zip_filename, error_msg));
1620 if (zip_archive.get() == nullptr) {
1621 return nullptr;
1622 }
1623 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(image_classes_filename, error_msg));
1624 if (zip_entry.get() == nullptr) {
1625 *error_msg = StringPrintf("Failed to find '%s' within '%s': %s", image_classes_filename,
1626 zip_filename, error_msg->c_str());
1627 return nullptr;
1628 }
1629 std::unique_ptr<MemMap> image_classes_file(zip_entry->ExtractToMemMap(zip_filename,
1630 image_classes_filename,
1631 error_msg));
1632 if (image_classes_file.get() == nullptr) {
1633 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", image_classes_filename,
1634 zip_filename, error_msg->c_str());
1635 return nullptr;
1636 }
1637 const std::string image_classes_string(reinterpret_cast<char*>(image_classes_file->Begin()),
1638 image_classes_file->Size());
1639 std::istringstream image_classes_stream(image_classes_string);
1640 return ReadImageClasses(image_classes_stream);
1641 }
1642
Mathieu Chartier49285c52014-12-02 15:43:48 -08001643 void LogCompletionTime() {
Andreas Gampe1d00add2015-02-27 19:35:46 -08001644 // Note: when creation of a runtime fails, e.g., when trying to compile an app but when there
1645 // is no image, there won't be a Runtime::Current().
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001646 LOG(INFO) << "dex2oat took " << PrettyDuration(NanoTime() - start_ns_)
Mathieu Chartierab972ef2014-12-03 17:38:22 -08001647 << " (threads: " << thread_count_ << ") "
Andreas Gampe1d00add2015-02-27 19:35:46 -08001648 << ((Runtime::Current() != nullptr) ?
1649 driver_->GetMemoryUsageString(kIsDebugBuild || VLOG_IS_ON(compiler)) :
1650 "");
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001651 }
1652
1653 std::unique_ptr<CompilerOptions> compiler_options_;
1654 Compiler::Kind compiler_kind_;
1655
1656 InstructionSet instruction_set_;
1657 std::unique_ptr<const InstructionSetFeatures> instruction_set_features_;
1658
1659 std::unique_ptr<SafeMap<std::string, std::string> > key_value_store_;
1660
1661 std::unique_ptr<VerificationResults> verification_results_;
1662 DexFileToMethodInlinerMap method_inliner_map_;
1663 std::unique_ptr<QuickCompilerCallbacks> callbacks_;
1664
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001665 // Ownership for the class path files.
1666 std::vector<std::unique_ptr<const DexFile>> class_path_files_;
1667
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001668 // Not a unique_ptr as we want to just exit on non-debug builds, not bringing the runtime down
1669 // in an orderly fashion. The destructor takes care of deleting this.
1670 Runtime* runtime_;
1671
1672 size_t thread_count_;
1673 uint64_t start_ns_;
1674 std::unique_ptr<WatchDog> watchdog_;
1675 std::unique_ptr<File> oat_file_;
1676 std::string oat_stripped_;
1677 std::string oat_unstripped_;
1678 std::string oat_location_;
1679 std::string oat_filename_;
1680 int oat_fd_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001681 std::vector<const char*> dex_filenames_;
1682 std::vector<const char*> dex_locations_;
1683 int zip_fd_;
1684 std::string zip_location_;
1685 std::string boot_image_option_;
1686 std::vector<const char*> runtime_args_;
1687 std::string image_filename_;
1688 uintptr_t image_base_;
1689 const char* image_classes_zip_filename_;
1690 const char* image_classes_filename_;
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001691 const char* compiled_classes_zip_filename_;
1692 const char* compiled_classes_filename_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001693 std::unique_ptr<std::set<std::string>> image_classes_;
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001694 std::unique_ptr<std::set<std::string>> compiled_classes_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001695 bool image_;
1696 std::unique_ptr<ImageWriter> image_writer_;
1697 bool is_host_;
1698 std::string android_root_;
1699 std::vector<const DexFile*> dex_files_;
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001700 std::vector<std::unique_ptr<const DexFile>> opened_dex_files_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001701 std::unique_ptr<CompilerDriver> driver_;
1702 std::vector<std::string> verbose_methods_;
1703 bool dump_stats_;
1704 bool dump_passes_;
1705 bool dump_timing_;
1706 bool dump_slow_timing_;
David Brazdil866c0312015-01-13 21:21:31 +00001707 std::string dump_cfg_file_name_;
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001708 std::string swap_file_name_;
1709 int swap_fd_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001710 std::string profile_file_; // Profile file to use
1711 TimingLogger* timings_;
1712 std::unique_ptr<CumulativeLogger> compiler_phases_timings_;
Andreas Gampedbfe2542014-11-25 22:21:42 -08001713 std::unique_ptr<std::ostream> init_failure_output_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001714
1715 DISALLOW_IMPLICIT_CONSTRUCTORS(Dex2Oat);
1716};
1717
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001718const unsigned int WatchDog::kWatchDogTimeoutSeconds;
1719
1720static void b13564922() {
1721#if defined(__linux__) && defined(__arm__)
1722 int major, minor;
1723 struct utsname uts;
1724 if (uname(&uts) != -1 &&
1725 sscanf(uts.release, "%d.%d", &major, &minor) == 2 &&
1726 ((major < 3) || ((major == 3) && (minor < 4)))) {
1727 // Kernels before 3.4 don't handle the ASLR well and we can run out of address
1728 // space (http://b/13564922). Work around the issue by inhibiting further mmap() randomization.
1729 int old_personality = personality(0xffffffff);
1730 if ((old_personality & ADDR_NO_RANDOMIZE) == 0) {
1731 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
1732 if (new_personality == -1) {
1733 LOG(WARNING) << "personality(. | ADDR_NO_RANDOMIZE) failed.";
1734 }
1735 }
1736 }
1737#endif
1738}
1739
Andreas Gampe10e477d2014-11-19 12:57:42 -08001740static int CompileImage(Dex2Oat& dex2oat) {
1741 dex2oat.Compile();
1742
1743 // Create the boot.oat.
1744 if (!dex2oat.CreateOatFile()) {
Andreas Gampea650e702014-12-03 14:28:02 -08001745 dex2oat.EraseOatFile();
Andreas Gampe10e477d2014-11-19 12:57:42 -08001746 return EXIT_FAILURE;
1747 }
1748
1749 // Flush and close the boot.oat. We always expect the output file by name, and it will be
1750 // re-opened from the unstripped name.
1751 if (!dex2oat.FlushCloseOatFile()) {
1752 return EXIT_FAILURE;
1753 }
1754
1755 // Creates the boot.art and patches the boot.oat.
1756 if (!dex2oat.HandleImage()) {
1757 return EXIT_FAILURE;
1758 }
1759
1760 // When given --host, finish early without stripping.
1761 if (dex2oat.IsHost()) {
1762 dex2oat.DumpTiming();
1763 return EXIT_SUCCESS;
1764 }
1765
1766 // Copy unstripped to stripped location, if necessary.
1767 if (!dex2oat.CopyUnstrippedToStripped()) {
1768 return EXIT_FAILURE;
1769 }
1770
Andreas Gampe10e477d2014-11-19 12:57:42 -08001771 // FlushClose again, as stripping might have re-opened the oat file.
1772 if (!dex2oat.FlushCloseOatFile()) {
1773 return EXIT_FAILURE;
1774 }
1775
1776 dex2oat.DumpTiming();
1777 return EXIT_SUCCESS;
1778}
1779
1780static int CompileApp(Dex2Oat& dex2oat) {
1781 dex2oat.Compile();
1782
1783 // Create the app oat.
1784 if (!dex2oat.CreateOatFile()) {
Andreas Gampea650e702014-12-03 14:28:02 -08001785 dex2oat.EraseOatFile();
Andreas Gampe10e477d2014-11-19 12:57:42 -08001786 return EXIT_FAILURE;
1787 }
1788
1789 // Do not close the oat file here. We might haven gotten the output file by file descriptor,
1790 // which we would lose.
1791 if (!dex2oat.FlushOatFile()) {
1792 return EXIT_FAILURE;
1793 }
1794
1795 // When given --host, finish early without stripping.
1796 if (dex2oat.IsHost()) {
1797 if (!dex2oat.FlushCloseOatFile()) {
1798 return EXIT_FAILURE;
1799 }
1800
1801 dex2oat.DumpTiming();
1802 return EXIT_SUCCESS;
1803 }
1804
1805 // Copy unstripped to stripped location, if necessary. This will implicitly flush & close the
1806 // unstripped version. If this is given, we expect to be able to open writable files by name.
1807 if (!dex2oat.CopyUnstrippedToStripped()) {
1808 return EXIT_FAILURE;
1809 }
1810
Andreas Gampe10e477d2014-11-19 12:57:42 -08001811 // Flush and close the file.
1812 if (!dex2oat.FlushCloseOatFile()) {
1813 return EXIT_FAILURE;
1814 }
1815
1816 dex2oat.DumpTiming();
1817 return EXIT_SUCCESS;
1818}
1819
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001820static int dex2oat(int argc, char** argv) {
1821 b13564922();
1822
1823 TimingLogger timings("compiler", false, false);
1824
1825 Dex2Oat dex2oat(&timings);
1826
1827 // Parse arguments. Argument mistakes will lead to exit(EXIT_FAILURE) in UsageError.
1828 dex2oat.ParseArgs(argc, argv);
1829
1830 // Check early that the result of compilation can be written
1831 if (!dex2oat.OpenFile()) {
1832 return EXIT_FAILURE;
1833 }
1834
1835 LOG(INFO) << CommandLine();
1836
1837 if (!dex2oat.Setup()) {
Andreas Gampea650e702014-12-03 14:28:02 -08001838 dex2oat.EraseOatFile();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001839 return EXIT_FAILURE;
1840 }
1841
Andreas Gampe10e477d2014-11-19 12:57:42 -08001842 if (dex2oat.IsImage()) {
1843 return CompileImage(dex2oat);
1844 } else {
1845 return CompileApp(dex2oat);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001846 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001847}
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001848} // namespace art
Brian Carlstrom7940e442013-07-12 13:46:57 -07001849
1850int main(int argc, char** argv) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001851 int result = art::dex2oat(argc, argv);
1852 // Everything was done, do an explicit exit here to avoid running Runtime destructors that take
1853 // time (bug 10645725) unless we're a debug build or running on valgrind. Note: The Dex2Oat class
1854 // should not destruct the runtime in this case.
1855 if (!art::kIsDebugBuild && (RUNNING_ON_VALGRIND == 0)) {
1856 exit(result);
1857 }
1858 return result;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001859}