blob: 22665ea6ee0ce5cf9c3ccfb2e510b18ad7fbe824 [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");
183#if ART_SMALL_MODE
184 UsageError(" Default: interpret-only");
185#else
186 UsageError(" Default: speed");
187#endif
188 UsageError("");
189 UsageError(" --huge-method-max=<method-instruction-count>: the threshold size for a huge");
190 UsageError(" method for compiler filter tuning.");
191 UsageError(" Example: --huge-method-max=%d", CompilerOptions::kDefaultHugeMethodThreshold);
192 UsageError(" Default: %d", CompilerOptions::kDefaultHugeMethodThreshold);
193 UsageError("");
194 UsageError(" --huge-method-max=<method-instruction-count>: threshold size for a huge");
195 UsageError(" method for compiler filter tuning.");
196 UsageError(" Example: --huge-method-max=%d", CompilerOptions::kDefaultHugeMethodThreshold);
197 UsageError(" Default: %d", CompilerOptions::kDefaultHugeMethodThreshold);
198 UsageError("");
199 UsageError(" --large-method-max=<method-instruction-count>: threshold size for a large");
200 UsageError(" method for compiler filter tuning.");
201 UsageError(" Example: --large-method-max=%d", CompilerOptions::kDefaultLargeMethodThreshold);
202 UsageError(" Default: %d", CompilerOptions::kDefaultLargeMethodThreshold);
203 UsageError("");
204 UsageError(" --small-method-max=<method-instruction-count>: threshold size for a small");
205 UsageError(" method for compiler filter tuning.");
206 UsageError(" Example: --small-method-max=%d", CompilerOptions::kDefaultSmallMethodThreshold);
207 UsageError(" Default: %d", CompilerOptions::kDefaultSmallMethodThreshold);
208 UsageError("");
209 UsageError(" --tiny-method-max=<method-instruction-count>: threshold size for a tiny");
210 UsageError(" method for compiler filter tuning.");
211 UsageError(" Example: --tiny-method-max=%d", CompilerOptions::kDefaultTinyMethodThreshold);
212 UsageError(" Default: %d", CompilerOptions::kDefaultTinyMethodThreshold);
213 UsageError("");
214 UsageError(" --num-dex-methods=<method-count>: threshold size for a small dex file for");
215 UsageError(" compiler filter tuning. If the input has fewer than this many methods");
Jeff Hao4a200f52014-04-01 14:58:49 -0700216 UsageError(" and the filter is not interpret-only or verify-none, overrides the");
217 UsageError(" filter to use speed");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800218 UsageError(" Example: --num-dex-method=%d", CompilerOptions::kDefaultNumDexMethodsThreshold);
219 UsageError(" Default: %d", CompilerOptions::kDefaultNumDexMethodsThreshold);
220 UsageError("");
Ian Rogers46398602013-08-20 07:50:36 -0700221 UsageError(" --dump-timing: display a breakdown of where time was spent");
222 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700223 UsageError(" --include-patch-information: Include patching information so the generated code");
224 UsageError(" can have its base address moved without full recompilation.");
225 UsageError("");
226 UsageError(" --no-include-patch-information: Do not include patching information.");
227 UsageError("");
Alex Light78382fa2014-06-06 15:45:32 -0700228 UsageError(" --include-debug-symbols: Include ELF symbols in this oat file");
229 UsageError("");
230 UsageError(" --no-include-debug-symbols: Do not include ELF symbols in this oat file");
231 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700232 UsageError(" --runtime-arg <argument>: used to specify various arguments for the runtime,");
233 UsageError(" such as initial heap size, maximum heap size, and verbose output.");
234 UsageError(" Use a separate --runtime-arg switch for each argument.");
235 UsageError(" Example: --runtime-arg -Xms256m");
Jeff Hao4a200f52014-04-01 14:58:49 -0700236 UsageError("");
Dave Allisond6ed6422014-04-09 23:36:15 +0000237 UsageError(" --profile-file=<filename>: specify profiler output file to use for compilation.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700238 UsageError("");
Chao-ying Fucd8ce662014-03-11 14:57:19 -0700239 UsageError(" --print-pass-names: print a list of pass names");
240 UsageError("");
241 UsageError(" --disable-passes=<pass-names>: disable one or more passes separated by comma.");
242 UsageError(" Example: --disable-passes=UseCount,BBOptimizations");
243 UsageError("");
Razvan A Lupusorubd25d4b2014-07-02 18:16:51 -0700244 UsageError(" --print-pass-options: print a list of passes that have configurable options along "
245 "with the setting.");
246 UsageError(" Will print default if no overridden setting exists.");
247 UsageError("");
248 UsageError(" --pass-options=Pass1Name:Pass1OptionName:Pass1Option#,"
249 "Pass2Name:Pass2OptionName:Pass2Option#");
250 UsageError(" Used to specify a pass specific option. The setting itself must be integer.");
251 UsageError(" Separator used between options is a comma.");
252 UsageError("");
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800253 UsageError(" --swap-file=<file-name>: specifies a file to use for swap.");
254 UsageError(" Example: --swap-file=/data/tmp/swap.001");
255 UsageError("");
256 UsageError(" --swap-fd=<file-descriptor>: specifies a file to use for swap (by descriptor).");
257 UsageError(" Example: --swap-fd=10");
258 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700259 std::cerr << "See log for usage error information\n";
260 exit(EXIT_FAILURE);
261}
262
Brian Carlstrom7940e442013-07-12 13:46:57 -0700263// The primary goal of the watchdog is to prevent stuck build servers
264// during development when fatal aborts lead to a cascade of failures
265// that result in a deadlock.
266class WatchDog {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800267// WatchDog defines its own CHECK_PTHREAD_CALL to avoid using LOG which uses locks
Brian Carlstrom7940e442013-07-12 13:46:57 -0700268#undef CHECK_PTHREAD_CALL
269#define CHECK_WATCH_DOG_PTHREAD_CALL(call, args, what) \
270 do { \
271 int rc = call args; \
272 if (rc != 0) { \
273 errno = rc; \
274 std::string message(# call); \
275 message += " failed for "; \
276 message += reason; \
277 Fatal(message); \
278 } \
279 } while (false)
280
281 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -0700282 explicit WatchDog(bool is_watch_dog_enabled) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700283 is_watch_dog_enabled_ = is_watch_dog_enabled;
284 if (!is_watch_dog_enabled_) {
285 return;
286 }
287 shutting_down_ = false;
288 const char* reason = "dex2oat watch dog thread startup";
Kenny Root51316382014-05-13 14:59:37 -0700289 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_init, (&mutex_, nullptr), reason);
290 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_init, (&cond_, nullptr), reason);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700291 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_init, (&attr_), reason);
292 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_create, (&pthread_, &attr_, &CallBack, this), reason);
293 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_destroy, (&attr_), reason);
294 }
295 ~WatchDog() {
296 if (!is_watch_dog_enabled_) {
297 return;
298 }
299 const char* reason = "dex2oat watch dog thread shutdown";
300 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
301 shutting_down_ = true;
302 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_signal, (&cond_), reason);
303 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
304
Kenny Root51316382014-05-13 14:59:37 -0700305 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_join, (pthread_, nullptr), reason);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700306
307 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_destroy, (&cond_), reason);
308 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_destroy, (&mutex_), reason);
309 }
310
311 private:
312 static void* CallBack(void* arg) {
313 WatchDog* self = reinterpret_cast<WatchDog*>(arg);
314 ::art::SetThreadName("dex2oat watch dog");
315 self->Wait();
Kenny Root51316382014-05-13 14:59:37 -0700316 return nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700317 }
318
319 static void Message(char severity, const std::string& message) {
320 // TODO: Remove when we switch to LOG when we can guarantee it won't prevent shutdown in error
321 // cases.
322 fprintf(stderr, "dex2oat%s %c %d %d %s\n",
323 kIsDebugBuild ? "d" : "",
324 severity,
325 getpid(),
326 GetTid(),
327 message.c_str());
328 }
329
Andreas Gampe794ad762015-02-23 08:12:24 -0800330 NO_RETURN static void Fatal(const std::string& message) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700331 Message('F', message);
332 exit(1);
333 }
334
335 void Wait() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700336 // TODO: tune the multiplier for GC verification, the following is just to make the timeout
337 // large.
Mathieu Chartier4e305412014-02-19 10:54:44 -0800338 int64_t multiplier = kVerifyObjectSupport > kVerifyObjectModeFast ? 100 : 1;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700339 timespec timeout_ts;
340 InitTimeSpec(true, CLOCK_REALTIME, multiplier * kWatchDogTimeoutSeconds * 1000, 0, &timeout_ts);
341 const char* reason = "dex2oat watch dog thread waiting";
342 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
343 while (!shutting_down_) {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800344 int rc = TEMP_FAILURE_RETRY(pthread_cond_timedwait(&cond_, &mutex_, &timeout_ts));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700345 if (rc == ETIMEDOUT) {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800346 Fatal(StringPrintf("dex2oat did not finish after %d seconds", kWatchDogTimeoutSeconds));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700347 } else if (rc != 0) {
348 std::string message(StringPrintf("pthread_cond_timedwait failed: %s",
349 strerror(errno)));
350 Fatal(message.c_str());
351 }
352 }
353 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
354 }
355
356 // 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 -0700357 // Debug builds are slower so they have larger timeouts.
358 static const unsigned int kSlowdownFactor = kIsDebugBuild ? 5U : 1U;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800359
Elliott Hughes956af0f2014-12-11 14:34:28 -0800360 // 6 minutes scaled by kSlowdownFactor.
361 static const unsigned int kWatchDogTimeoutSeconds = kSlowdownFactor * 6 * 60;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700362
363 bool is_watch_dog_enabled_;
364 bool shutting_down_;
365 // TODO: Switch to Mutex when we can guarantee it won't prevent shutdown in error cases.
366 pthread_mutex_t mutex_;
367 pthread_cond_t cond_;
368 pthread_attr_t attr_;
369 pthread_t pthread_;
370};
Brian Carlstrom7940e442013-07-12 13:46:57 -0700371
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800372static void ParseStringAfterChar(const std::string& s, char c, std::string* parsed_value) {
Calin Juravlec1b643c2014-05-30 23:44:11 +0100373 std::string::size_type colon = s.find(c);
374 if (colon == std::string::npos) {
375 Usage("Missing char %c in option %s\n", c, s.c_str());
376 }
377 // Add one to remove the char we were trimming until.
378 *parsed_value = s.substr(colon + 1);
379}
380
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800381static void ParseDouble(const std::string& option, char after_char, double min, double max,
382 double* parsed_value) {
Calin Juravlec1b643c2014-05-30 23:44:11 +0100383 std::string substring;
384 ParseStringAfterChar(option, after_char, &substring);
385 bool sane_val = true;
386 double value;
387 if (false) {
388 // TODO: this doesn't seem to work on the emulator. b/15114595
389 std::stringstream iss(substring);
390 iss >> value;
391 // Ensure that we have a value, there was no cruft after it and it satisfies a sensible range.
392 sane_val = iss.eof() && (value >= min) && (value <= max);
393 } else {
394 char* end = nullptr;
395 value = strtod(substring.c_str(), &end);
396 sane_val = *end == '\0' && value >= min && value <= max;
397 }
398 if (!sane_val) {
399 Usage("Invalid double value %s for option %s\n", substring.c_str(), option.c_str());
400 }
401 *parsed_value = value;
402}
403
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800404static constexpr size_t kMinDexFilesForSwap = 2;
405static constexpr size_t kMinDexFileCumulativeSizeForSwap = 20 * MB;
406
407static bool UseSwap(bool is_image, std::vector<const DexFile*>& dex_files) {
408 if (is_image) {
409 // Don't use swap, we know generation should succeed, and we don't want to slow it down.
410 return false;
411 }
412 if (dex_files.size() < kMinDexFilesForSwap) {
413 // If there are less dex files than the threshold, assume it's gonna be fine.
414 return false;
415 }
416 size_t dex_files_size = 0;
417 for (const auto* dex_file : dex_files) {
418 dex_files_size += dex_file->GetHeader().file_size_;
419 }
420 return dex_files_size >= kMinDexFileCumulativeSizeForSwap;
421}
422
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800423class Dex2Oat FINAL {
424 public:
425 explicit Dex2Oat(TimingLogger* timings) :
Elliott Hughes956af0f2014-12-11 14:34:28 -0800426 compiler_kind_(kUseOptimizingCompiler ? Compiler::kOptimizing : Compiler::kQuick),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800427 instruction_set_(kRuntimeISA),
428 // Take the default set of instruction features from the build.
429 method_inliner_map_(),
430 runtime_(nullptr),
431 thread_count_(sysconf(_SC_NPROCESSORS_CONF)),
432 start_ns_(NanoTime()),
433 oat_fd_(-1),
434 zip_fd_(-1),
435 image_base_(0U),
436 image_classes_zip_filename_(nullptr),
437 image_classes_filename_(nullptr),
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800438 compiled_classes_zip_filename_(nullptr),
439 compiled_classes_filename_(nullptr),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800440 image_(false),
441 is_host_(false),
442 dump_stats_(false),
443 dump_passes_(false),
444 dump_timing_(false),
445 dump_slow_timing_(kIsDebugBuild),
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800446 swap_fd_(-1),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800447 timings_(timings) {}
448
449 ~Dex2Oat() {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800450 // Free opened dex files before deleting the runtime_, because ~DexFile
451 // uses MemMap, which is shut down by ~Runtime.
452 class_path_files_.clear();
453 opened_dex_files_.clear();
454
455 // Log completion time before deleting the runtime_, because this accesses
456 // the runtime.
457 LogCompletionTime();
458
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800459 if (kIsDebugBuild || (RUNNING_ON_VALGRIND != 0)) {
460 delete runtime_; // See field declaration for why this is manual.
Vladimir Markof94b7812014-06-05 15:48:04 +0100461 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700462 }
463
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800464 // Parse the arguments from the command line. In case of an unrecognized option or impossible
465 // values/combinations, a usage error will be displayed and exit() is called. Thus, if the method
466 // returns, arguments have been successfully parsed.
467 void ParseArgs(int argc, char** argv) {
468 original_argc = argc;
469 original_argv = argv;
Dave Allison70202782013-10-22 17:52:19 -0700470
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800471 InitLogging(argv);
Dave Allison70202782013-10-22 17:52:19 -0700472
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800473 // Skip over argv[0].
474 argv++;
475 argc--;
Dave Allison70202782013-10-22 17:52:19 -0700476
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800477 if (argc == 0) {
478 Usage("No arguments specified");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700479 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800480
481 std::string oat_symbols;
482 std::string boot_image_filename;
483 const char* compiler_filter_string = nullptr;
484 bool compile_pic = false;
485 int huge_method_threshold = CompilerOptions::kDefaultHugeMethodThreshold;
486 int large_method_threshold = CompilerOptions::kDefaultLargeMethodThreshold;
487 int small_method_threshold = CompilerOptions::kDefaultSmallMethodThreshold;
488 int tiny_method_threshold = CompilerOptions::kDefaultTinyMethodThreshold;
489 int num_dex_methods_threshold = CompilerOptions::kDefaultNumDexMethodsThreshold;
490
491 // Profile file to use
492 double top_k_profile_threshold = CompilerOptions::kDefaultTopKProfileThreshold;
493
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800494 bool include_patch_information = CompilerOptions::kDefaultIncludePatchInformation;
495 bool include_debug_symbols = kIsDebugBuild;
496 bool watch_dog_enabled = true;
497 bool generate_gdb_information = kIsDebugBuild;
498
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800499 PassManagerOptions pass_manager_options;
500
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800501 std::string error_msg;
502
503 for (int i = 0; i < argc; i++) {
504 const StringPiece option(argv[i]);
505 const bool log_options = false;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700506 if (log_options) {
507 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
508 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800509 if (option.starts_with("--dex-file=")) {
510 dex_filenames_.push_back(option.substr(strlen("--dex-file=")).data());
511 } else if (option.starts_with("--dex-location=")) {
512 dex_locations_.push_back(option.substr(strlen("--dex-location=")).data());
513 } else if (option.starts_with("--zip-fd=")) {
514 const char* zip_fd_str = option.substr(strlen("--zip-fd=")).data();
515 if (!ParseInt(zip_fd_str, &zip_fd_)) {
516 Usage("Failed to parse --zip-fd argument '%s' as an integer", zip_fd_str);
517 }
518 if (zip_fd_ < 0) {
519 Usage("--zip-fd passed a negative value %d", zip_fd_);
520 }
521 } else if (option.starts_with("--zip-location=")) {
522 zip_location_ = option.substr(strlen("--zip-location=")).data();
523 } else if (option.starts_with("--oat-file=")) {
524 oat_filename_ = option.substr(strlen("--oat-file=")).data();
525 } else if (option.starts_with("--oat-symbols=")) {
526 oat_symbols = option.substr(strlen("--oat-symbols=")).data();
527 } else if (option.starts_with("--oat-fd=")) {
528 const char* oat_fd_str = option.substr(strlen("--oat-fd=")).data();
529 if (!ParseInt(oat_fd_str, &oat_fd_)) {
530 Usage("Failed to parse --oat-fd argument '%s' as an integer", oat_fd_str);
531 }
532 if (oat_fd_ < 0) {
533 Usage("--oat-fd passed a negative value %d", oat_fd_);
534 }
535 } else if (option == "--watch-dog") {
536 watch_dog_enabled = true;
537 } else if (option == "--no-watch-dog") {
538 watch_dog_enabled = false;
539 } else if (option == "--gen-gdb-info") {
540 generate_gdb_information = true;
541 // Debug symbols are needed for gdb information.
542 include_debug_symbols = true;
543 } else if (option == "--no-gen-gdb-info") {
544 generate_gdb_information = false;
545 } else if (option.starts_with("-j")) {
546 const char* thread_count_str = option.substr(strlen("-j")).data();
547 if (!ParseUint(thread_count_str, &thread_count_)) {
548 Usage("Failed to parse -j argument '%s' as an integer", thread_count_str);
549 }
550 } else if (option.starts_with("--oat-location=")) {
551 oat_location_ = option.substr(strlen("--oat-location=")).data();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800552 } else if (option.starts_with("--image=")) {
553 image_filename_ = option.substr(strlen("--image=")).data();
554 } else if (option.starts_with("--image-classes=")) {
555 image_classes_filename_ = option.substr(strlen("--image-classes=")).data();
556 } else if (option.starts_with("--image-classes-zip=")) {
557 image_classes_zip_filename_ = option.substr(strlen("--image-classes-zip=")).data();
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800558 } else if (option.starts_with("--compiled-classes=")) {
559 compiled_classes_filename_ = option.substr(strlen("--compiled-classes=")).data();
560 } else if (option.starts_with("--compiled-classes-zip=")) {
561 compiled_classes_zip_filename_ = option.substr(strlen("--compiled-classes-zip=")).data();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800562 } else if (option.starts_with("--base=")) {
563 const char* image_base_str = option.substr(strlen("--base=")).data();
564 char* end;
565 image_base_ = strtoul(image_base_str, &end, 16);
566 if (end == image_base_str || *end != '\0') {
567 Usage("Failed to parse hexadecimal value for option %s", option.data());
568 }
569 } else if (option.starts_with("--boot-image=")) {
570 boot_image_filename = option.substr(strlen("--boot-image=")).data();
571 } else if (option.starts_with("--android-root=")) {
572 android_root_ = option.substr(strlen("--android-root=")).data();
573 } else if (option.starts_with("--instruction-set=")) {
574 StringPiece instruction_set_str = option.substr(strlen("--instruction-set=")).data();
575 // StringPiece is not necessarily zero-terminated, so need to make a copy and ensure it.
Dan Albert6fc59ab2014-12-11 14:09:51 -0800576 std::unique_ptr<char[]> buf(new char[instruction_set_str.length() + 1]);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800577 strncpy(buf.get(), instruction_set_str.data(), instruction_set_str.length());
578 buf.get()[instruction_set_str.length()] = 0;
579 instruction_set_ = GetInstructionSetFromString(buf.get());
580 // arm actually means thumb2.
581 if (instruction_set_ == InstructionSet::kArm) {
582 instruction_set_ = InstructionSet::kThumb2;
583 }
584 } else if (option.starts_with("--instruction-set-variant=")) {
585 StringPiece str = option.substr(strlen("--instruction-set-variant=")).data();
586 instruction_set_features_.reset(
587 InstructionSetFeatures::FromVariant(instruction_set_, str.as_string(), &error_msg));
588 if (instruction_set_features_.get() == nullptr) {
589 Usage("%s", error_msg.c_str());
590 }
591 } else if (option.starts_with("--instruction-set-features=")) {
592 StringPiece str = option.substr(strlen("--instruction-set-features=")).data();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800593 if (instruction_set_features_.get() == nullptr) {
Ian Rogersd582fa42014-11-05 23:46:43 -0800594 instruction_set_features_.reset(
595 InstructionSetFeatures::FromVariant(instruction_set_, "default", &error_msg));
596 if (instruction_set_features_.get() == nullptr) {
597 Usage("Problem initializing default instruction set features variant: %s",
598 error_msg.c_str());
599 }
600 }
601 instruction_set_features_.reset(
602 instruction_set_features_->AddFeaturesFromString(str.as_string(), &error_msg));
603 if (instruction_set_features_.get() == nullptr) {
604 Usage("Error parsing '%s': %s", option.data(), error_msg.c_str());
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800605 }
606 } else if (option.starts_with("--compiler-backend=")) {
607 StringPiece backend_str = option.substr(strlen("--compiler-backend=")).data();
608 if (backend_str == "Quick") {
609 compiler_kind_ = Compiler::kQuick;
610 } else if (backend_str == "Optimizing") {
611 compiler_kind_ = Compiler::kOptimizing;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800612 } else {
613 Usage("Unknown compiler backend: %s", backend_str.data());
614 }
615 } else if (option.starts_with("--compiler-filter=")) {
616 compiler_filter_string = option.substr(strlen("--compiler-filter=")).data();
617 } else if (option == "--compile-pic") {
618 compile_pic = true;
619 } else if (option.starts_with("--huge-method-max=")) {
620 const char* threshold = option.substr(strlen("--huge-method-max=")).data();
621 if (!ParseInt(threshold, &huge_method_threshold)) {
622 Usage("Failed to parse --huge-method-max '%s' as an integer", threshold);
623 }
624 if (huge_method_threshold < 0) {
625 Usage("--huge-method-max passed a negative value %s", huge_method_threshold);
626 }
627 } else if (option.starts_with("--large-method-max=")) {
628 const char* threshold = option.substr(strlen("--large-method-max=")).data();
629 if (!ParseInt(threshold, &large_method_threshold)) {
630 Usage("Failed to parse --large-method-max '%s' as an integer", threshold);
631 }
632 if (large_method_threshold < 0) {
633 Usage("--large-method-max passed a negative value %s", large_method_threshold);
634 }
635 } else if (option.starts_with("--small-method-max=")) {
636 const char* threshold = option.substr(strlen("--small-method-max=")).data();
637 if (!ParseInt(threshold, &small_method_threshold)) {
638 Usage("Failed to parse --small-method-max '%s' as an integer", threshold);
639 }
640 if (small_method_threshold < 0) {
641 Usage("--small-method-max passed a negative value %s", small_method_threshold);
642 }
643 } else if (option.starts_with("--tiny-method-max=")) {
644 const char* threshold = option.substr(strlen("--tiny-method-max=")).data();
645 if (!ParseInt(threshold, &tiny_method_threshold)) {
646 Usage("Failed to parse --tiny-method-max '%s' as an integer", threshold);
647 }
648 if (tiny_method_threshold < 0) {
649 Usage("--tiny-method-max passed a negative value %s", tiny_method_threshold);
650 }
651 } else if (option.starts_with("--num-dex-methods=")) {
652 const char* threshold = option.substr(strlen("--num-dex-methods=")).data();
653 if (!ParseInt(threshold, &num_dex_methods_threshold)) {
654 Usage("Failed to parse --num-dex-methods '%s' as an integer", threshold);
655 }
656 if (num_dex_methods_threshold < 0) {
657 Usage("--num-dex-methods passed a negative value %s", num_dex_methods_threshold);
658 }
659 } else if (option == "--host") {
660 is_host_ = true;
661 } else if (option == "--runtime-arg") {
662 if (++i >= argc) {
663 Usage("Missing required argument for --runtime-arg");
664 }
665 if (log_options) {
666 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
667 }
668 runtime_args_.push_back(argv[i]);
669 } else if (option == "--dump-timing") {
670 dump_timing_ = true;
671 } else if (option == "--dump-passes") {
672 dump_passes_ = true;
David Brazdil866c0312015-01-13 21:21:31 +0000673 } else if (option.starts_with("--dump-cfg=")) {
674 dump_cfg_file_name_ = option.substr(strlen("--dump-cfg=")).data();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800675 } else if (option == "--dump-stats") {
676 dump_stats_ = true;
677 } else if (option == "--include-debug-symbols" || option == "--no-strip-symbols") {
678 include_debug_symbols = true;
679 } else if (option == "--no-include-debug-symbols" || option == "--strip-symbols") {
680 include_debug_symbols = false;
681 generate_gdb_information = false; // Depends on debug symbols, see above.
682 } 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 Gampe88ec7f42014-11-05 10:18:32 -0800736 } else {
737 Usage("Unknown argument %s", option.data());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700738 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800739 }
740
Nicolas Geoffray9bb492a2014-11-25 23:42:00 +0000741 if (compiler_kind_ == Compiler::kOptimizing) {
742 // Optimizing only supports PIC mode.
743 compile_pic = true;
744 }
745
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800746 if (oat_filename_.empty() && oat_fd_ == -1) {
747 Usage("Output must be supplied with either --oat-file or --oat-fd");
748 }
749
750 if (!oat_filename_.empty() && oat_fd_ != -1) {
751 Usage("--oat-file should not be used with --oat-fd");
752 }
753
754 if (!oat_symbols.empty() && oat_fd_ != -1) {
755 Usage("--oat-symbols should not be used with --oat-fd");
756 }
757
758 if (!oat_symbols.empty() && is_host_) {
759 Usage("--oat-symbols should not be used with --host");
760 }
761
762 if (oat_fd_ != -1 && !image_filename_.empty()) {
763 Usage("--oat-fd should not be used with --image");
764 }
765
766 if (android_root_.empty()) {
767 const char* android_root_env_var = getenv("ANDROID_ROOT");
768 if (android_root_env_var == nullptr) {
769 Usage("--android-root unspecified and ANDROID_ROOT not set");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700770 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800771 android_root_ += android_root_env_var;
772 }
773
774 image_ = (!image_filename_.empty());
775 if (!image_ && boot_image_filename.empty()) {
776 boot_image_filename += android_root_;
777 boot_image_filename += "/framework/boot.art";
778 }
779 if (!boot_image_filename.empty()) {
780 boot_image_option_ += "-Ximage:";
781 boot_image_option_ += boot_image_filename;
782 }
783
784 if (image_classes_filename_ != nullptr && !image_) {
785 Usage("--image-classes should only be used with --image");
786 }
787
788 if (image_classes_filename_ != nullptr && !boot_image_option_.empty()) {
789 Usage("--image-classes should not be used with --boot-image");
790 }
791
792 if (image_classes_zip_filename_ != nullptr && image_classes_filename_ == nullptr) {
793 Usage("--image-classes-zip should be used with --image-classes");
794 }
795
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800796 if (compiled_classes_filename_ != nullptr && !image_) {
797 Usage("--compiled-classes should only be used with --image");
798 }
799
800 if (compiled_classes_filename_ != nullptr && !boot_image_option_.empty()) {
801 Usage("--compiled-classes should not be used with --boot-image");
802 }
803
804 if (compiled_classes_zip_filename_ != nullptr && compiled_classes_filename_ == nullptr) {
805 Usage("--compiled-classes-zip should be used with --compiled-classes");
806 }
807
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800808 if (dex_filenames_.empty() && zip_fd_ == -1) {
809 Usage("Input must be supplied with either --dex-file or --zip-fd");
810 }
811
812 if (!dex_filenames_.empty() && zip_fd_ != -1) {
813 Usage("--dex-file should not be used with --zip-fd");
814 }
815
816 if (!dex_filenames_.empty() && !zip_location_.empty()) {
817 Usage("--dex-file should not be used with --zip-location");
818 }
819
820 if (dex_locations_.empty()) {
821 for (const char* dex_file_name : dex_filenames_) {
822 dex_locations_.push_back(dex_file_name);
823 }
824 } else if (dex_locations_.size() != dex_filenames_.size()) {
825 Usage("--dex-location arguments do not match --dex-file arguments");
826 }
827
828 if (zip_fd_ != -1 && zip_location_.empty()) {
829 Usage("--zip-location should be supplied with --zip-fd");
830 }
831
832 if (boot_image_option_.empty()) {
833 if (image_base_ == 0) {
834 Usage("Non-zero --base not specified");
835 }
836 }
837
838 oat_stripped_ = oat_filename_;
839 if (!oat_symbols.empty()) {
840 oat_unstripped_ = oat_symbols;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700841 } else {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800842 oat_unstripped_ = oat_filename_;
843 }
844
845 // If no instruction set feature was given, use the default one for the target
846 // instruction set.
847 if (instruction_set_features_.get() == nullptr) {
848 instruction_set_features_.reset(
Ian Rogersd582fa42014-11-05 23:46:43 -0800849 InstructionSetFeatures::FromVariant(instruction_set_, "default", &error_msg));
850 if (instruction_set_features_.get() == nullptr) {
851 Usage("Problem initializing default instruction set features variant: %s",
852 error_msg.c_str());
853 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800854 }
855
856 if (instruction_set_ == kRuntimeISA) {
857 std::unique_ptr<const InstructionSetFeatures> runtime_features(
858 InstructionSetFeatures::FromCppDefines());
859 if (!instruction_set_features_->Equals(runtime_features.get())) {
860 LOG(WARNING) << "Mismatch between dex2oat instruction set features ("
861 << *instruction_set_features_ << ") and those of dex2oat executable ("
862 << *runtime_features <<") for the command line:\n"
863 << CommandLine();
864 }
865 }
866
867 if (compiler_filter_string == nullptr) {
Andreas Gampec5a3ea72015-01-13 16:41:53 -0800868 if (instruction_set_ == kMips &&
869 reinterpret_cast<const MipsInstructionSetFeatures*>(instruction_set_features_.get())->
870 IsR6()) {
871 // For R6, only interpreter mode is working.
872 // TODO: fix compiler for Mips32r6.
873 compiler_filter_string = "interpret-only";
874 } else if (instruction_set_ == kMips64) {
Andreas Gampe57b34292015-01-14 15:45:59 -0800875 // For Mips64, can only compile in interpreter mode.
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800876 // TODO: fix compiler for Mips64.
877 compiler_filter_string = "interpret-only";
878 } else if (image_) {
879 compiler_filter_string = "speed";
880 } else {
881 // TODO: Migrate SMALL mode to command line option.
882 #if ART_SMALL_MODE
883 compiler_filter_string = "interpret-only";
884 #else
885 compiler_filter_string = "speed";
886 #endif
887 }
888 }
889 CHECK(compiler_filter_string != nullptr);
890 CompilerOptions::CompilerFilter compiler_filter = CompilerOptions::kDefaultCompilerFilter;
891 if (strcmp(compiler_filter_string, "verify-none") == 0) {
892 compiler_filter = CompilerOptions::kVerifyNone;
893 } else if (strcmp(compiler_filter_string, "interpret-only") == 0) {
894 compiler_filter = CompilerOptions::kInterpretOnly;
895 } else if (strcmp(compiler_filter_string, "space") == 0) {
896 compiler_filter = CompilerOptions::kSpace;
897 } else if (strcmp(compiler_filter_string, "balanced") == 0) {
898 compiler_filter = CompilerOptions::kBalanced;
899 } else if (strcmp(compiler_filter_string, "speed") == 0) {
900 compiler_filter = CompilerOptions::kSpeed;
901 } else if (strcmp(compiler_filter_string, "everything") == 0) {
902 compiler_filter = CompilerOptions::kEverything;
903 } else if (strcmp(compiler_filter_string, "time") == 0) {
904 compiler_filter = CompilerOptions::kTime;
905 } else {
906 Usage("Unknown --compiler-filter value %s", compiler_filter_string);
907 }
908
909 // Checks are all explicit until we know the architecture.
910 bool implicit_null_checks = false;
911 bool implicit_so_checks = false;
912 bool implicit_suspend_checks = false;
913 // Set the compilation target's implicit checks options.
914 switch (instruction_set_) {
915 case kArm:
916 case kThumb2:
917 case kArm64:
918 case kX86:
919 case kX86_64:
920 implicit_null_checks = true;
921 implicit_so_checks = true;
922 break;
923
924 default:
925 // Defaults are correct.
926 break;
927 }
928
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800929 compiler_options_.reset(new CompilerOptions(compiler_filter,
930 huge_method_threshold,
931 large_method_threshold,
932 small_method_threshold,
933 tiny_method_threshold,
934 num_dex_methods_threshold,
935 generate_gdb_information,
936 include_patch_information,
937 top_k_profile_threshold,
938 include_debug_symbols,
939 implicit_null_checks,
940 implicit_so_checks,
941 implicit_suspend_checks,
942 compile_pic,
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800943 verbose_methods_.empty() ?
944 nullptr :
Andreas Gampedbfe2542014-11-25 22:21:42 -0800945 &verbose_methods_,
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800946 new PassManagerOptions(pass_manager_options),
Andreas Gampedbfe2542014-11-25 22:21:42 -0800947 init_failure_output_.get()));
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800948
949 // Done with usage checks, enable watchdog if requested
950 if (watch_dog_enabled) {
951 watchdog_.reset(new WatchDog(true));
952 }
953
954 // Fill some values into the key-value store for the oat header.
955 key_value_store_.reset(new SafeMap<std::string, std::string>());
956
957 // Insert some compiler things.
958 {
959 std::ostringstream oss;
960 for (int i = 0; i < argc; ++i) {
961 if (i > 0) {
962 oss << ' ';
963 }
964 oss << argv[i];
965 }
966 key_value_store_->Put(OatHeader::kDex2OatCmdLineKey, oss.str());
967 oss.str(""); // Reset.
968 oss << kRuntimeISA;
969 key_value_store_->Put(OatHeader::kDex2OatHostKey, oss.str());
970 key_value_store_->Put(OatHeader::kPicKey, compile_pic ? "true" : "false");
971 }
972 }
973
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800974 // Check whether the oat output file is writable, and open it for later. Also open a swap file,
975 // if a name is given.
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800976 bool OpenFile() {
977 bool create_file = !oat_unstripped_.empty(); // as opposed to using open file descriptor
978 if (create_file) {
979 oat_file_.reset(OS::CreateEmptyFile(oat_unstripped_.c_str()));
980 if (oat_location_.empty()) {
981 oat_location_ = oat_filename_;
982 }
983 } else {
Andreas Gampe4303ba92014-11-06 01:00:46 -0800984 oat_file_.reset(new File(oat_fd_, oat_location_, true));
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800985 oat_file_->DisableAutoClose();
Andreas Gampe4303ba92014-11-06 01:00:46 -0800986 if (oat_file_->SetLength(0) != 0) {
987 PLOG(WARNING) << "Truncating oat file " << oat_location_ << " failed.";
988 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800989 }
990 if (oat_file_.get() == nullptr) {
991 PLOG(ERROR) << "Failed to create oat file: " << oat_location_;
992 return false;
993 }
994 if (create_file && fchmod(oat_file_->Fd(), 0644) != 0) {
995 PLOG(ERROR) << "Failed to make oat file world readable: " << oat_location_;
Andreas Gampe4303ba92014-11-06 01:00:46 -0800996 oat_file_->Erase();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800997 return false;
998 }
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800999
1000 // Swap file handling.
1001 //
1002 // If the swap fd is not -1, we assume this is the file descriptor of an open but unlinked file
1003 // that we can use for swap.
1004 //
1005 // If the swap fd is -1 and we have a swap-file string, open the given file as a swap file. We
1006 // will immediately unlink to satisfy the swap fd assumption.
1007 if (swap_fd_ == -1 && !swap_file_name_.empty()) {
1008 std::unique_ptr<File> swap_file(OS::CreateEmptyFile(swap_file_name_.c_str()));
1009 if (swap_file.get() == nullptr) {
1010 PLOG(ERROR) << "Failed to create swap file: " << swap_file_name_;
1011 return false;
1012 }
1013 swap_fd_ = swap_file->Fd();
1014 swap_file->MarkUnchecked(); // We don't we to track this, it will be unlinked immediately.
1015 swap_file->DisableAutoClose(); // We'll handle it ourselves, the File object will be
1016 // released immediately.
1017 unlink(swap_file_name_.c_str());
1018 }
1019
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001020 return true;
1021 }
1022
Andreas Gampea650e702014-12-03 14:28:02 -08001023 void EraseOatFile() {
1024 DCHECK(oat_file_.get() != nullptr);
1025 oat_file_->Erase();
1026 oat_file_.reset();
1027 }
1028
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001029 // Set up the environment for compilation. Includes starting the runtime and loading/opening the
1030 // boot class path.
1031 bool Setup() {
1032 TimingLogger::ScopedTiming t("dex2oat Setup", timings_);
1033 RuntimeOptions runtime_options;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001034 art::MemMap::Init(); // For ZipEntry::ExtractToMemMap.
1035 if (boot_image_option_.empty()) {
Richard Uhlerc2752592015-01-02 13:28:22 -08001036 std::string boot_class_path = "-Xbootclasspath:";
1037 boot_class_path += Join(dex_filenames_, ':');
1038 runtime_options.push_back(std::make_pair(boot_class_path, nullptr));
1039 std::string boot_class_path_locations = "-Xbootclasspath-locations:";
1040 boot_class_path_locations += Join(dex_locations_, ':');
1041 runtime_options.push_back(std::make_pair(boot_class_path_locations, nullptr));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001042 } else {
Richard Uhlerc2752592015-01-02 13:28:22 -08001043 runtime_options.push_back(std::make_pair(boot_image_option_, nullptr));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001044 }
1045 for (size_t i = 0; i < runtime_args_.size(); i++) {
1046 runtime_options.push_back(std::make_pair(runtime_args_[i], nullptr));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001047 }
Brian Carlstromd76e0832013-08-29 15:17:42 -07001048
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001049 verification_results_.reset(new VerificationResults(compiler_options_.get()));
1050 callbacks_.reset(new QuickCompilerCallbacks(verification_results_.get(), &method_inliner_map_));
1051 runtime_options.push_back(std::make_pair("compilercallbacks", callbacks_.get()));
1052 runtime_options.push_back(
1053 std::make_pair("imageinstructionset", GetInstructionSetString(instruction_set_)));
1054
Andreas Gampe1d00add2015-02-27 19:35:46 -08001055 // Only allow no boot image for the runtime if we're compiling one. When we compile an app,
1056 // we don't want fallback mode, it will abort as we do not push a boot classpath (it might
1057 // have been stripped in preopting, anyways).
1058 if (!image_) {
1059 runtime_options.push_back(std::make_pair("-Xno-dex-file-fallback", nullptr));
1060 }
1061
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001062 if (!CreateRuntime(runtime_options)) {
1063 return false;
1064 }
1065
1066 // Runtime::Create acquired the mutator_lock_ that is normally given away when we
1067 // Runtime::Start, give it away now so that we don't starve GC.
1068 Thread* self = Thread::Current();
1069 self->TransitionFromRunnableToSuspended(kNative);
1070 // If we're doing the image, override the compiler filter to force full compilation. Must be
1071 // done ahead of WellKnownClasses::Init that causes verification. Note: doesn't force
1072 // compilation of class initializers.
1073 // Whilst we're in native take the opportunity to initialize well known classes.
1074 WellKnownClasses::Init(self->GetJniEnv());
1075
1076 // If --image-classes was specified, calculate the full list of classes to include in the image
1077 if (image_classes_filename_ != nullptr) {
1078 std::string error_msg;
1079 if (image_classes_zip_filename_ != nullptr) {
1080 image_classes_.reset(ReadImageClassesFromZip(image_classes_zip_filename_,
1081 image_classes_filename_,
1082 &error_msg));
1083 } else {
1084 image_classes_.reset(ReadImageClassesFromFile(image_classes_filename_));
1085 }
1086 if (image_classes_.get() == nullptr) {
1087 LOG(ERROR) << "Failed to create list of image classes from '" << image_classes_filename_ <<
1088 "': " << error_msg;
1089 return false;
1090 }
1091 } else if (image_) {
1092 image_classes_.reset(new std::set<std::string>);
1093 }
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001094 // If --compiled-classes was specified, calculate the full list of classes to compile in the
1095 // image.
1096 if (compiled_classes_filename_ != nullptr) {
1097 std::string error_msg;
1098 if (compiled_classes_zip_filename_ != nullptr) {
1099 compiled_classes_.reset(ReadImageClassesFromZip(compiled_classes_zip_filename_,
1100 compiled_classes_filename_,
1101 &error_msg));
1102 } else {
1103 compiled_classes_.reset(ReadImageClassesFromFile(compiled_classes_filename_));
1104 }
1105 if (compiled_classes_.get() == nullptr) {
1106 LOG(ERROR) << "Failed to create list of compiled classes from '"
1107 << compiled_classes_filename_ << "': " << error_msg;
1108 return false;
1109 }
1110 } else if (image_) {
1111 compiled_classes_.reset(nullptr); // By default compile everything.
1112 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001113
1114 if (boot_image_option_.empty()) {
1115 dex_files_ = Runtime::Current()->GetClassLinker()->GetBootClassPath();
1116 } else {
1117 if (dex_filenames_.empty()) {
1118 ATRACE_BEGIN("Opening zip archive from file descriptor");
1119 std::string error_msg;
1120 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(zip_fd_,
1121 zip_location_.c_str(),
1122 &error_msg));
1123 if (zip_archive.get() == nullptr) {
1124 LOG(ERROR) << "Failed to open zip from file descriptor for '" << zip_location_ << "': "
1125 << error_msg;
1126 return false;
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001127 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001128 if (!DexFile::OpenFromZip(*zip_archive.get(), zip_location_, &error_msg, &opened_dex_files_)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001129 LOG(ERROR) << "Failed to open dex from file descriptor for zip file '" << zip_location_
1130 << "': " << error_msg;
1131 return false;
1132 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001133 for (auto& dex_file : opened_dex_files_) {
1134 dex_files_.push_back(dex_file.get());
1135 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001136 ATRACE_END();
1137 } else {
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001138 size_t failure_count = OpenDexFiles(dex_filenames_, dex_locations_, &opened_dex_files_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001139 if (failure_count > 0) {
1140 LOG(ERROR) << "Failed to open some dex files: " << failure_count;
1141 return false;
1142 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001143 for (auto& dex_file : opened_dex_files_) {
1144 dex_files_.push_back(dex_file.get());
1145 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001146 }
1147
1148 constexpr bool kSaveDexInput = false;
1149 if (kSaveDexInput) {
1150 for (size_t i = 0; i < dex_files_.size(); ++i) {
1151 const DexFile* dex_file = dex_files_[i];
Brian Carlstrom95b033b2014-12-03 22:29:37 -08001152 std::string tmp_file_name(StringPrintf("/data/local/tmp/dex2oat.%d.%zd.dex",
1153 getpid(), i));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001154 std::unique_ptr<File> tmp_file(OS::CreateEmptyFile(tmp_file_name.c_str()));
1155 if (tmp_file.get() == nullptr) {
1156 PLOG(ERROR) << "Failed to open file " << tmp_file_name
1157 << ". Try: adb shell chmod 777 /data/local/tmp";
1158 continue;
1159 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001160 // This is just dumping files for debugging. Ignore errors, and leave remnants.
1161 UNUSED(tmp_file->WriteFully(dex_file->Begin(), dex_file->Size()));
1162 UNUSED(tmp_file->Flush());
1163 UNUSED(tmp_file->Close());
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001164 LOG(INFO) << "Wrote input to " << tmp_file_name;
1165 }
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001166 }
1167 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001168 // Ensure opened dex files are writable for dex-to-dex transformations.
1169 for (const auto& dex_file : dex_files_) {
1170 if (!dex_file->EnableWrite()) {
1171 PLOG(ERROR) << "Failed to make .dex file writeable '" << dex_file->GetLocation() << "'\n";
Andreas Gampe7ba64962014-10-23 11:37:40 -07001172 }
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001173 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001174
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001175 // If we use a swap file, ensure we are above the threshold to make it necessary.
1176 if (swap_fd_ != -1) {
1177 if (!UseSwap(image_, dex_files_)) {
1178 close(swap_fd_);
1179 swap_fd_ = -1;
1180 LOG(INFO) << "Decided to run without swap.";
1181 } else {
1182 LOG(INFO) << "Accepted running with swap.";
1183 }
1184 }
1185 // Note that dex2oat won't close the swap_fd_. The compiler driver's swap space will do that.
1186
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001187 /*
1188 * If we're not in interpret-only or verify-none mode, go ahead and compile small applications.
1189 * Don't bother to check if we're doing the image.
1190 */
Brian Carlstrom95b033b2014-12-03 22:29:37 -08001191 if (!image_ &&
1192 compiler_options_->IsCompilationEnabled() &&
1193 compiler_kind_ == Compiler::kQuick) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001194 size_t num_methods = 0;
1195 for (size_t i = 0; i != dex_files_.size(); ++i) {
1196 const DexFile* dex_file = dex_files_[i];
1197 CHECK(dex_file != nullptr);
1198 num_methods += dex_file->NumMethodIds();
1199 }
1200 if (num_methods <= compiler_options_->GetNumDexMethodsThreshold()) {
1201 compiler_options_->SetCompilerFilter(CompilerOptions::kSpeed);
1202 VLOG(compiler) << "Below method threshold, compiling anyways";
1203 }
1204 }
1205
1206 return true;
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001207 }
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001208
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001209 // Create and invoke the compiler driver. This will compile all the dex files.
1210 void Compile() {
1211 TimingLogger::ScopedTiming t("dex2oat Compile", timings_);
1212 compiler_phases_timings_.reset(new CumulativeLogger("compilation times"));
Vladimir Markof4da6752014-08-01 19:04:18 +01001213
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001214 // Handle and ClassLoader creation needs to come after Runtime::Create
1215 jobject class_loader = nullptr;
1216 Thread* self = Thread::Current();
1217 if (!boot_image_option_.empty()) {
1218 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001219 OpenClassPathFiles(runtime_->GetClassPathString(), dex_files_, &class_path_files_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001220 ScopedObjectAccess soa(self);
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001221 std::vector<const DexFile*> class_path_files(dex_files_);
1222 for (auto& class_path_file : class_path_files_) {
1223 class_path_files.push_back(class_path_file.get());
1224 }
1225
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001226 for (size_t i = 0; i < class_path_files.size(); i++) {
1227 class_linker->RegisterDexFile(*class_path_files[i]);
1228 }
1229 soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader);
1230 ScopedLocalRef<jobject> class_loader_local(soa.Env(),
1231 soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader));
1232 class_loader = soa.Env()->NewGlobalRef(class_loader_local.get());
1233 Runtime::Current()->SetCompileTimeClassPath(class_loader, class_path_files);
1234 }
1235
1236 driver_.reset(new CompilerDriver(compiler_options_.get(),
1237 verification_results_.get(),
1238 &method_inliner_map_,
1239 compiler_kind_,
1240 instruction_set_,
1241 instruction_set_features_.get(),
1242 image_,
1243 image_classes_.release(),
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001244 compiled_classes_.release(),
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001245 thread_count_,
1246 dump_stats_,
1247 dump_passes_,
David Brazdil866c0312015-01-13 21:21:31 +00001248 dump_cfg_file_name_,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001249 compiler_phases_timings_.get(),
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001250 swap_fd_,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001251 profile_file_));
1252
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001253 driver_->CompileAll(class_loader, dex_files_, timings_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001254 }
1255
Brian Carlstrom7940e442013-07-12 13:46:57 -07001256 // Notes on the interleaving of creating the image and oat file to
1257 // ensure the references between the two are correct.
1258 //
1259 // Currently we have a memory layout that looks something like this:
1260 //
1261 // +--------------+
1262 // | image |
1263 // +--------------+
1264 // | boot oat |
1265 // +--------------+
1266 // | alloc spaces |
1267 // +--------------+
1268 //
Brian Carlstrom45602482013-07-21 22:07:55 -07001269 // There are several constraints on the loading of the image and boot.oat.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001270 //
1271 // 1. The image is expected to be loaded at an absolute address and
1272 // contains Objects with absolute pointers within the image.
1273 //
1274 // 2. There are absolute pointers from Methods in the image to their
1275 // code in the oat.
1276 //
1277 // 3. There are absolute pointers from the code in the oat to Methods
1278 // in the image.
1279 //
1280 // 4. There are absolute pointers from code in the oat to other code
1281 // in the oat.
1282 //
1283 // To get this all correct, we go through several steps.
1284 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001285 // 1. We prepare offsets for all data in the oat file and calculate
1286 // the oat data size and code size. During this stage, we also set
1287 // oat code offsets in methods for use by the image writer.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001288 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001289 // 2. We prepare offsets for the objects in the image and calculate
1290 // the image size.
1291 //
1292 // 3. We create the oat file. Originally this was just our own proprietary
1293 // file but now it is contained within an ELF dynamic object (aka an .so
1294 // file). Since we know the image size and oat data size and code size we
1295 // can prepare the ELF headers and we then know the ELF memory segment
1296 // layout and we can now resolve all references. The compiler provides
1297 // LinkerPatch information in each CompiledMethod and we resolve these,
1298 // using the layout information and image object locations provided by
1299 // image writer, as we're writing the method code.
1300 //
1301 // 4. We create the image file. It needs to know where the oat file
Brian Carlstrom7940e442013-07-12 13:46:57 -07001302 // will be loaded after itself. Originally when oat file was simply
1303 // memory mapped so we could predict where its contents were based
1304 // on the file size. Now that it is an ELF file, we need to inspect
1305 // the ELF file to understand the in memory segment layout including
Vladimir Markof4da6752014-08-01 19:04:18 +01001306 // where the oat header is located within.
1307 // TODO: We could just remember this information from step 3.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001308 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001309 // 5. We fixup the ELF program headers so that dlopen will try to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001310 // load the .so at the desired location at runtime by offsetting the
1311 // Elf32_Phdr.p_vaddr values by the desired base address.
Vladimir Markof4da6752014-08-01 19:04:18 +01001312 // TODO: Do this in step 3. We already know the layout there.
1313 //
1314 // Steps 1.-3. are done by the CreateOatFile() above, steps 4.-5.
1315 // are done by the CreateImageFile() below.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001316
1317
1318 // Write out the generated code part. Calls the OatWriter and ElfBuilder. Also prepares the
1319 // ImageWriter, if necessary.
Andreas Gampe10e477d2014-11-19 12:57:42 -08001320 // Note: Flushing (and closing) the file is the caller's responsibility, except for the failure
1321 // case (when the file will be explicitly erased).
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001322 bool CreateOatFile() {
1323 CHECK(key_value_store_.get() != nullptr);
1324
1325 TimingLogger::ScopedTiming t("dex2oat Oat", timings_);
1326
1327 std::unique_ptr<OatWriter> oat_writer;
1328 {
1329 TimingLogger::ScopedTiming t2("dex2oat OatWriter", timings_);
1330 std::string image_file_location;
1331 uint32_t image_file_location_oat_checksum = 0;
1332 uintptr_t image_file_location_oat_data_begin = 0;
1333 int32_t image_patch_delta = 0;
1334 if (image_) {
1335 PrepareImageWriter(image_base_);
1336 } else {
1337 TimingLogger::ScopedTiming t3("Loading image checksum", timings_);
1338 gc::space::ImageSpace* image_space = Runtime::Current()->GetHeap()->GetImageSpace();
1339 image_file_location_oat_checksum = image_space->GetImageHeader().GetOatChecksum();
1340 image_file_location_oat_data_begin =
1341 reinterpret_cast<uintptr_t>(image_space->GetImageHeader().GetOatDataBegin());
1342 image_file_location = image_space->GetImageFilename();
1343 image_patch_delta = image_space->GetImageHeader().GetPatchDelta();
1344 }
1345
1346 if (!image_file_location.empty()) {
1347 key_value_store_->Put(OatHeader::kImageLocationKey, image_file_location);
1348 }
1349
1350 oat_writer.reset(new OatWriter(dex_files_, image_file_location_oat_checksum,
1351 image_file_location_oat_data_begin,
1352 image_patch_delta,
1353 driver_.get(),
1354 image_writer_.get(),
1355 timings_,
1356 key_value_store_.get()));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001357 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001358
1359 if (image_) {
1360 // The OatWriter constructor has already updated offsets in methods and we need to
1361 // prepare method offsets in the image address space for direct method patching.
1362 TimingLogger::ScopedTiming t2("dex2oat Prepare image address space", timings_);
1363 if (!image_writer_->PrepareImageAddressSpace()) {
1364 LOG(ERROR) << "Failed to prepare image address space.";
1365 return false;
1366 }
1367 }
1368
1369 {
1370 TimingLogger::ScopedTiming t2("dex2oat Write ELF", timings_);
1371 if (!driver_->WriteElf(android_root_, is_host_, dex_files_, oat_writer.get(),
1372 oat_file_.get())) {
1373 LOG(ERROR) << "Failed to write ELF file " << oat_file_->GetPath();
1374 return false;
1375 }
1376 }
1377
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001378 VLOG(compiler) << "Oat file written successfully (unstripped): " << oat_location_;
1379 return true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001380 }
1381
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001382 // If we are compiling an image, invoke the image creation routine. Else just skip.
1383 bool HandleImage() {
1384 if (image_) {
1385 TimingLogger::ScopedTiming t("dex2oat ImageWriter", timings_);
1386 if (!CreateImageFile()) {
1387 return false;
1388 }
1389 VLOG(compiler) << "Image written successfully: " << image_filename_;
Brian Carlstrom45602482013-07-21 22:07:55 -07001390 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001391 return true;
1392 }
1393
Andreas Gampe10e477d2014-11-19 12:57:42 -08001394 // Create a copy from unstripped to stripped.
1395 bool CopyUnstrippedToStripped() {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001396 // If we don't want to strip in place, copy from unstripped location to stripped location.
1397 // We need to strip after image creation because FixupElf needs to use .strtab.
1398 if (oat_unstripped_ != oat_stripped_) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08001399 // If the oat file is still open, flush it.
1400 if (oat_file_.get() != nullptr && oat_file_->IsOpened()) {
1401 if (!FlushCloseOatFile()) {
1402 return false;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001403 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001404 }
Andreas Gampe10e477d2014-11-19 12:57:42 -08001405
1406 TimingLogger::ScopedTiming t("dex2oat OatFile copy", timings_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001407 std::unique_ptr<File> in(OS::OpenFileForReading(oat_unstripped_.c_str()));
1408 std::unique_ptr<File> out(OS::CreateEmptyFile(oat_stripped_.c_str()));
1409 size_t buffer_size = 8192;
Dan Albert6fc59ab2014-12-11 14:09:51 -08001410 std::unique_ptr<uint8_t[]> buffer(new uint8_t[buffer_size]);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001411 while (true) {
1412 int bytes_read = TEMP_FAILURE_RETRY(read(in->Fd(), buffer.get(), buffer_size));
1413 if (bytes_read <= 0) {
1414 break;
1415 }
1416 bool write_ok = out->WriteFully(buffer.get(), bytes_read);
1417 CHECK(write_ok);
1418 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08001419 if (out->FlushCloseOrErase() != 0) {
1420 PLOG(ERROR) << "Failed to flush and close copied oat file: " << oat_stripped_;
1421 return false;
Andreas Gampe10e477d2014-11-19 12:57:42 -08001422 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001423 VLOG(compiler) << "Oat file copied successfully (stripped): " << oat_stripped_;
Nicolas Geoffrayea3fa0b2014-02-10 11:59:41 +00001424 }
Andreas Gampe10e477d2014-11-19 12:57:42 -08001425 return true;
1426 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001427
Andreas Gampe10e477d2014-11-19 12:57:42 -08001428 bool FlushOatFile() {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001429 if (oat_file_.get() != nullptr) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08001430 TimingLogger::ScopedTiming t2("dex2oat Flush ELF", timings_);
1431 if (oat_file_->Flush() != 0) {
1432 PLOG(ERROR) << "Failed to flush oat file: " << oat_location_ << " / "
1433 << oat_filename_;
1434 oat_file_->Erase();
1435 return false;
1436 }
1437 }
1438 return true;
1439 }
1440
1441 bool FlushCloseOatFile() {
1442 if (oat_file_.get() != nullptr) {
1443 std::unique_ptr<File> tmp(oat_file_.release());
1444 if (tmp->FlushCloseOrErase() != 0) {
1445 PLOG(ERROR) << "Failed to flush and close oat file: " << oat_location_ << " / "
1446 << oat_filename_;
1447 return false;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001448 }
1449 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001450 return true;
1451 }
1452
1453 void DumpTiming() {
1454 if (dump_timing_ || (dump_slow_timing_ && timings_->GetTotalNs() > MsToNs(1000))) {
1455 LOG(INFO) << Dumpable<TimingLogger>(*timings_);
1456 }
1457 if (dump_passes_) {
1458 LOG(INFO) << Dumpable<CumulativeLogger>(*driver_->GetTimingsLogger());
1459 }
1460 }
1461
1462 CompilerOptions* GetCompilerOptions() const {
1463 return compiler_options_.get();
1464 }
1465
Andreas Gampe10e477d2014-11-19 12:57:42 -08001466 bool IsImage() const {
1467 return image_;
1468 }
1469
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001470 bool IsHost() const {
1471 return is_host_;
1472 }
1473
1474 private:
1475 static size_t OpenDexFiles(const std::vector<const char*>& dex_filenames,
1476 const std::vector<const char*>& dex_locations,
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001477 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
1478 DCHECK(dex_files != nullptr) << "OpenDexFiles out-param is NULL";
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001479 size_t failure_count = 0;
1480 for (size_t i = 0; i < dex_filenames.size(); i++) {
1481 const char* dex_filename = dex_filenames[i];
1482 const char* dex_location = dex_locations[i];
1483 ATRACE_BEGIN(StringPrintf("Opening dex file '%s'", dex_filenames[i]).c_str());
1484 std::string error_msg;
1485 if (!OS::FileExists(dex_filename)) {
1486 LOG(WARNING) << "Skipping non-existent dex file '" << dex_filename << "'";
1487 continue;
1488 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001489 if (!DexFile::Open(dex_filename, dex_location, &error_msg, dex_files)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001490 LOG(WARNING) << "Failed to open .dex from file '" << dex_filename << "': " << error_msg;
1491 ++failure_count;
1492 }
1493 ATRACE_END();
1494 }
1495 return failure_count;
1496 }
1497
1498 // Returns true if dex_files has a dex with the named location.
1499 static bool DexFilesContains(const std::vector<const DexFile*>& dex_files,
1500 const std::string& location) {
1501 for (size_t i = 0; i < dex_files.size(); ++i) {
1502 if (dex_files[i]->GetLocation() == location) {
1503 return true;
1504 }
1505 }
1506 return false;
1507 }
1508
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001509 // Appends to opened_dex_files any elements of class_path that dex_files
1510 // doesn't already contain. This will open those dex files as necessary.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001511 static void OpenClassPathFiles(const std::string& class_path,
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001512 std::vector<const DexFile*> dex_files,
1513 std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
1514 DCHECK(opened_dex_files != nullptr) << "OpenClassPathFiles out-param is NULL";
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001515 std::vector<std::string> parsed;
1516 Split(class_path, ':', &parsed);
1517 // Take Locks::mutator_lock_ so that lock ordering on the ClassLinker::dex_lock_ is maintained.
1518 ScopedObjectAccess soa(Thread::Current());
1519 for (size_t i = 0; i < parsed.size(); ++i) {
1520 if (DexFilesContains(dex_files, parsed[i])) {
1521 continue;
1522 }
1523 std::string error_msg;
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001524 if (!DexFile::Open(parsed[i].c_str(), parsed[i].c_str(), &error_msg, opened_dex_files)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001525 LOG(WARNING) << "Failed to open dex file '" << parsed[i] << "': " << error_msg;
1526 }
1527 }
1528 }
1529
1530 // Create a runtime necessary for compilation.
1531 bool CreateRuntime(const RuntimeOptions& runtime_options)
1532 SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_) {
1533 if (!Runtime::Create(runtime_options, false)) {
1534 LOG(ERROR) << "Failed to create runtime";
1535 return false;
1536 }
1537 Runtime* runtime = Runtime::Current();
1538 runtime->SetInstructionSet(instruction_set_);
1539 for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
1540 Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i);
1541 if (!runtime->HasCalleeSaveMethod(type)) {
1542 runtime->SetCalleeSaveMethod(runtime->CreateCalleeSaveMethod(), type);
1543 }
1544 }
1545 runtime->GetClassLinker()->FixupDexCaches(runtime->GetResolutionMethod());
1546 runtime->GetClassLinker()->RunRootClinits();
1547 runtime_ = runtime;
1548 return true;
1549 }
1550
1551 void PrepareImageWriter(uintptr_t image_base) {
1552 image_writer_.reset(new ImageWriter(*driver_, image_base, compiler_options_->GetCompilePic()));
1553 }
1554
1555 // Let the ImageWriter write the image file. If we do not compile PIC, also fix up the oat file.
1556 bool CreateImageFile()
1557 LOCKS_EXCLUDED(Locks::mutator_lock_) {
1558 CHECK(image_writer_ != nullptr);
1559 if (!image_writer_->Write(image_filename_, oat_unstripped_, oat_location_)) {
1560 LOG(ERROR) << "Failed to create image file " << image_filename_;
1561 return false;
1562 }
1563 uintptr_t oat_data_begin = image_writer_->GetOatDataBegin();
1564
1565 // Destroy ImageWriter before doing FixupElf.
1566 image_writer_.reset();
1567
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001568 // Do not fix up the ELF file if we are --compile-pic
1569 if (!compiler_options_->GetCompilePic()) {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001570 std::unique_ptr<File> oat_file(OS::OpenFileReadWrite(oat_unstripped_.c_str()));
1571 if (oat_file.get() == nullptr) {
1572 PLOG(ERROR) << "Failed to open ELF file: " << oat_unstripped_;
1573 return false;
1574 }
1575
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001576 if (!ElfWriter::Fixup(oat_file.get(), oat_data_begin)) {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001577 oat_file->Erase();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001578 LOG(ERROR) << "Failed to fixup ELF file " << oat_file->GetPath();
1579 return false;
1580 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001581
1582 if (oat_file->FlushCloseOrErase()) {
1583 PLOG(ERROR) << "Failed to flush and close fixed ELF file " << oat_file->GetPath();
1584 return false;
1585 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001586 }
1587
1588 return true;
1589 }
1590
1591 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
1592 static std::set<std::string>* ReadImageClassesFromFile(const char* image_classes_filename) {
1593 std::unique_ptr<std::ifstream> image_classes_file(new std::ifstream(image_classes_filename,
1594 std::ifstream::in));
1595 if (image_classes_file.get() == nullptr) {
1596 LOG(ERROR) << "Failed to open image classes file " << image_classes_filename;
1597 return nullptr;
1598 }
1599 std::unique_ptr<std::set<std::string>> result(ReadImageClasses(*image_classes_file));
1600 image_classes_file->close();
1601 return result.release();
1602 }
1603
1604 static std::set<std::string>* ReadImageClasses(std::istream& image_classes_stream) {
1605 std::unique_ptr<std::set<std::string>> image_classes(new std::set<std::string>);
1606 while (image_classes_stream.good()) {
1607 std::string dot;
1608 std::getline(image_classes_stream, dot);
1609 if (StartsWith(dot, "#") || dot.empty()) {
1610 continue;
1611 }
1612 std::string descriptor(DotToDescriptor(dot.c_str()));
1613 image_classes->insert(descriptor);
1614 }
1615 return image_classes.release();
1616 }
1617
1618 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
1619 static std::set<std::string>* ReadImageClassesFromZip(const char* zip_filename,
1620 const char* image_classes_filename,
1621 std::string* error_msg) {
1622 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::Open(zip_filename, error_msg));
1623 if (zip_archive.get() == nullptr) {
1624 return nullptr;
1625 }
1626 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(image_classes_filename, error_msg));
1627 if (zip_entry.get() == nullptr) {
1628 *error_msg = StringPrintf("Failed to find '%s' within '%s': %s", image_classes_filename,
1629 zip_filename, error_msg->c_str());
1630 return nullptr;
1631 }
1632 std::unique_ptr<MemMap> image_classes_file(zip_entry->ExtractToMemMap(zip_filename,
1633 image_classes_filename,
1634 error_msg));
1635 if (image_classes_file.get() == nullptr) {
1636 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", image_classes_filename,
1637 zip_filename, error_msg->c_str());
1638 return nullptr;
1639 }
1640 const std::string image_classes_string(reinterpret_cast<char*>(image_classes_file->Begin()),
1641 image_classes_file->Size());
1642 std::istringstream image_classes_stream(image_classes_string);
1643 return ReadImageClasses(image_classes_stream);
1644 }
1645
Mathieu Chartier49285c52014-12-02 15:43:48 -08001646 void LogCompletionTime() {
Andreas Gampe1d00add2015-02-27 19:35:46 -08001647 // Note: when creation of a runtime fails, e.g., when trying to compile an app but when there
1648 // is no image, there won't be a Runtime::Current().
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001649 LOG(INFO) << "dex2oat took " << PrettyDuration(NanoTime() - start_ns_)
Mathieu Chartierab972ef2014-12-03 17:38:22 -08001650 << " (threads: " << thread_count_ << ") "
Andreas Gampe1d00add2015-02-27 19:35:46 -08001651 << ((Runtime::Current() != nullptr) ?
1652 driver_->GetMemoryUsageString(kIsDebugBuild || VLOG_IS_ON(compiler)) :
1653 "");
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001654 }
1655
1656 std::unique_ptr<CompilerOptions> compiler_options_;
1657 Compiler::Kind compiler_kind_;
1658
1659 InstructionSet instruction_set_;
1660 std::unique_ptr<const InstructionSetFeatures> instruction_set_features_;
1661
1662 std::unique_ptr<SafeMap<std::string, std::string> > key_value_store_;
1663
1664 std::unique_ptr<VerificationResults> verification_results_;
1665 DexFileToMethodInlinerMap method_inliner_map_;
1666 std::unique_ptr<QuickCompilerCallbacks> callbacks_;
1667
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001668 // Ownership for the class path files.
1669 std::vector<std::unique_ptr<const DexFile>> class_path_files_;
1670
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001671 // Not a unique_ptr as we want to just exit on non-debug builds, not bringing the runtime down
1672 // in an orderly fashion. The destructor takes care of deleting this.
1673 Runtime* runtime_;
1674
1675 size_t thread_count_;
1676 uint64_t start_ns_;
1677 std::unique_ptr<WatchDog> watchdog_;
1678 std::unique_ptr<File> oat_file_;
1679 std::string oat_stripped_;
1680 std::string oat_unstripped_;
1681 std::string oat_location_;
1682 std::string oat_filename_;
1683 int oat_fd_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001684 std::vector<const char*> dex_filenames_;
1685 std::vector<const char*> dex_locations_;
1686 int zip_fd_;
1687 std::string zip_location_;
1688 std::string boot_image_option_;
1689 std::vector<const char*> runtime_args_;
1690 std::string image_filename_;
1691 uintptr_t image_base_;
1692 const char* image_classes_zip_filename_;
1693 const char* image_classes_filename_;
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001694 const char* compiled_classes_zip_filename_;
1695 const char* compiled_classes_filename_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001696 std::unique_ptr<std::set<std::string>> image_classes_;
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001697 std::unique_ptr<std::set<std::string>> compiled_classes_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001698 bool image_;
1699 std::unique_ptr<ImageWriter> image_writer_;
1700 bool is_host_;
1701 std::string android_root_;
1702 std::vector<const DexFile*> dex_files_;
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001703 std::vector<std::unique_ptr<const DexFile>> opened_dex_files_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001704 std::unique_ptr<CompilerDriver> driver_;
1705 std::vector<std::string> verbose_methods_;
1706 bool dump_stats_;
1707 bool dump_passes_;
1708 bool dump_timing_;
1709 bool dump_slow_timing_;
David Brazdil866c0312015-01-13 21:21:31 +00001710 std::string dump_cfg_file_name_;
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001711 std::string swap_file_name_;
1712 int swap_fd_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001713 std::string profile_file_; // Profile file to use
1714 TimingLogger* timings_;
1715 std::unique_ptr<CumulativeLogger> compiler_phases_timings_;
Andreas Gampedbfe2542014-11-25 22:21:42 -08001716 std::unique_ptr<std::ostream> init_failure_output_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001717
1718 DISALLOW_IMPLICIT_CONSTRUCTORS(Dex2Oat);
1719};
1720
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001721const unsigned int WatchDog::kWatchDogTimeoutSeconds;
1722
1723static void b13564922() {
1724#if defined(__linux__) && defined(__arm__)
1725 int major, minor;
1726 struct utsname uts;
1727 if (uname(&uts) != -1 &&
1728 sscanf(uts.release, "%d.%d", &major, &minor) == 2 &&
1729 ((major < 3) || ((major == 3) && (minor < 4)))) {
1730 // Kernels before 3.4 don't handle the ASLR well and we can run out of address
1731 // space (http://b/13564922). Work around the issue by inhibiting further mmap() randomization.
1732 int old_personality = personality(0xffffffff);
1733 if ((old_personality & ADDR_NO_RANDOMIZE) == 0) {
1734 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
1735 if (new_personality == -1) {
1736 LOG(WARNING) << "personality(. | ADDR_NO_RANDOMIZE) failed.";
1737 }
1738 }
1739 }
1740#endif
1741}
1742
Andreas Gampe10e477d2014-11-19 12:57:42 -08001743static int CompileImage(Dex2Oat& dex2oat) {
1744 dex2oat.Compile();
1745
1746 // Create the boot.oat.
1747 if (!dex2oat.CreateOatFile()) {
Andreas Gampea650e702014-12-03 14:28:02 -08001748 dex2oat.EraseOatFile();
Andreas Gampe10e477d2014-11-19 12:57:42 -08001749 return EXIT_FAILURE;
1750 }
1751
1752 // Flush and close the boot.oat. We always expect the output file by name, and it will be
1753 // re-opened from the unstripped name.
1754 if (!dex2oat.FlushCloseOatFile()) {
1755 return EXIT_FAILURE;
1756 }
1757
1758 // Creates the boot.art and patches the boot.oat.
1759 if (!dex2oat.HandleImage()) {
1760 return EXIT_FAILURE;
1761 }
1762
1763 // When given --host, finish early without stripping.
1764 if (dex2oat.IsHost()) {
1765 dex2oat.DumpTiming();
1766 return EXIT_SUCCESS;
1767 }
1768
1769 // Copy unstripped to stripped location, if necessary.
1770 if (!dex2oat.CopyUnstrippedToStripped()) {
1771 return EXIT_FAILURE;
1772 }
1773
Andreas Gampe10e477d2014-11-19 12:57:42 -08001774 // FlushClose again, as stripping might have re-opened the oat file.
1775 if (!dex2oat.FlushCloseOatFile()) {
1776 return EXIT_FAILURE;
1777 }
1778
1779 dex2oat.DumpTiming();
1780 return EXIT_SUCCESS;
1781}
1782
1783static int CompileApp(Dex2Oat& dex2oat) {
1784 dex2oat.Compile();
1785
1786 // Create the app oat.
1787 if (!dex2oat.CreateOatFile()) {
Andreas Gampea650e702014-12-03 14:28:02 -08001788 dex2oat.EraseOatFile();
Andreas Gampe10e477d2014-11-19 12:57:42 -08001789 return EXIT_FAILURE;
1790 }
1791
1792 // Do not close the oat file here. We might haven gotten the output file by file descriptor,
1793 // which we would lose.
1794 if (!dex2oat.FlushOatFile()) {
1795 return EXIT_FAILURE;
1796 }
1797
1798 // When given --host, finish early without stripping.
1799 if (dex2oat.IsHost()) {
1800 if (!dex2oat.FlushCloseOatFile()) {
1801 return EXIT_FAILURE;
1802 }
1803
1804 dex2oat.DumpTiming();
1805 return EXIT_SUCCESS;
1806 }
1807
1808 // Copy unstripped to stripped location, if necessary. This will implicitly flush & close the
1809 // unstripped version. If this is given, we expect to be able to open writable files by name.
1810 if (!dex2oat.CopyUnstrippedToStripped()) {
1811 return EXIT_FAILURE;
1812 }
1813
Andreas Gampe10e477d2014-11-19 12:57:42 -08001814 // Flush and close the file.
1815 if (!dex2oat.FlushCloseOatFile()) {
1816 return EXIT_FAILURE;
1817 }
1818
1819 dex2oat.DumpTiming();
1820 return EXIT_SUCCESS;
1821}
1822
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001823static int dex2oat(int argc, char** argv) {
1824 b13564922();
1825
1826 TimingLogger timings("compiler", false, false);
1827
1828 Dex2Oat dex2oat(&timings);
1829
1830 // Parse arguments. Argument mistakes will lead to exit(EXIT_FAILURE) in UsageError.
1831 dex2oat.ParseArgs(argc, argv);
1832
1833 // Check early that the result of compilation can be written
1834 if (!dex2oat.OpenFile()) {
1835 return EXIT_FAILURE;
1836 }
1837
1838 LOG(INFO) << CommandLine();
1839
1840 if (!dex2oat.Setup()) {
Andreas Gampea650e702014-12-03 14:28:02 -08001841 dex2oat.EraseOatFile();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001842 return EXIT_FAILURE;
1843 }
1844
Andreas Gampe10e477d2014-11-19 12:57:42 -08001845 if (dex2oat.IsImage()) {
1846 return CompileImage(dex2oat);
1847 } else {
1848 return CompileApp(dex2oat);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001849 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001850}
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001851} // namespace art
Brian Carlstrom7940e442013-07-12 13:46:57 -07001852
1853int main(int argc, char** argv) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001854 int result = art::dex2oat(argc, argv);
1855 // Everything was done, do an explicit exit here to avoid running Runtime destructors that take
1856 // time (bug 10645725) unless we're a debug build or running on valgrind. Note: The Dex2Oat class
1857 // should not destruct the runtime in this case.
1858 if (!art::kIsDebugBuild && (RUNNING_ON_VALGRIND == 0)) {
1859 exit(result);
1860 }
1861 return result;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001862}