blob: 96919dcc08f09c7980d23077f2e92e089513a3bc [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";
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800876 } else {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800877 compiler_filter_string = "speed";
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800878 }
879 }
Maja Gagic6ea651f2015-02-24 16:55:04 +0100880
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800881 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 Gampe6cf49e52015-03-05 13:08:45 -0800944 init_failure_output_.get(),
945 abort_on_hard_verifier_error));
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800946
947 // Done with usage checks, enable watchdog if requested
948 if (watch_dog_enabled) {
949 watchdog_.reset(new WatchDog(true));
950 }
951
952 // Fill some values into the key-value store for the oat header.
953 key_value_store_.reset(new SafeMap<std::string, std::string>());
954
955 // Insert some compiler things.
956 {
957 std::ostringstream oss;
958 for (int i = 0; i < argc; ++i) {
959 if (i > 0) {
960 oss << ' ';
961 }
962 oss << argv[i];
963 }
964 key_value_store_->Put(OatHeader::kDex2OatCmdLineKey, oss.str());
965 oss.str(""); // Reset.
966 oss << kRuntimeISA;
967 key_value_store_->Put(OatHeader::kDex2OatHostKey, oss.str());
968 key_value_store_->Put(OatHeader::kPicKey, compile_pic ? "true" : "false");
969 }
970 }
971
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800972 // Check whether the oat output file is writable, and open it for later. Also open a swap file,
973 // if a name is given.
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800974 bool OpenFile() {
975 bool create_file = !oat_unstripped_.empty(); // as opposed to using open file descriptor
976 if (create_file) {
977 oat_file_.reset(OS::CreateEmptyFile(oat_unstripped_.c_str()));
978 if (oat_location_.empty()) {
979 oat_location_ = oat_filename_;
980 }
981 } else {
Andreas Gampe4303ba92014-11-06 01:00:46 -0800982 oat_file_.reset(new File(oat_fd_, oat_location_, true));
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800983 oat_file_->DisableAutoClose();
Andreas Gampe4303ba92014-11-06 01:00:46 -0800984 if (oat_file_->SetLength(0) != 0) {
985 PLOG(WARNING) << "Truncating oat file " << oat_location_ << " failed.";
986 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800987 }
988 if (oat_file_.get() == nullptr) {
989 PLOG(ERROR) << "Failed to create oat file: " << oat_location_;
990 return false;
991 }
992 if (create_file && fchmod(oat_file_->Fd(), 0644) != 0) {
993 PLOG(ERROR) << "Failed to make oat file world readable: " << oat_location_;
Andreas Gampe4303ba92014-11-06 01:00:46 -0800994 oat_file_->Erase();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800995 return false;
996 }
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800997
998 // Swap file handling.
999 //
1000 // If the swap fd is not -1, we assume this is the file descriptor of an open but unlinked file
1001 // that we can use for swap.
1002 //
1003 // If the swap fd is -1 and we have a swap-file string, open the given file as a swap file. We
1004 // will immediately unlink to satisfy the swap fd assumption.
1005 if (swap_fd_ == -1 && !swap_file_name_.empty()) {
1006 std::unique_ptr<File> swap_file(OS::CreateEmptyFile(swap_file_name_.c_str()));
1007 if (swap_file.get() == nullptr) {
1008 PLOG(ERROR) << "Failed to create swap file: " << swap_file_name_;
1009 return false;
1010 }
1011 swap_fd_ = swap_file->Fd();
1012 swap_file->MarkUnchecked(); // We don't we to track this, it will be unlinked immediately.
1013 swap_file->DisableAutoClose(); // We'll handle it ourselves, the File object will be
1014 // released immediately.
1015 unlink(swap_file_name_.c_str());
1016 }
1017
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001018 return true;
1019 }
1020
Andreas Gampea650e702014-12-03 14:28:02 -08001021 void EraseOatFile() {
1022 DCHECK(oat_file_.get() != nullptr);
1023 oat_file_->Erase();
1024 oat_file_.reset();
1025 }
1026
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001027 // Set up the environment for compilation. Includes starting the runtime and loading/opening the
1028 // boot class path.
1029 bool Setup() {
1030 TimingLogger::ScopedTiming t("dex2oat Setup", timings_);
1031 RuntimeOptions runtime_options;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001032 art::MemMap::Init(); // For ZipEntry::ExtractToMemMap.
1033 if (boot_image_option_.empty()) {
Richard Uhlerc2752592015-01-02 13:28:22 -08001034 std::string boot_class_path = "-Xbootclasspath:";
1035 boot_class_path += Join(dex_filenames_, ':');
1036 runtime_options.push_back(std::make_pair(boot_class_path, nullptr));
1037 std::string boot_class_path_locations = "-Xbootclasspath-locations:";
1038 boot_class_path_locations += Join(dex_locations_, ':');
1039 runtime_options.push_back(std::make_pair(boot_class_path_locations, nullptr));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001040 } else {
Richard Uhlerc2752592015-01-02 13:28:22 -08001041 runtime_options.push_back(std::make_pair(boot_image_option_, nullptr));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001042 }
1043 for (size_t i = 0; i < runtime_args_.size(); i++) {
1044 runtime_options.push_back(std::make_pair(runtime_args_[i], nullptr));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001045 }
Brian Carlstromd76e0832013-08-29 15:17:42 -07001046
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001047 verification_results_.reset(new VerificationResults(compiler_options_.get()));
1048 callbacks_.reset(new QuickCompilerCallbacks(verification_results_.get(), &method_inliner_map_));
1049 runtime_options.push_back(std::make_pair("compilercallbacks", callbacks_.get()));
1050 runtime_options.push_back(
1051 std::make_pair("imageinstructionset", GetInstructionSetString(instruction_set_)));
1052
Andreas Gampe1d00add2015-02-27 19:35:46 -08001053 // Only allow no boot image for the runtime if we're compiling one. When we compile an app,
1054 // we don't want fallback mode, it will abort as we do not push a boot classpath (it might
1055 // have been stripped in preopting, anyways).
1056 if (!image_) {
1057 runtime_options.push_back(std::make_pair("-Xno-dex-file-fallback", nullptr));
1058 }
1059
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001060 if (!CreateRuntime(runtime_options)) {
1061 return false;
1062 }
1063
1064 // Runtime::Create acquired the mutator_lock_ that is normally given away when we
1065 // Runtime::Start, give it away now so that we don't starve GC.
1066 Thread* self = Thread::Current();
1067 self->TransitionFromRunnableToSuspended(kNative);
1068 // If we're doing the image, override the compiler filter to force full compilation. Must be
1069 // done ahead of WellKnownClasses::Init that causes verification. Note: doesn't force
1070 // compilation of class initializers.
1071 // Whilst we're in native take the opportunity to initialize well known classes.
1072 WellKnownClasses::Init(self->GetJniEnv());
1073
1074 // If --image-classes was specified, calculate the full list of classes to include in the image
1075 if (image_classes_filename_ != nullptr) {
1076 std::string error_msg;
1077 if (image_classes_zip_filename_ != nullptr) {
1078 image_classes_.reset(ReadImageClassesFromZip(image_classes_zip_filename_,
1079 image_classes_filename_,
1080 &error_msg));
1081 } else {
1082 image_classes_.reset(ReadImageClassesFromFile(image_classes_filename_));
1083 }
1084 if (image_classes_.get() == nullptr) {
1085 LOG(ERROR) << "Failed to create list of image classes from '" << image_classes_filename_ <<
1086 "': " << error_msg;
1087 return false;
1088 }
1089 } else if (image_) {
1090 image_classes_.reset(new std::set<std::string>);
1091 }
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001092 // If --compiled-classes was specified, calculate the full list of classes to compile in the
1093 // image.
1094 if (compiled_classes_filename_ != nullptr) {
1095 std::string error_msg;
1096 if (compiled_classes_zip_filename_ != nullptr) {
1097 compiled_classes_.reset(ReadImageClassesFromZip(compiled_classes_zip_filename_,
1098 compiled_classes_filename_,
1099 &error_msg));
1100 } else {
1101 compiled_classes_.reset(ReadImageClassesFromFile(compiled_classes_filename_));
1102 }
1103 if (compiled_classes_.get() == nullptr) {
1104 LOG(ERROR) << "Failed to create list of compiled classes from '"
1105 << compiled_classes_filename_ << "': " << error_msg;
1106 return false;
1107 }
1108 } else if (image_) {
1109 compiled_classes_.reset(nullptr); // By default compile everything.
1110 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001111
1112 if (boot_image_option_.empty()) {
1113 dex_files_ = Runtime::Current()->GetClassLinker()->GetBootClassPath();
1114 } else {
1115 if (dex_filenames_.empty()) {
1116 ATRACE_BEGIN("Opening zip archive from file descriptor");
1117 std::string error_msg;
1118 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(zip_fd_,
1119 zip_location_.c_str(),
1120 &error_msg));
1121 if (zip_archive.get() == nullptr) {
1122 LOG(ERROR) << "Failed to open zip from file descriptor for '" << zip_location_ << "': "
1123 << error_msg;
1124 return false;
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001125 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001126 if (!DexFile::OpenFromZip(*zip_archive.get(), zip_location_, &error_msg, &opened_dex_files_)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001127 LOG(ERROR) << "Failed to open dex from file descriptor for zip file '" << zip_location_
1128 << "': " << error_msg;
1129 return false;
1130 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001131 for (auto& dex_file : opened_dex_files_) {
1132 dex_files_.push_back(dex_file.get());
1133 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001134 ATRACE_END();
1135 } else {
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001136 size_t failure_count = OpenDexFiles(dex_filenames_, dex_locations_, &opened_dex_files_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001137 if (failure_count > 0) {
1138 LOG(ERROR) << "Failed to open some dex files: " << failure_count;
1139 return false;
1140 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001141 for (auto& dex_file : opened_dex_files_) {
1142 dex_files_.push_back(dex_file.get());
1143 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001144 }
1145
1146 constexpr bool kSaveDexInput = false;
1147 if (kSaveDexInput) {
1148 for (size_t i = 0; i < dex_files_.size(); ++i) {
1149 const DexFile* dex_file = dex_files_[i];
Brian Carlstrom95b033b2014-12-03 22:29:37 -08001150 std::string tmp_file_name(StringPrintf("/data/local/tmp/dex2oat.%d.%zd.dex",
1151 getpid(), i));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001152 std::unique_ptr<File> tmp_file(OS::CreateEmptyFile(tmp_file_name.c_str()));
1153 if (tmp_file.get() == nullptr) {
1154 PLOG(ERROR) << "Failed to open file " << tmp_file_name
1155 << ". Try: adb shell chmod 777 /data/local/tmp";
1156 continue;
1157 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001158 // This is just dumping files for debugging. Ignore errors, and leave remnants.
1159 UNUSED(tmp_file->WriteFully(dex_file->Begin(), dex_file->Size()));
1160 UNUSED(tmp_file->Flush());
1161 UNUSED(tmp_file->Close());
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001162 LOG(INFO) << "Wrote input to " << tmp_file_name;
1163 }
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001164 }
1165 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001166 // Ensure opened dex files are writable for dex-to-dex transformations.
1167 for (const auto& dex_file : dex_files_) {
1168 if (!dex_file->EnableWrite()) {
1169 PLOG(ERROR) << "Failed to make .dex file writeable '" << dex_file->GetLocation() << "'\n";
Andreas Gampe7ba64962014-10-23 11:37:40 -07001170 }
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001171 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001172
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001173 // If we use a swap file, ensure we are above the threshold to make it necessary.
1174 if (swap_fd_ != -1) {
1175 if (!UseSwap(image_, dex_files_)) {
1176 close(swap_fd_);
1177 swap_fd_ = -1;
1178 LOG(INFO) << "Decided to run without swap.";
1179 } else {
1180 LOG(INFO) << "Accepted running with swap.";
1181 }
1182 }
1183 // Note that dex2oat won't close the swap_fd_. The compiler driver's swap space will do that.
1184
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001185 /*
1186 * If we're not in interpret-only or verify-none mode, go ahead and compile small applications.
1187 * Don't bother to check if we're doing the image.
1188 */
Brian Carlstrom95b033b2014-12-03 22:29:37 -08001189 if (!image_ &&
1190 compiler_options_->IsCompilationEnabled() &&
1191 compiler_kind_ == Compiler::kQuick) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001192 size_t num_methods = 0;
1193 for (size_t i = 0; i != dex_files_.size(); ++i) {
1194 const DexFile* dex_file = dex_files_[i];
1195 CHECK(dex_file != nullptr);
1196 num_methods += dex_file->NumMethodIds();
1197 }
1198 if (num_methods <= compiler_options_->GetNumDexMethodsThreshold()) {
1199 compiler_options_->SetCompilerFilter(CompilerOptions::kSpeed);
1200 VLOG(compiler) << "Below method threshold, compiling anyways";
1201 }
1202 }
1203
1204 return true;
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001205 }
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001206
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001207 // Create and invoke the compiler driver. This will compile all the dex files.
1208 void Compile() {
1209 TimingLogger::ScopedTiming t("dex2oat Compile", timings_);
1210 compiler_phases_timings_.reset(new CumulativeLogger("compilation times"));
Vladimir Markof4da6752014-08-01 19:04:18 +01001211
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001212 // Handle and ClassLoader creation needs to come after Runtime::Create
1213 jobject class_loader = nullptr;
1214 Thread* self = Thread::Current();
1215 if (!boot_image_option_.empty()) {
1216 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001217 OpenClassPathFiles(runtime_->GetClassPathString(), dex_files_, &class_path_files_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001218 ScopedObjectAccess soa(self);
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001219 std::vector<const DexFile*> class_path_files(dex_files_);
1220 for (auto& class_path_file : class_path_files_) {
1221 class_path_files.push_back(class_path_file.get());
1222 }
1223
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001224 for (size_t i = 0; i < class_path_files.size(); i++) {
1225 class_linker->RegisterDexFile(*class_path_files[i]);
1226 }
1227 soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader);
1228 ScopedLocalRef<jobject> class_loader_local(soa.Env(),
1229 soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader));
1230 class_loader = soa.Env()->NewGlobalRef(class_loader_local.get());
1231 Runtime::Current()->SetCompileTimeClassPath(class_loader, class_path_files);
1232 }
1233
1234 driver_.reset(new CompilerDriver(compiler_options_.get(),
1235 verification_results_.get(),
1236 &method_inliner_map_,
1237 compiler_kind_,
1238 instruction_set_,
1239 instruction_set_features_.get(),
1240 image_,
1241 image_classes_.release(),
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001242 compiled_classes_.release(),
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001243 thread_count_,
1244 dump_stats_,
1245 dump_passes_,
David Brazdil866c0312015-01-13 21:21:31 +00001246 dump_cfg_file_name_,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001247 compiler_phases_timings_.get(),
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001248 swap_fd_,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001249 profile_file_));
1250
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001251 driver_->CompileAll(class_loader, dex_files_, timings_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001252 }
1253
Brian Carlstrom7940e442013-07-12 13:46:57 -07001254 // Notes on the interleaving of creating the image and oat file to
1255 // ensure the references between the two are correct.
1256 //
1257 // Currently we have a memory layout that looks something like this:
1258 //
1259 // +--------------+
1260 // | image |
1261 // +--------------+
1262 // | boot oat |
1263 // +--------------+
1264 // | alloc spaces |
1265 // +--------------+
1266 //
Brian Carlstrom45602482013-07-21 22:07:55 -07001267 // There are several constraints on the loading of the image and boot.oat.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001268 //
1269 // 1. The image is expected to be loaded at an absolute address and
1270 // contains Objects with absolute pointers within the image.
1271 //
1272 // 2. There are absolute pointers from Methods in the image to their
1273 // code in the oat.
1274 //
1275 // 3. There are absolute pointers from the code in the oat to Methods
1276 // in the image.
1277 //
1278 // 4. There are absolute pointers from code in the oat to other code
1279 // in the oat.
1280 //
1281 // To get this all correct, we go through several steps.
1282 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001283 // 1. We prepare offsets for all data in the oat file and calculate
1284 // the oat data size and code size. During this stage, we also set
1285 // oat code offsets in methods for use by the image writer.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001286 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001287 // 2. We prepare offsets for the objects in the image and calculate
1288 // the image size.
1289 //
1290 // 3. We create the oat file. Originally this was just our own proprietary
1291 // file but now it is contained within an ELF dynamic object (aka an .so
1292 // file). Since we know the image size and oat data size and code size we
1293 // can prepare the ELF headers and we then know the ELF memory segment
1294 // layout and we can now resolve all references. The compiler provides
1295 // LinkerPatch information in each CompiledMethod and we resolve these,
1296 // using the layout information and image object locations provided by
1297 // image writer, as we're writing the method code.
1298 //
1299 // 4. We create the image file. It needs to know where the oat file
Brian Carlstrom7940e442013-07-12 13:46:57 -07001300 // will be loaded after itself. Originally when oat file was simply
1301 // memory mapped so we could predict where its contents were based
1302 // on the file size. Now that it is an ELF file, we need to inspect
1303 // the ELF file to understand the in memory segment layout including
Vladimir Markof4da6752014-08-01 19:04:18 +01001304 // where the oat header is located within.
1305 // TODO: We could just remember this information from step 3.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001306 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001307 // 5. We fixup the ELF program headers so that dlopen will try to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001308 // load the .so at the desired location at runtime by offsetting the
1309 // Elf32_Phdr.p_vaddr values by the desired base address.
Vladimir Markof4da6752014-08-01 19:04:18 +01001310 // TODO: Do this in step 3. We already know the layout there.
1311 //
1312 // Steps 1.-3. are done by the CreateOatFile() above, steps 4.-5.
1313 // are done by the CreateImageFile() below.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001314
1315
1316 // Write out the generated code part. Calls the OatWriter and ElfBuilder. Also prepares the
1317 // ImageWriter, if necessary.
Andreas Gampe10e477d2014-11-19 12:57:42 -08001318 // Note: Flushing (and closing) the file is the caller's responsibility, except for the failure
1319 // case (when the file will be explicitly erased).
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001320 bool CreateOatFile() {
1321 CHECK(key_value_store_.get() != nullptr);
1322
1323 TimingLogger::ScopedTiming t("dex2oat Oat", timings_);
1324
1325 std::unique_ptr<OatWriter> oat_writer;
1326 {
1327 TimingLogger::ScopedTiming t2("dex2oat OatWriter", timings_);
1328 std::string image_file_location;
1329 uint32_t image_file_location_oat_checksum = 0;
1330 uintptr_t image_file_location_oat_data_begin = 0;
1331 int32_t image_patch_delta = 0;
1332 if (image_) {
1333 PrepareImageWriter(image_base_);
1334 } else {
1335 TimingLogger::ScopedTiming t3("Loading image checksum", timings_);
1336 gc::space::ImageSpace* image_space = Runtime::Current()->GetHeap()->GetImageSpace();
1337 image_file_location_oat_checksum = image_space->GetImageHeader().GetOatChecksum();
1338 image_file_location_oat_data_begin =
1339 reinterpret_cast<uintptr_t>(image_space->GetImageHeader().GetOatDataBegin());
1340 image_file_location = image_space->GetImageFilename();
1341 image_patch_delta = image_space->GetImageHeader().GetPatchDelta();
1342 }
1343
1344 if (!image_file_location.empty()) {
1345 key_value_store_->Put(OatHeader::kImageLocationKey, image_file_location);
1346 }
1347
1348 oat_writer.reset(new OatWriter(dex_files_, image_file_location_oat_checksum,
1349 image_file_location_oat_data_begin,
1350 image_patch_delta,
1351 driver_.get(),
1352 image_writer_.get(),
1353 timings_,
1354 key_value_store_.get()));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001355 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001356
1357 if (image_) {
1358 // The OatWriter constructor has already updated offsets in methods and we need to
1359 // prepare method offsets in the image address space for direct method patching.
1360 TimingLogger::ScopedTiming t2("dex2oat Prepare image address space", timings_);
1361 if (!image_writer_->PrepareImageAddressSpace()) {
1362 LOG(ERROR) << "Failed to prepare image address space.";
1363 return false;
1364 }
1365 }
1366
1367 {
1368 TimingLogger::ScopedTiming t2("dex2oat Write ELF", timings_);
1369 if (!driver_->WriteElf(android_root_, is_host_, dex_files_, oat_writer.get(),
1370 oat_file_.get())) {
1371 LOG(ERROR) << "Failed to write ELF file " << oat_file_->GetPath();
1372 return false;
1373 }
1374 }
1375
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001376 VLOG(compiler) << "Oat file written successfully (unstripped): " << oat_location_;
1377 return true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001378 }
1379
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001380 // If we are compiling an image, invoke the image creation routine. Else just skip.
1381 bool HandleImage() {
1382 if (image_) {
1383 TimingLogger::ScopedTiming t("dex2oat ImageWriter", timings_);
1384 if (!CreateImageFile()) {
1385 return false;
1386 }
1387 VLOG(compiler) << "Image written successfully: " << image_filename_;
Brian Carlstrom45602482013-07-21 22:07:55 -07001388 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001389 return true;
1390 }
1391
Andreas Gampe10e477d2014-11-19 12:57:42 -08001392 // Create a copy from unstripped to stripped.
1393 bool CopyUnstrippedToStripped() {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001394 // If we don't want to strip in place, copy from unstripped location to stripped location.
1395 // We need to strip after image creation because FixupElf needs to use .strtab.
1396 if (oat_unstripped_ != oat_stripped_) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08001397 // If the oat file is still open, flush it.
1398 if (oat_file_.get() != nullptr && oat_file_->IsOpened()) {
1399 if (!FlushCloseOatFile()) {
1400 return false;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001401 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001402 }
Andreas Gampe10e477d2014-11-19 12:57:42 -08001403
1404 TimingLogger::ScopedTiming t("dex2oat OatFile copy", timings_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001405 std::unique_ptr<File> in(OS::OpenFileForReading(oat_unstripped_.c_str()));
1406 std::unique_ptr<File> out(OS::CreateEmptyFile(oat_stripped_.c_str()));
1407 size_t buffer_size = 8192;
Dan Albert6fc59ab2014-12-11 14:09:51 -08001408 std::unique_ptr<uint8_t[]> buffer(new uint8_t[buffer_size]);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001409 while (true) {
1410 int bytes_read = TEMP_FAILURE_RETRY(read(in->Fd(), buffer.get(), buffer_size));
1411 if (bytes_read <= 0) {
1412 break;
1413 }
1414 bool write_ok = out->WriteFully(buffer.get(), bytes_read);
1415 CHECK(write_ok);
1416 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08001417 if (out->FlushCloseOrErase() != 0) {
1418 PLOG(ERROR) << "Failed to flush and close copied oat file: " << oat_stripped_;
1419 return false;
Andreas Gampe10e477d2014-11-19 12:57:42 -08001420 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001421 VLOG(compiler) << "Oat file copied successfully (stripped): " << oat_stripped_;
Nicolas Geoffrayea3fa0b2014-02-10 11:59:41 +00001422 }
Andreas Gampe10e477d2014-11-19 12:57:42 -08001423 return true;
1424 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001425
Andreas Gampe10e477d2014-11-19 12:57:42 -08001426 bool FlushOatFile() {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001427 if (oat_file_.get() != nullptr) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08001428 TimingLogger::ScopedTiming t2("dex2oat Flush ELF", timings_);
1429 if (oat_file_->Flush() != 0) {
1430 PLOG(ERROR) << "Failed to flush oat file: " << oat_location_ << " / "
1431 << oat_filename_;
1432 oat_file_->Erase();
1433 return false;
1434 }
1435 }
1436 return true;
1437 }
1438
1439 bool FlushCloseOatFile() {
1440 if (oat_file_.get() != nullptr) {
1441 std::unique_ptr<File> tmp(oat_file_.release());
1442 if (tmp->FlushCloseOrErase() != 0) {
1443 PLOG(ERROR) << "Failed to flush and close oat file: " << oat_location_ << " / "
1444 << oat_filename_;
1445 return false;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001446 }
1447 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001448 return true;
1449 }
1450
1451 void DumpTiming() {
1452 if (dump_timing_ || (dump_slow_timing_ && timings_->GetTotalNs() > MsToNs(1000))) {
1453 LOG(INFO) << Dumpable<TimingLogger>(*timings_);
1454 }
1455 if (dump_passes_) {
1456 LOG(INFO) << Dumpable<CumulativeLogger>(*driver_->GetTimingsLogger());
1457 }
1458 }
1459
1460 CompilerOptions* GetCompilerOptions() const {
1461 return compiler_options_.get();
1462 }
1463
Andreas Gampe10e477d2014-11-19 12:57:42 -08001464 bool IsImage() const {
1465 return image_;
1466 }
1467
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001468 bool IsHost() const {
1469 return is_host_;
1470 }
1471
1472 private:
1473 static size_t OpenDexFiles(const std::vector<const char*>& dex_filenames,
1474 const std::vector<const char*>& dex_locations,
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001475 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
1476 DCHECK(dex_files != nullptr) << "OpenDexFiles out-param is NULL";
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001477 size_t failure_count = 0;
1478 for (size_t i = 0; i < dex_filenames.size(); i++) {
1479 const char* dex_filename = dex_filenames[i];
1480 const char* dex_location = dex_locations[i];
1481 ATRACE_BEGIN(StringPrintf("Opening dex file '%s'", dex_filenames[i]).c_str());
1482 std::string error_msg;
1483 if (!OS::FileExists(dex_filename)) {
1484 LOG(WARNING) << "Skipping non-existent dex file '" << dex_filename << "'";
1485 continue;
1486 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001487 if (!DexFile::Open(dex_filename, dex_location, &error_msg, dex_files)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001488 LOG(WARNING) << "Failed to open .dex from file '" << dex_filename << "': " << error_msg;
1489 ++failure_count;
1490 }
1491 ATRACE_END();
1492 }
1493 return failure_count;
1494 }
1495
1496 // Returns true if dex_files has a dex with the named location.
1497 static bool DexFilesContains(const std::vector<const DexFile*>& dex_files,
1498 const std::string& location) {
1499 for (size_t i = 0; i < dex_files.size(); ++i) {
1500 if (dex_files[i]->GetLocation() == location) {
1501 return true;
1502 }
1503 }
1504 return false;
1505 }
1506
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001507 // Appends to opened_dex_files any elements of class_path that dex_files
1508 // doesn't already contain. This will open those dex files as necessary.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001509 static void OpenClassPathFiles(const std::string& class_path,
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001510 std::vector<const DexFile*> dex_files,
1511 std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
1512 DCHECK(opened_dex_files != nullptr) << "OpenClassPathFiles out-param is NULL";
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001513 std::vector<std::string> parsed;
1514 Split(class_path, ':', &parsed);
1515 // Take Locks::mutator_lock_ so that lock ordering on the ClassLinker::dex_lock_ is maintained.
1516 ScopedObjectAccess soa(Thread::Current());
1517 for (size_t i = 0; i < parsed.size(); ++i) {
1518 if (DexFilesContains(dex_files, parsed[i])) {
1519 continue;
1520 }
1521 std::string error_msg;
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001522 if (!DexFile::Open(parsed[i].c_str(), parsed[i].c_str(), &error_msg, opened_dex_files)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001523 LOG(WARNING) << "Failed to open dex file '" << parsed[i] << "': " << error_msg;
1524 }
1525 }
1526 }
1527
1528 // Create a runtime necessary for compilation.
1529 bool CreateRuntime(const RuntimeOptions& runtime_options)
1530 SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_) {
1531 if (!Runtime::Create(runtime_options, false)) {
1532 LOG(ERROR) << "Failed to create runtime";
1533 return false;
1534 }
1535 Runtime* runtime = Runtime::Current();
1536 runtime->SetInstructionSet(instruction_set_);
1537 for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
1538 Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i);
1539 if (!runtime->HasCalleeSaveMethod(type)) {
1540 runtime->SetCalleeSaveMethod(runtime->CreateCalleeSaveMethod(), type);
1541 }
1542 }
1543 runtime->GetClassLinker()->FixupDexCaches(runtime->GetResolutionMethod());
1544 runtime->GetClassLinker()->RunRootClinits();
1545 runtime_ = runtime;
1546 return true;
1547 }
1548
1549 void PrepareImageWriter(uintptr_t image_base) {
1550 image_writer_.reset(new ImageWriter(*driver_, image_base, compiler_options_->GetCompilePic()));
1551 }
1552
1553 // Let the ImageWriter write the image file. If we do not compile PIC, also fix up the oat file.
1554 bool CreateImageFile()
1555 LOCKS_EXCLUDED(Locks::mutator_lock_) {
1556 CHECK(image_writer_ != nullptr);
1557 if (!image_writer_->Write(image_filename_, oat_unstripped_, oat_location_)) {
1558 LOG(ERROR) << "Failed to create image file " << image_filename_;
1559 return false;
1560 }
1561 uintptr_t oat_data_begin = image_writer_->GetOatDataBegin();
1562
1563 // Destroy ImageWriter before doing FixupElf.
1564 image_writer_.reset();
1565
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001566 // Do not fix up the ELF file if we are --compile-pic
1567 if (!compiler_options_->GetCompilePic()) {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001568 std::unique_ptr<File> oat_file(OS::OpenFileReadWrite(oat_unstripped_.c_str()));
1569 if (oat_file.get() == nullptr) {
1570 PLOG(ERROR) << "Failed to open ELF file: " << oat_unstripped_;
1571 return false;
1572 }
1573
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001574 if (!ElfWriter::Fixup(oat_file.get(), oat_data_begin)) {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001575 oat_file->Erase();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001576 LOG(ERROR) << "Failed to fixup ELF file " << oat_file->GetPath();
1577 return false;
1578 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001579
1580 if (oat_file->FlushCloseOrErase()) {
1581 PLOG(ERROR) << "Failed to flush and close fixed ELF file " << oat_file->GetPath();
1582 return false;
1583 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001584 }
1585
1586 return true;
1587 }
1588
1589 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
1590 static std::set<std::string>* ReadImageClassesFromFile(const char* image_classes_filename) {
1591 std::unique_ptr<std::ifstream> image_classes_file(new std::ifstream(image_classes_filename,
1592 std::ifstream::in));
1593 if (image_classes_file.get() == nullptr) {
1594 LOG(ERROR) << "Failed to open image classes file " << image_classes_filename;
1595 return nullptr;
1596 }
1597 std::unique_ptr<std::set<std::string>> result(ReadImageClasses(*image_classes_file));
1598 image_classes_file->close();
1599 return result.release();
1600 }
1601
1602 static std::set<std::string>* ReadImageClasses(std::istream& image_classes_stream) {
1603 std::unique_ptr<std::set<std::string>> image_classes(new std::set<std::string>);
1604 while (image_classes_stream.good()) {
1605 std::string dot;
1606 std::getline(image_classes_stream, dot);
1607 if (StartsWith(dot, "#") || dot.empty()) {
1608 continue;
1609 }
1610 std::string descriptor(DotToDescriptor(dot.c_str()));
1611 image_classes->insert(descriptor);
1612 }
1613 return image_classes.release();
1614 }
1615
1616 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
1617 static std::set<std::string>* ReadImageClassesFromZip(const char* zip_filename,
1618 const char* image_classes_filename,
1619 std::string* error_msg) {
1620 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::Open(zip_filename, error_msg));
1621 if (zip_archive.get() == nullptr) {
1622 return nullptr;
1623 }
1624 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(image_classes_filename, error_msg));
1625 if (zip_entry.get() == nullptr) {
1626 *error_msg = StringPrintf("Failed to find '%s' within '%s': %s", image_classes_filename,
1627 zip_filename, error_msg->c_str());
1628 return nullptr;
1629 }
1630 std::unique_ptr<MemMap> image_classes_file(zip_entry->ExtractToMemMap(zip_filename,
1631 image_classes_filename,
1632 error_msg));
1633 if (image_classes_file.get() == nullptr) {
1634 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", image_classes_filename,
1635 zip_filename, error_msg->c_str());
1636 return nullptr;
1637 }
1638 const std::string image_classes_string(reinterpret_cast<char*>(image_classes_file->Begin()),
1639 image_classes_file->Size());
1640 std::istringstream image_classes_stream(image_classes_string);
1641 return ReadImageClasses(image_classes_stream);
1642 }
1643
Mathieu Chartier49285c52014-12-02 15:43:48 -08001644 void LogCompletionTime() {
Andreas Gampe1d00add2015-02-27 19:35:46 -08001645 // Note: when creation of a runtime fails, e.g., when trying to compile an app but when there
1646 // is no image, there won't be a Runtime::Current().
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001647 LOG(INFO) << "dex2oat took " << PrettyDuration(NanoTime() - start_ns_)
Mathieu Chartierab972ef2014-12-03 17:38:22 -08001648 << " (threads: " << thread_count_ << ") "
Andreas Gampe1d00add2015-02-27 19:35:46 -08001649 << ((Runtime::Current() != nullptr) ?
1650 driver_->GetMemoryUsageString(kIsDebugBuild || VLOG_IS_ON(compiler)) :
1651 "");
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001652 }
1653
1654 std::unique_ptr<CompilerOptions> compiler_options_;
1655 Compiler::Kind compiler_kind_;
1656
1657 InstructionSet instruction_set_;
1658 std::unique_ptr<const InstructionSetFeatures> instruction_set_features_;
1659
1660 std::unique_ptr<SafeMap<std::string, std::string> > key_value_store_;
1661
1662 std::unique_ptr<VerificationResults> verification_results_;
1663 DexFileToMethodInlinerMap method_inliner_map_;
1664 std::unique_ptr<QuickCompilerCallbacks> callbacks_;
1665
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001666 // Ownership for the class path files.
1667 std::vector<std::unique_ptr<const DexFile>> class_path_files_;
1668
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001669 // Not a unique_ptr as we want to just exit on non-debug builds, not bringing the runtime down
1670 // in an orderly fashion. The destructor takes care of deleting this.
1671 Runtime* runtime_;
1672
1673 size_t thread_count_;
1674 uint64_t start_ns_;
1675 std::unique_ptr<WatchDog> watchdog_;
1676 std::unique_ptr<File> oat_file_;
1677 std::string oat_stripped_;
1678 std::string oat_unstripped_;
1679 std::string oat_location_;
1680 std::string oat_filename_;
1681 int oat_fd_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001682 std::vector<const char*> dex_filenames_;
1683 std::vector<const char*> dex_locations_;
1684 int zip_fd_;
1685 std::string zip_location_;
1686 std::string boot_image_option_;
1687 std::vector<const char*> runtime_args_;
1688 std::string image_filename_;
1689 uintptr_t image_base_;
1690 const char* image_classes_zip_filename_;
1691 const char* image_classes_filename_;
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001692 const char* compiled_classes_zip_filename_;
1693 const char* compiled_classes_filename_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001694 std::unique_ptr<std::set<std::string>> image_classes_;
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001695 std::unique_ptr<std::set<std::string>> compiled_classes_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001696 bool image_;
1697 std::unique_ptr<ImageWriter> image_writer_;
1698 bool is_host_;
1699 std::string android_root_;
1700 std::vector<const DexFile*> dex_files_;
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001701 std::vector<std::unique_ptr<const DexFile>> opened_dex_files_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001702 std::unique_ptr<CompilerDriver> driver_;
1703 std::vector<std::string> verbose_methods_;
1704 bool dump_stats_;
1705 bool dump_passes_;
1706 bool dump_timing_;
1707 bool dump_slow_timing_;
David Brazdil866c0312015-01-13 21:21:31 +00001708 std::string dump_cfg_file_name_;
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001709 std::string swap_file_name_;
1710 int swap_fd_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001711 std::string profile_file_; // Profile file to use
1712 TimingLogger* timings_;
1713 std::unique_ptr<CumulativeLogger> compiler_phases_timings_;
Andreas Gampedbfe2542014-11-25 22:21:42 -08001714 std::unique_ptr<std::ostream> init_failure_output_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001715
1716 DISALLOW_IMPLICIT_CONSTRUCTORS(Dex2Oat);
1717};
1718
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001719const unsigned int WatchDog::kWatchDogTimeoutSeconds;
1720
1721static void b13564922() {
1722#if defined(__linux__) && defined(__arm__)
1723 int major, minor;
1724 struct utsname uts;
1725 if (uname(&uts) != -1 &&
1726 sscanf(uts.release, "%d.%d", &major, &minor) == 2 &&
1727 ((major < 3) || ((major == 3) && (minor < 4)))) {
1728 // Kernels before 3.4 don't handle the ASLR well and we can run out of address
1729 // space (http://b/13564922). Work around the issue by inhibiting further mmap() randomization.
1730 int old_personality = personality(0xffffffff);
1731 if ((old_personality & ADDR_NO_RANDOMIZE) == 0) {
1732 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
1733 if (new_personality == -1) {
1734 LOG(WARNING) << "personality(. | ADDR_NO_RANDOMIZE) failed.";
1735 }
1736 }
1737 }
1738#endif
1739}
1740
Andreas Gampe10e477d2014-11-19 12:57:42 -08001741static int CompileImage(Dex2Oat& dex2oat) {
1742 dex2oat.Compile();
1743
1744 // Create the boot.oat.
1745 if (!dex2oat.CreateOatFile()) {
Andreas Gampea650e702014-12-03 14:28:02 -08001746 dex2oat.EraseOatFile();
Andreas Gampe10e477d2014-11-19 12:57:42 -08001747 return EXIT_FAILURE;
1748 }
1749
1750 // Flush and close the boot.oat. We always expect the output file by name, and it will be
1751 // re-opened from the unstripped name.
1752 if (!dex2oat.FlushCloseOatFile()) {
1753 return EXIT_FAILURE;
1754 }
1755
1756 // Creates the boot.art and patches the boot.oat.
1757 if (!dex2oat.HandleImage()) {
1758 return EXIT_FAILURE;
1759 }
1760
1761 // When given --host, finish early without stripping.
1762 if (dex2oat.IsHost()) {
1763 dex2oat.DumpTiming();
1764 return EXIT_SUCCESS;
1765 }
1766
1767 // Copy unstripped to stripped location, if necessary.
1768 if (!dex2oat.CopyUnstrippedToStripped()) {
1769 return EXIT_FAILURE;
1770 }
1771
Andreas Gampe10e477d2014-11-19 12:57:42 -08001772 // FlushClose again, as stripping might have re-opened the oat file.
1773 if (!dex2oat.FlushCloseOatFile()) {
1774 return EXIT_FAILURE;
1775 }
1776
1777 dex2oat.DumpTiming();
1778 return EXIT_SUCCESS;
1779}
1780
1781static int CompileApp(Dex2Oat& dex2oat) {
1782 dex2oat.Compile();
1783
1784 // Create the app oat.
1785 if (!dex2oat.CreateOatFile()) {
Andreas Gampea650e702014-12-03 14:28:02 -08001786 dex2oat.EraseOatFile();
Andreas Gampe10e477d2014-11-19 12:57:42 -08001787 return EXIT_FAILURE;
1788 }
1789
1790 // Do not close the oat file here. We might haven gotten the output file by file descriptor,
1791 // which we would lose.
1792 if (!dex2oat.FlushOatFile()) {
1793 return EXIT_FAILURE;
1794 }
1795
1796 // When given --host, finish early without stripping.
1797 if (dex2oat.IsHost()) {
1798 if (!dex2oat.FlushCloseOatFile()) {
1799 return EXIT_FAILURE;
1800 }
1801
1802 dex2oat.DumpTiming();
1803 return EXIT_SUCCESS;
1804 }
1805
1806 // Copy unstripped to stripped location, if necessary. This will implicitly flush & close the
1807 // unstripped version. If this is given, we expect to be able to open writable files by name.
1808 if (!dex2oat.CopyUnstrippedToStripped()) {
1809 return EXIT_FAILURE;
1810 }
1811
Andreas Gampe10e477d2014-11-19 12:57:42 -08001812 // Flush and close the file.
1813 if (!dex2oat.FlushCloseOatFile()) {
1814 return EXIT_FAILURE;
1815 }
1816
1817 dex2oat.DumpTiming();
1818 return EXIT_SUCCESS;
1819}
1820
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001821static int dex2oat(int argc, char** argv) {
1822 b13564922();
1823
1824 TimingLogger timings("compiler", false, false);
1825
1826 Dex2Oat dex2oat(&timings);
1827
1828 // Parse arguments. Argument mistakes will lead to exit(EXIT_FAILURE) in UsageError.
1829 dex2oat.ParseArgs(argc, argv);
1830
1831 // Check early that the result of compilation can be written
1832 if (!dex2oat.OpenFile()) {
1833 return EXIT_FAILURE;
1834 }
1835
1836 LOG(INFO) << CommandLine();
1837
1838 if (!dex2oat.Setup()) {
Andreas Gampea650e702014-12-03 14:28:02 -08001839 dex2oat.EraseOatFile();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001840 return EXIT_FAILURE;
1841 }
1842
Andreas Gampe10e477d2014-11-19 12:57:42 -08001843 if (dex2oat.IsImage()) {
1844 return CompileImage(dex2oat);
1845 } else {
1846 return CompileApp(dex2oat);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001847 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001848}
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001849} // namespace art
Brian Carlstrom7940e442013-07-12 13:46:57 -07001850
1851int main(int argc, char** argv) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001852 int result = art::dex2oat(argc, argv);
1853 // Everything was done, do an explicit exit here to avoid running Runtime destructors that take
1854 // time (bug 10645725) unless we're a debug build or running on valgrind. Note: The Dex2Oat class
1855 // should not destruct the runtime in this case.
1856 if (!art::kIsDebugBuild && (RUNNING_ON_VALGRIND == 0)) {
1857 exit(result);
1858 }
1859 return result;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001860}