blob: 67c96fd63bb1967eeebd51b90da4655bbf848f98 [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"
Andreas Gampe2969bcd2015-03-09 12:57:41 -070059#include "interpreter/unstarted_runtime.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070060#include "leb128.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070061#include "mirror/art_method-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070062#include "mirror/class-inl.h"
63#include "mirror/class_loader.h"
64#include "mirror/object-inl.h"
65#include "mirror/object_array-inl.h"
66#include "oat_writer.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070067#include "os.h"
68#include "runtime.h"
69#include "ScopedLocalRef.h"
70#include "scoped_thread_state_change.h"
Alex Light53cb16b2014-06-12 11:26:29 -070071#include "utils.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070072#include "vector_output_stream.h"
73#include "well_known_classes.h"
74#include "zip_archive.h"
75
76namespace art {
77
Brian Carlstrom6449c622014-02-10 23:48:36 -080078static int original_argc;
79static char** original_argv;
80
81static std::string CommandLine() {
82 std::vector<std::string> command;
83 for (int i = 0; i < original_argc; ++i) {
84 command.push_back(original_argv[i]);
85 }
86 return Join(command, ' ');
87}
88
Brian Carlstrom7940e442013-07-12 13:46:57 -070089static void UsageErrorV(const char* fmt, va_list ap) {
90 std::string error;
91 StringAppendV(&error, fmt, ap);
92 LOG(ERROR) << error;
93}
94
95static void UsageError(const char* fmt, ...) {
96 va_list ap;
97 va_start(ap, fmt);
98 UsageErrorV(fmt, ap);
99 va_end(ap);
100}
101
Andreas Gampe794ad762015-02-23 08:12:24 -0800102NO_RETURN static void Usage(const char* fmt, ...) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700103 va_list ap;
104 va_start(ap, fmt);
105 UsageErrorV(fmt, ap);
106 va_end(ap);
107
Brian Carlstrom6449c622014-02-10 23:48:36 -0800108 UsageError("Command: %s", CommandLine().c_str());
109
Brian Carlstrom7940e442013-07-12 13:46:57 -0700110 UsageError("Usage: dex2oat [options]...");
111 UsageError("");
112 UsageError(" --dex-file=<dex-file>: specifies a .dex file to compile.");
113 UsageError(" Example: --dex-file=/system/framework/core.jar");
114 UsageError("");
115 UsageError(" --zip-fd=<file-descriptor>: specifies a file descriptor of a zip file");
116 UsageError(" containing a classes.dex file to compile.");
117 UsageError(" Example: --zip-fd=5");
118 UsageError("");
Brian Carlstrom45602482013-07-21 22:07:55 -0700119 UsageError(" --zip-location=<zip-location>: specifies a symbolic name for the file");
120 UsageError(" corresponding to the file descriptor specified by --zip-fd.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700121 UsageError(" Example: --zip-location=/system/app/Calculator.apk");
122 UsageError("");
123 UsageError(" --oat-file=<file.oat>: specifies the oat output destination via a filename.");
124 UsageError(" Example: --oat-file=/system/framework/boot.oat");
125 UsageError("");
126 UsageError(" --oat-fd=<number>: specifies the oat output destination via a file descriptor.");
Wonil Kim9cb554a2014-04-28 11:26:55 +0900127 UsageError(" Example: --oat-fd=6");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700128 UsageError("");
129 UsageError(" --oat-location=<oat-name>: specifies a symbolic name for the file corresponding");
130 UsageError(" to the file descriptor specified by --oat-fd.");
131 UsageError(" Example: --oat-location=/data/dalvik-cache/system@app@Calculator.apk.oat");
132 UsageError("");
133 UsageError(" --oat-symbols=<file.oat>: specifies the oat output destination with full symbols.");
134 UsageError(" Example: --oat-symbols=/symbols/system/framework/boot.oat");
135 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700136 UsageError(" --image=<file.art>: specifies the output image filename.");
137 UsageError(" Example: --image=/system/framework/boot.art");
138 UsageError("");
139 UsageError(" --image-classes=<classname-file>: specifies classes to include in an image.");
140 UsageError(" Example: --image=frameworks/base/preloaded-classes");
141 UsageError("");
142 UsageError(" --base=<hex-address>: specifies the base address when creating a boot image.");
143 UsageError(" Example: --base=0x50000000");
144 UsageError("");
145 UsageError(" --boot-image=<file.art>: provide the image file for the boot class path.");
146 UsageError(" Example: --boot-image=/system/framework/boot.art");
Nicolas Geoffray9583fbc2014-02-28 15:21:07 +0000147 UsageError(" Default: $ANDROID_ROOT/system/framework/boot.art");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700148 UsageError("");
149 UsageError(" --android-root=<path>: used to locate libraries for portable linking.");
150 UsageError(" Example: --android-root=out/host/linux-x86");
151 UsageError(" Default: $ANDROID_ROOT");
152 UsageError("");
Andreas Gampe57b34292015-01-14 15:45:59 -0800153 UsageError(" --instruction-set=(arm|arm64|mips|mips64|x86|x86_64): compile for a particular");
Alex Light53cb16b2014-06-12 11:26:29 -0700154 UsageError(" instruction set.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700155 UsageError(" Example: --instruction-set=x86");
156 UsageError(" Default: arm");
157 UsageError("");
Dave Allison70202782013-10-22 17:52:19 -0700158 UsageError(" --instruction-set-features=...,: Specify instruction set features");
159 UsageError(" Example: --instruction-set-features=div");
160 UsageError(" Default: default");
161 UsageError("");
Igor Murashkin46774762014-10-22 11:37:02 -0700162 UsageError(" --compile-pic: Force indirect use of code, methods, and classes");
163 UsageError(" Default: disabled");
164 UsageError("");
Elliott Hughes956af0f2014-12-11 14:34:28 -0800165 UsageError(" --compiler-backend=(Quick|Optimizing): select compiler backend");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700166 UsageError(" set.");
Elliott Hughes956af0f2014-12-11 14:34:28 -0800167 UsageError(" Example: --compiler-backend=Optimizing");
168 if (kUseOptimizingCompiler) {
Nicolas Geoffray4586fb62014-11-28 16:22:11 +0000169 UsageError(" Default: Optimizing");
170 } else {
171 UsageError(" Default: Quick");
172 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700173 UsageError("");
Nicolas Geoffray88157ef2014-09-12 10:29:53 +0100174 UsageError(" --compiler-filter="
175 "(verify-none"
176 "|interpret-only"
177 "|space"
178 "|balanced"
179 "|speed"
180 "|everything"
181 "|time):");
Jeff Hao4a200f52014-04-01 14:58:49 -0700182 UsageError(" select compiler filter.");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800183 UsageError(" Example: --compiler-filter=everything");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800184 UsageError(" Default: speed");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800185 UsageError("");
186 UsageError(" --huge-method-max=<method-instruction-count>: the threshold size for a huge");
187 UsageError(" method for compiler filter tuning.");
188 UsageError(" Example: --huge-method-max=%d", CompilerOptions::kDefaultHugeMethodThreshold);
189 UsageError(" Default: %d", CompilerOptions::kDefaultHugeMethodThreshold);
190 UsageError("");
191 UsageError(" --huge-method-max=<method-instruction-count>: threshold size for a huge");
192 UsageError(" method for compiler filter tuning.");
193 UsageError(" Example: --huge-method-max=%d", CompilerOptions::kDefaultHugeMethodThreshold);
194 UsageError(" Default: %d", CompilerOptions::kDefaultHugeMethodThreshold);
195 UsageError("");
196 UsageError(" --large-method-max=<method-instruction-count>: threshold size for a large");
197 UsageError(" method for compiler filter tuning.");
198 UsageError(" Example: --large-method-max=%d", CompilerOptions::kDefaultLargeMethodThreshold);
199 UsageError(" Default: %d", CompilerOptions::kDefaultLargeMethodThreshold);
200 UsageError("");
201 UsageError(" --small-method-max=<method-instruction-count>: threshold size for a small");
202 UsageError(" method for compiler filter tuning.");
203 UsageError(" Example: --small-method-max=%d", CompilerOptions::kDefaultSmallMethodThreshold);
204 UsageError(" Default: %d", CompilerOptions::kDefaultSmallMethodThreshold);
205 UsageError("");
206 UsageError(" --tiny-method-max=<method-instruction-count>: threshold size for a tiny");
207 UsageError(" method for compiler filter tuning.");
208 UsageError(" Example: --tiny-method-max=%d", CompilerOptions::kDefaultTinyMethodThreshold);
209 UsageError(" Default: %d", CompilerOptions::kDefaultTinyMethodThreshold);
210 UsageError("");
211 UsageError(" --num-dex-methods=<method-count>: threshold size for a small dex file for");
212 UsageError(" compiler filter tuning. If the input has fewer than this many methods");
Jeff Hao4a200f52014-04-01 14:58:49 -0700213 UsageError(" and the filter is not interpret-only or verify-none, overrides the");
214 UsageError(" filter to use speed");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800215 UsageError(" Example: --num-dex-method=%d", CompilerOptions::kDefaultNumDexMethodsThreshold);
216 UsageError(" Default: %d", CompilerOptions::kDefaultNumDexMethodsThreshold);
217 UsageError("");
Ian Rogers46398602013-08-20 07:50:36 -0700218 UsageError(" --dump-timing: display a breakdown of where time was spent");
219 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700220 UsageError(" --include-patch-information: Include patching information so the generated code");
221 UsageError(" can have its base address moved without full recompilation.");
222 UsageError("");
223 UsageError(" --no-include-patch-information: Do not include patching information.");
224 UsageError("");
Alex Light78382fa2014-06-06 15:45:32 -0700225 UsageError(" --include-debug-symbols: Include ELF symbols in this oat file");
226 UsageError("");
227 UsageError(" --no-include-debug-symbols: Do not include ELF symbols in this oat file");
228 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700229 UsageError(" --runtime-arg <argument>: used to specify various arguments for the runtime,");
230 UsageError(" such as initial heap size, maximum heap size, and verbose output.");
231 UsageError(" Use a separate --runtime-arg switch for each argument.");
232 UsageError(" Example: --runtime-arg -Xms256m");
Jeff Hao4a200f52014-04-01 14:58:49 -0700233 UsageError("");
Dave Allisond6ed6422014-04-09 23:36:15 +0000234 UsageError(" --profile-file=<filename>: specify profiler output file to use for compilation.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700235 UsageError("");
Chao-ying Fucd8ce662014-03-11 14:57:19 -0700236 UsageError(" --print-pass-names: print a list of pass names");
237 UsageError("");
238 UsageError(" --disable-passes=<pass-names>: disable one or more passes separated by comma.");
239 UsageError(" Example: --disable-passes=UseCount,BBOptimizations");
240 UsageError("");
Razvan A Lupusorubd25d4b2014-07-02 18:16:51 -0700241 UsageError(" --print-pass-options: print a list of passes that have configurable options along "
242 "with the setting.");
243 UsageError(" Will print default if no overridden setting exists.");
244 UsageError("");
245 UsageError(" --pass-options=Pass1Name:Pass1OptionName:Pass1Option#,"
246 "Pass2Name:Pass2OptionName:Pass2Option#");
247 UsageError(" Used to specify a pass specific option. The setting itself must be integer.");
248 UsageError(" Separator used between options is a comma.");
249 UsageError("");
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800250 UsageError(" --swap-file=<file-name>: specifies a file to use for swap.");
251 UsageError(" Example: --swap-file=/data/tmp/swap.001");
252 UsageError("");
253 UsageError(" --swap-fd=<file-descriptor>: specifies a file to use for swap (by descriptor).");
254 UsageError(" Example: --swap-fd=10");
255 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700256 std::cerr << "See log for usage error information\n";
257 exit(EXIT_FAILURE);
258}
259
Brian Carlstrom7940e442013-07-12 13:46:57 -0700260// The primary goal of the watchdog is to prevent stuck build servers
261// during development when fatal aborts lead to a cascade of failures
262// that result in a deadlock.
263class WatchDog {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800264// WatchDog defines its own CHECK_PTHREAD_CALL to avoid using LOG which uses locks
Brian Carlstrom7940e442013-07-12 13:46:57 -0700265#undef CHECK_PTHREAD_CALL
266#define CHECK_WATCH_DOG_PTHREAD_CALL(call, args, what) \
267 do { \
268 int rc = call args; \
269 if (rc != 0) { \
270 errno = rc; \
271 std::string message(# call); \
272 message += " failed for "; \
273 message += reason; \
274 Fatal(message); \
275 } \
276 } while (false)
277
278 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -0700279 explicit WatchDog(bool is_watch_dog_enabled) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700280 is_watch_dog_enabled_ = is_watch_dog_enabled;
281 if (!is_watch_dog_enabled_) {
282 return;
283 }
284 shutting_down_ = false;
285 const char* reason = "dex2oat watch dog thread startup";
Kenny Root51316382014-05-13 14:59:37 -0700286 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_init, (&mutex_, nullptr), reason);
287 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_init, (&cond_, nullptr), reason);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700288 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_init, (&attr_), reason);
289 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_create, (&pthread_, &attr_, &CallBack, this), reason);
290 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_destroy, (&attr_), reason);
291 }
292 ~WatchDog() {
293 if (!is_watch_dog_enabled_) {
294 return;
295 }
296 const char* reason = "dex2oat watch dog thread shutdown";
297 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
298 shutting_down_ = true;
299 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_signal, (&cond_), reason);
300 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
301
Kenny Root51316382014-05-13 14:59:37 -0700302 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_join, (pthread_, nullptr), reason);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700303
304 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_destroy, (&cond_), reason);
305 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_destroy, (&mutex_), reason);
306 }
307
308 private:
309 static void* CallBack(void* arg) {
310 WatchDog* self = reinterpret_cast<WatchDog*>(arg);
311 ::art::SetThreadName("dex2oat watch dog");
312 self->Wait();
Kenny Root51316382014-05-13 14:59:37 -0700313 return nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700314 }
315
316 static void Message(char severity, const std::string& message) {
317 // TODO: Remove when we switch to LOG when we can guarantee it won't prevent shutdown in error
318 // cases.
319 fprintf(stderr, "dex2oat%s %c %d %d %s\n",
320 kIsDebugBuild ? "d" : "",
321 severity,
322 getpid(),
323 GetTid(),
324 message.c_str());
325 }
326
Andreas Gampe794ad762015-02-23 08:12:24 -0800327 NO_RETURN static void Fatal(const std::string& message) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700328 Message('F', message);
329 exit(1);
330 }
331
332 void Wait() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700333 // TODO: tune the multiplier for GC verification, the following is just to make the timeout
334 // large.
Mathieu Chartier4e305412014-02-19 10:54:44 -0800335 int64_t multiplier = kVerifyObjectSupport > kVerifyObjectModeFast ? 100 : 1;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700336 timespec timeout_ts;
337 InitTimeSpec(true, CLOCK_REALTIME, multiplier * kWatchDogTimeoutSeconds * 1000, 0, &timeout_ts);
338 const char* reason = "dex2oat watch dog thread waiting";
339 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
340 while (!shutting_down_) {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800341 int rc = TEMP_FAILURE_RETRY(pthread_cond_timedwait(&cond_, &mutex_, &timeout_ts));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700342 if (rc == ETIMEDOUT) {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800343 Fatal(StringPrintf("dex2oat did not finish after %d seconds", kWatchDogTimeoutSeconds));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700344 } else if (rc != 0) {
345 std::string message(StringPrintf("pthread_cond_timedwait failed: %s",
346 strerror(errno)));
347 Fatal(message.c_str());
348 }
349 }
350 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
351 }
352
353 // 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 -0700354 // Debug builds are slower so they have larger timeouts.
355 static const unsigned int kSlowdownFactor = kIsDebugBuild ? 5U : 1U;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800356
Elliott Hughes956af0f2014-12-11 14:34:28 -0800357 // 6 minutes scaled by kSlowdownFactor.
358 static const unsigned int kWatchDogTimeoutSeconds = kSlowdownFactor * 6 * 60;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700359
360 bool is_watch_dog_enabled_;
361 bool shutting_down_;
362 // TODO: Switch to Mutex when we can guarantee it won't prevent shutdown in error cases.
363 pthread_mutex_t mutex_;
364 pthread_cond_t cond_;
365 pthread_attr_t attr_;
366 pthread_t pthread_;
367};
Brian Carlstrom7940e442013-07-12 13:46:57 -0700368
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800369static void ParseStringAfterChar(const std::string& s, char c, std::string* parsed_value) {
Calin Juravlec1b643c2014-05-30 23:44:11 +0100370 std::string::size_type colon = s.find(c);
371 if (colon == std::string::npos) {
372 Usage("Missing char %c in option %s\n", c, s.c_str());
373 }
374 // Add one to remove the char we were trimming until.
375 *parsed_value = s.substr(colon + 1);
376}
377
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800378static void ParseDouble(const std::string& option, char after_char, double min, double max,
379 double* parsed_value) {
Calin Juravlec1b643c2014-05-30 23:44:11 +0100380 std::string substring;
381 ParseStringAfterChar(option, after_char, &substring);
382 bool sane_val = true;
383 double value;
384 if (false) {
385 // TODO: this doesn't seem to work on the emulator. b/15114595
386 std::stringstream iss(substring);
387 iss >> value;
388 // Ensure that we have a value, there was no cruft after it and it satisfies a sensible range.
389 sane_val = iss.eof() && (value >= min) && (value <= max);
390 } else {
391 char* end = nullptr;
392 value = strtod(substring.c_str(), &end);
393 sane_val = *end == '\0' && value >= min && value <= max;
394 }
395 if (!sane_val) {
396 Usage("Invalid double value %s for option %s\n", substring.c_str(), option.c_str());
397 }
398 *parsed_value = value;
399}
400
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800401static constexpr size_t kMinDexFilesForSwap = 2;
402static constexpr size_t kMinDexFileCumulativeSizeForSwap = 20 * MB;
403
404static bool UseSwap(bool is_image, std::vector<const DexFile*>& dex_files) {
405 if (is_image) {
406 // Don't use swap, we know generation should succeed, and we don't want to slow it down.
407 return false;
408 }
409 if (dex_files.size() < kMinDexFilesForSwap) {
410 // If there are less dex files than the threshold, assume it's gonna be fine.
411 return false;
412 }
413 size_t dex_files_size = 0;
414 for (const auto* dex_file : dex_files) {
415 dex_files_size += dex_file->GetHeader().file_size_;
416 }
417 return dex_files_size >= kMinDexFileCumulativeSizeForSwap;
418}
419
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800420class Dex2Oat FINAL {
421 public:
422 explicit Dex2Oat(TimingLogger* timings) :
Elliott Hughes956af0f2014-12-11 14:34:28 -0800423 compiler_kind_(kUseOptimizingCompiler ? Compiler::kOptimizing : Compiler::kQuick),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800424 instruction_set_(kRuntimeISA),
425 // Take the default set of instruction features from the build.
426 method_inliner_map_(),
427 runtime_(nullptr),
428 thread_count_(sysconf(_SC_NPROCESSORS_CONF)),
429 start_ns_(NanoTime()),
430 oat_fd_(-1),
431 zip_fd_(-1),
432 image_base_(0U),
433 image_classes_zip_filename_(nullptr),
434 image_classes_filename_(nullptr),
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800435 compiled_classes_zip_filename_(nullptr),
436 compiled_classes_filename_(nullptr),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800437 image_(false),
438 is_host_(false),
439 dump_stats_(false),
440 dump_passes_(false),
441 dump_timing_(false),
442 dump_slow_timing_(kIsDebugBuild),
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800443 swap_fd_(-1),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800444 timings_(timings) {}
445
446 ~Dex2Oat() {
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800447 // Free opened dex files before deleting the runtime_, because ~DexFile
448 // uses MemMap, which is shut down by ~Runtime.
449 class_path_files_.clear();
450 opened_dex_files_.clear();
451
452 // Log completion time before deleting the runtime_, because this accesses
453 // the runtime.
454 LogCompletionTime();
455
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800456 if (kIsDebugBuild || (RUNNING_ON_VALGRIND != 0)) {
457 delete runtime_; // See field declaration for why this is manual.
Vladimir Markof94b7812014-06-05 15:48:04 +0100458 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700459 }
460
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800461 // Parse the arguments from the command line. In case of an unrecognized option or impossible
462 // values/combinations, a usage error will be displayed and exit() is called. Thus, if the method
463 // returns, arguments have been successfully parsed.
464 void ParseArgs(int argc, char** argv) {
465 original_argc = argc;
466 original_argv = argv;
Dave Allison70202782013-10-22 17:52:19 -0700467
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800468 InitLogging(argv);
Dave Allison70202782013-10-22 17:52:19 -0700469
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800470 // Skip over argv[0].
471 argv++;
472 argc--;
Dave Allison70202782013-10-22 17:52:19 -0700473
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800474 if (argc == 0) {
475 Usage("No arguments specified");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700476 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800477
478 std::string oat_symbols;
479 std::string boot_image_filename;
480 const char* compiler_filter_string = nullptr;
481 bool compile_pic = false;
482 int huge_method_threshold = CompilerOptions::kDefaultHugeMethodThreshold;
483 int large_method_threshold = CompilerOptions::kDefaultLargeMethodThreshold;
484 int small_method_threshold = CompilerOptions::kDefaultSmallMethodThreshold;
485 int tiny_method_threshold = CompilerOptions::kDefaultTinyMethodThreshold;
486 int num_dex_methods_threshold = CompilerOptions::kDefaultNumDexMethodsThreshold;
487
488 // Profile file to use
489 double top_k_profile_threshold = CompilerOptions::kDefaultTopKProfileThreshold;
490
Andreas Gampe7b2f09e2015-03-02 14:07:33 -0800491 bool debuggable = false;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800492 bool include_patch_information = CompilerOptions::kDefaultIncludePatchInformation;
493 bool include_debug_symbols = kIsDebugBuild;
494 bool watch_dog_enabled = true;
495 bool generate_gdb_information = kIsDebugBuild;
Andreas Gampe6cf49e52015-03-05 13:08:45 -0800496 bool abort_on_hard_verifier_error = false;
Nicolas Geoffray1412dfa2015-03-20 14:48:13 +0000497 bool requested_specific_compiler = false;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800498
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=")) {
Nicolas Geoffray1412dfa2015-03-20 14:48:13 +0000607 requested_specific_compiler = true;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800608 StringPiece backend_str = option.substr(strlen("--compiler-backend=")).data();
609 if (backend_str == "Quick") {
610 compiler_kind_ = Compiler::kQuick;
611 } else if (backend_str == "Optimizing") {
612 compiler_kind_ = Compiler::kOptimizing;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800613 } else {
614 Usage("Unknown compiler backend: %s", backend_str.data());
615 }
616 } else if (option.starts_with("--compiler-filter=")) {
Nicolas Geoffray1412dfa2015-03-20 14:48:13 +0000617 requested_specific_compiler = true;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800618 compiler_filter_string = option.substr(strlen("--compiler-filter=")).data();
619 } else if (option == "--compile-pic") {
620 compile_pic = true;
621 } else if (option.starts_with("--huge-method-max=")) {
622 const char* threshold = option.substr(strlen("--huge-method-max=")).data();
623 if (!ParseInt(threshold, &huge_method_threshold)) {
624 Usage("Failed to parse --huge-method-max '%s' as an integer", threshold);
625 }
626 if (huge_method_threshold < 0) {
627 Usage("--huge-method-max passed a negative value %s", huge_method_threshold);
628 }
629 } else if (option.starts_with("--large-method-max=")) {
630 const char* threshold = option.substr(strlen("--large-method-max=")).data();
631 if (!ParseInt(threshold, &large_method_threshold)) {
632 Usage("Failed to parse --large-method-max '%s' as an integer", threshold);
633 }
634 if (large_method_threshold < 0) {
635 Usage("--large-method-max passed a negative value %s", large_method_threshold);
636 }
637 } else if (option.starts_with("--small-method-max=")) {
638 const char* threshold = option.substr(strlen("--small-method-max=")).data();
639 if (!ParseInt(threshold, &small_method_threshold)) {
640 Usage("Failed to parse --small-method-max '%s' as an integer", threshold);
641 }
642 if (small_method_threshold < 0) {
643 Usage("--small-method-max passed a negative value %s", small_method_threshold);
644 }
645 } else if (option.starts_with("--tiny-method-max=")) {
646 const char* threshold = option.substr(strlen("--tiny-method-max=")).data();
647 if (!ParseInt(threshold, &tiny_method_threshold)) {
648 Usage("Failed to parse --tiny-method-max '%s' as an integer", threshold);
649 }
650 if (tiny_method_threshold < 0) {
651 Usage("--tiny-method-max passed a negative value %s", tiny_method_threshold);
652 }
653 } else if (option.starts_with("--num-dex-methods=")) {
654 const char* threshold = option.substr(strlen("--num-dex-methods=")).data();
655 if (!ParseInt(threshold, &num_dex_methods_threshold)) {
656 Usage("Failed to parse --num-dex-methods '%s' as an integer", threshold);
657 }
658 if (num_dex_methods_threshold < 0) {
659 Usage("--num-dex-methods passed a negative value %s", num_dex_methods_threshold);
660 }
661 } else if (option == "--host") {
662 is_host_ = true;
663 } else if (option == "--runtime-arg") {
664 if (++i >= argc) {
665 Usage("Missing required argument for --runtime-arg");
666 }
667 if (log_options) {
668 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
669 }
670 runtime_args_.push_back(argv[i]);
671 } else if (option == "--dump-timing") {
672 dump_timing_ = true;
673 } else if (option == "--dump-passes") {
674 dump_passes_ = true;
David Brazdil866c0312015-01-13 21:21:31 +0000675 } else if (option.starts_with("--dump-cfg=")) {
676 dump_cfg_file_name_ = option.substr(strlen("--dump-cfg=")).data();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800677 } else if (option == "--dump-stats") {
678 dump_stats_ = true;
679 } else if (option == "--include-debug-symbols" || option == "--no-strip-symbols") {
680 include_debug_symbols = true;
681 } else if (option == "--no-include-debug-symbols" || option == "--strip-symbols") {
682 include_debug_symbols = false;
683 generate_gdb_information = false; // Depends on debug symbols, see above.
Andreas Gampe7b2f09e2015-03-02 14:07:33 -0800684 } else if (option == "--debuggable") {
685 debuggable = true;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800686 } else if (option.starts_with("--profile-file=")) {
687 profile_file_ = option.substr(strlen("--profile-file=")).data();
688 VLOG(compiler) << "dex2oat: profile file is " << profile_file_;
689 } else if (option == "--no-profile-file") {
690 // No profile
691 } else if (option.starts_with("--top-k-profile-threshold=")) {
692 ParseDouble(option.data(), '=', 0.0, 100.0, &top_k_profile_threshold);
693 } else if (option == "--print-pass-names") {
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800694 pass_manager_options.SetPrintPassNames(true);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800695 } else if (option.starts_with("--disable-passes=")) {
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800696 const std::string disable_passes = option.substr(strlen("--disable-passes=")).data();
697 pass_manager_options.SetDisablePassList(disable_passes);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800698 } else if (option.starts_with("--print-passes=")) {
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800699 const std::string print_passes = option.substr(strlen("--print-passes=")).data();
700 pass_manager_options.SetPrintPassList(print_passes);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800701 } else if (option == "--print-all-passes") {
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800702 pass_manager_options.SetPrintAllPasses();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800703 } else if (option.starts_with("--dump-cfg-passes=")) {
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800704 const std::string dump_passes_string = option.substr(strlen("--dump-cfg-passes=")).data();
705 pass_manager_options.SetDumpPassList(dump_passes_string);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800706 } else if (option == "--print-pass-options") {
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800707 pass_manager_options.SetPrintPassOptions(true);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800708 } else if (option.starts_with("--pass-options=")) {
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800709 const std::string options = option.substr(strlen("--pass-options=")).data();
710 pass_manager_options.SetOverriddenPassOptions(options);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800711 } else if (option == "--include-patch-information") {
712 include_patch_information = true;
713 } else if (option == "--no-include-patch-information") {
714 include_patch_information = false;
715 } else if (option.starts_with("--verbose-methods=")) {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800716 // TODO: rather than switch off compiler logging, make all VLOG(compiler) messages
717 // conditional on having verbost methods.
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800718 gLogVerbosity.compiler = false;
719 Split(option.substr(strlen("--verbose-methods=")).ToString(), ',', &verbose_methods_);
Andreas Gampedbfe2542014-11-25 22:21:42 -0800720 } else if (option.starts_with("--dump-init-failures=")) {
721 std::string file_name = option.substr(strlen("--dump-init-failures=")).data();
722 init_failure_output_.reset(new std::ofstream(file_name));
723 if (init_failure_output_.get() == nullptr) {
724 LOG(ERROR) << "Failed to allocate ofstream";
725 } else if (init_failure_output_->fail()) {
726 LOG(ERROR) << "Failed to open " << file_name << " for writing the initialization "
727 << "failures.";
728 init_failure_output_.reset();
729 }
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800730 } else if (option.starts_with("--swap-file=")) {
731 swap_file_name_ = option.substr(strlen("--swap-file=")).data();
732 } else if (option.starts_with("--swap-fd=")) {
733 const char* swap_fd_str = option.substr(strlen("--swap-fd=")).data();
734 if (!ParseInt(swap_fd_str, &swap_fd_)) {
735 Usage("Failed to parse --swap-fd argument '%s' as an integer", swap_fd_str);
736 }
737 if (swap_fd_ < 0) {
738 Usage("--swap-fd passed a negative value %d", swap_fd_);
739 }
Andreas Gampe6cf49e52015-03-05 13:08:45 -0800740 } else if (option == "--abort-on-hard-verifier-error") {
741 abort_on_hard_verifier_error = true;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800742 } else {
743 Usage("Unknown argument %s", option.data());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700744 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800745 }
746
Nicolas Geoffray1412dfa2015-03-20 14:48:13 +0000747 image_ = (!image_filename_.empty());
748 if (!requested_specific_compiler && !kUseOptimizingCompiler) {
749 // If no specific compiler is requested, the current behavior is
750 // to compile the boot image with Quick, and the rest with Optimizing.
751 compiler_kind_ = image_ ? Compiler::kQuick : Compiler::kOptimizing;
752 }
753
Nicolas Geoffray9bb492a2014-11-25 23:42:00 +0000754 if (compiler_kind_ == Compiler::kOptimizing) {
755 // Optimizing only supports PIC mode.
756 compile_pic = true;
757 }
758
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800759 if (oat_filename_.empty() && oat_fd_ == -1) {
760 Usage("Output must be supplied with either --oat-file or --oat-fd");
761 }
762
763 if (!oat_filename_.empty() && oat_fd_ != -1) {
764 Usage("--oat-file should not be used with --oat-fd");
765 }
766
767 if (!oat_symbols.empty() && oat_fd_ != -1) {
768 Usage("--oat-symbols should not be used with --oat-fd");
769 }
770
771 if (!oat_symbols.empty() && is_host_) {
772 Usage("--oat-symbols should not be used with --host");
773 }
774
775 if (oat_fd_ != -1 && !image_filename_.empty()) {
776 Usage("--oat-fd should not be used with --image");
777 }
778
779 if (android_root_.empty()) {
780 const char* android_root_env_var = getenv("ANDROID_ROOT");
781 if (android_root_env_var == nullptr) {
782 Usage("--android-root unspecified and ANDROID_ROOT not set");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700783 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800784 android_root_ += android_root_env_var;
785 }
786
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800787 if (!image_ && boot_image_filename.empty()) {
788 boot_image_filename += android_root_;
789 boot_image_filename += "/framework/boot.art";
790 }
791 if (!boot_image_filename.empty()) {
792 boot_image_option_ += "-Ximage:";
793 boot_image_option_ += boot_image_filename;
794 }
795
796 if (image_classes_filename_ != nullptr && !image_) {
797 Usage("--image-classes should only be used with --image");
798 }
799
800 if (image_classes_filename_ != nullptr && !boot_image_option_.empty()) {
801 Usage("--image-classes should not be used with --boot-image");
802 }
803
804 if (image_classes_zip_filename_ != nullptr && image_classes_filename_ == nullptr) {
805 Usage("--image-classes-zip should be used with --image-classes");
806 }
807
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800808 if (compiled_classes_filename_ != nullptr && !image_) {
809 Usage("--compiled-classes should only be used with --image");
810 }
811
812 if (compiled_classes_filename_ != nullptr && !boot_image_option_.empty()) {
813 Usage("--compiled-classes should not be used with --boot-image");
814 }
815
816 if (compiled_classes_zip_filename_ != nullptr && compiled_classes_filename_ == nullptr) {
817 Usage("--compiled-classes-zip should be used with --compiled-classes");
818 }
819
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800820 if (dex_filenames_.empty() && zip_fd_ == -1) {
821 Usage("Input must be supplied with either --dex-file or --zip-fd");
822 }
823
824 if (!dex_filenames_.empty() && zip_fd_ != -1) {
825 Usage("--dex-file should not be used with --zip-fd");
826 }
827
828 if (!dex_filenames_.empty() && !zip_location_.empty()) {
829 Usage("--dex-file should not be used with --zip-location");
830 }
831
832 if (dex_locations_.empty()) {
833 for (const char* dex_file_name : dex_filenames_) {
834 dex_locations_.push_back(dex_file_name);
835 }
836 } else if (dex_locations_.size() != dex_filenames_.size()) {
837 Usage("--dex-location arguments do not match --dex-file arguments");
838 }
839
840 if (zip_fd_ != -1 && zip_location_.empty()) {
841 Usage("--zip-location should be supplied with --zip-fd");
842 }
843
844 if (boot_image_option_.empty()) {
845 if (image_base_ == 0) {
846 Usage("Non-zero --base not specified");
847 }
848 }
849
850 oat_stripped_ = oat_filename_;
851 if (!oat_symbols.empty()) {
852 oat_unstripped_ = oat_symbols;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700853 } else {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800854 oat_unstripped_ = oat_filename_;
855 }
856
857 // If no instruction set feature was given, use the default one for the target
858 // instruction set.
859 if (instruction_set_features_.get() == nullptr) {
860 instruction_set_features_.reset(
Ian Rogersd582fa42014-11-05 23:46:43 -0800861 InstructionSetFeatures::FromVariant(instruction_set_, "default", &error_msg));
862 if (instruction_set_features_.get() == nullptr) {
863 Usage("Problem initializing default instruction set features variant: %s",
864 error_msg.c_str());
865 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800866 }
867
868 if (instruction_set_ == kRuntimeISA) {
869 std::unique_ptr<const InstructionSetFeatures> runtime_features(
870 InstructionSetFeatures::FromCppDefines());
871 if (!instruction_set_features_->Equals(runtime_features.get())) {
872 LOG(WARNING) << "Mismatch between dex2oat instruction set features ("
873 << *instruction_set_features_ << ") and those of dex2oat executable ("
874 << *runtime_features <<") for the command line:\n"
875 << CommandLine();
876 }
877 }
878
879 if (compiler_filter_string == nullptr) {
Andreas Gampec5a3ea72015-01-13 16:41:53 -0800880 if (instruction_set_ == kMips &&
881 reinterpret_cast<const MipsInstructionSetFeatures*>(instruction_set_features_.get())->
882 IsR6()) {
883 // For R6, only interpreter mode is working.
884 // TODO: fix compiler for Mips32r6.
885 compiler_filter_string = "interpret-only";
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800886 } else {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800887 compiler_filter_string = "speed";
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800888 }
889 }
Maja Gagic6ea651f2015-02-24 16:55:04 +0100890
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800891 CHECK(compiler_filter_string != nullptr);
892 CompilerOptions::CompilerFilter compiler_filter = CompilerOptions::kDefaultCompilerFilter;
893 if (strcmp(compiler_filter_string, "verify-none") == 0) {
894 compiler_filter = CompilerOptions::kVerifyNone;
895 } else if (strcmp(compiler_filter_string, "interpret-only") == 0) {
896 compiler_filter = CompilerOptions::kInterpretOnly;
Mathieu Chartiere86deef2015-03-19 13:43:37 -0700897 } else if (strcmp(compiler_filter_string, "verify-at-runtime") == 0) {
898 compiler_filter = CompilerOptions::kVerifyAtRuntime;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800899 } else if (strcmp(compiler_filter_string, "space") == 0) {
900 compiler_filter = CompilerOptions::kSpace;
901 } else if (strcmp(compiler_filter_string, "balanced") == 0) {
902 compiler_filter = CompilerOptions::kBalanced;
903 } else if (strcmp(compiler_filter_string, "speed") == 0) {
904 compiler_filter = CompilerOptions::kSpeed;
905 } else if (strcmp(compiler_filter_string, "everything") == 0) {
906 compiler_filter = CompilerOptions::kEverything;
907 } else if (strcmp(compiler_filter_string, "time") == 0) {
908 compiler_filter = CompilerOptions::kTime;
909 } else {
910 Usage("Unknown --compiler-filter value %s", compiler_filter_string);
911 }
912
913 // Checks are all explicit until we know the architecture.
914 bool implicit_null_checks = false;
915 bool implicit_so_checks = false;
916 bool implicit_suspend_checks = false;
917 // Set the compilation target's implicit checks options.
918 switch (instruction_set_) {
919 case kArm:
920 case kThumb2:
921 case kArm64:
922 case kX86:
923 case kX86_64:
924 implicit_null_checks = true;
925 implicit_so_checks = true;
926 break;
927
928 default:
929 // Defaults are correct.
930 break;
931 }
932
Andreas Gampe7b2f09e2015-03-02 14:07:33 -0800933 if (debuggable) {
934 // TODO: Consider adding CFI info and symbols here.
935 }
936
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800937 compiler_options_.reset(new CompilerOptions(compiler_filter,
938 huge_method_threshold,
939 large_method_threshold,
940 small_method_threshold,
941 tiny_method_threshold,
942 num_dex_methods_threshold,
943 generate_gdb_information,
944 include_patch_information,
945 top_k_profile_threshold,
Andreas Gampe7b2f09e2015-03-02 14:07:33 -0800946 debuggable,
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800947 include_debug_symbols,
948 implicit_null_checks,
949 implicit_so_checks,
950 implicit_suspend_checks,
951 compile_pic,
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800952 verbose_methods_.empty() ?
953 nullptr :
Andreas Gampedbfe2542014-11-25 22:21:42 -0800954 &verbose_methods_,
Mathieu Chartier5bdab122015-01-26 18:30:19 -0800955 new PassManagerOptions(pass_manager_options),
Andreas Gampe6cf49e52015-03-05 13:08:45 -0800956 init_failure_output_.get(),
957 abort_on_hard_verifier_error));
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800958
959 // Done with usage checks, enable watchdog if requested
960 if (watch_dog_enabled) {
961 watchdog_.reset(new WatchDog(true));
962 }
963
964 // Fill some values into the key-value store for the oat header.
965 key_value_store_.reset(new SafeMap<std::string, std::string>());
966
967 // Insert some compiler things.
968 {
969 std::ostringstream oss;
970 for (int i = 0; i < argc; ++i) {
971 if (i > 0) {
972 oss << ' ';
973 }
974 oss << argv[i];
975 }
976 key_value_store_->Put(OatHeader::kDex2OatCmdLineKey, oss.str());
977 oss.str(""); // Reset.
978 oss << kRuntimeISA;
979 key_value_store_->Put(OatHeader::kDex2OatHostKey, oss.str());
980 key_value_store_->Put(OatHeader::kPicKey, compile_pic ? "true" : "false");
981 }
982 }
983
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800984 // Check whether the oat output file is writable, and open it for later. Also open a swap file,
985 // if a name is given.
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800986 bool OpenFile() {
987 bool create_file = !oat_unstripped_.empty(); // as opposed to using open file descriptor
988 if (create_file) {
989 oat_file_.reset(OS::CreateEmptyFile(oat_unstripped_.c_str()));
990 if (oat_location_.empty()) {
991 oat_location_ = oat_filename_;
992 }
993 } else {
Andreas Gampe4303ba92014-11-06 01:00:46 -0800994 oat_file_.reset(new File(oat_fd_, oat_location_, true));
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800995 oat_file_->DisableAutoClose();
Andreas Gampe4303ba92014-11-06 01:00:46 -0800996 if (oat_file_->SetLength(0) != 0) {
997 PLOG(WARNING) << "Truncating oat file " << oat_location_ << " failed.";
998 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800999 }
1000 if (oat_file_.get() == nullptr) {
1001 PLOG(ERROR) << "Failed to create oat file: " << oat_location_;
1002 return false;
1003 }
1004 if (create_file && fchmod(oat_file_->Fd(), 0644) != 0) {
1005 PLOG(ERROR) << "Failed to make oat file world readable: " << oat_location_;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001006 oat_file_->Erase();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001007 return false;
1008 }
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001009
1010 // Swap file handling.
1011 //
1012 // If the swap fd is not -1, we assume this is the file descriptor of an open but unlinked file
1013 // that we can use for swap.
1014 //
1015 // If the swap fd is -1 and we have a swap-file string, open the given file as a swap file. We
1016 // will immediately unlink to satisfy the swap fd assumption.
1017 if (swap_fd_ == -1 && !swap_file_name_.empty()) {
1018 std::unique_ptr<File> swap_file(OS::CreateEmptyFile(swap_file_name_.c_str()));
1019 if (swap_file.get() == nullptr) {
1020 PLOG(ERROR) << "Failed to create swap file: " << swap_file_name_;
1021 return false;
1022 }
1023 swap_fd_ = swap_file->Fd();
1024 swap_file->MarkUnchecked(); // We don't we to track this, it will be unlinked immediately.
1025 swap_file->DisableAutoClose(); // We'll handle it ourselves, the File object will be
1026 // released immediately.
1027 unlink(swap_file_name_.c_str());
1028 }
1029
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001030 return true;
1031 }
1032
Andreas Gampea650e702014-12-03 14:28:02 -08001033 void EraseOatFile() {
1034 DCHECK(oat_file_.get() != nullptr);
1035 oat_file_->Erase();
1036 oat_file_.reset();
1037 }
1038
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001039 // Set up the environment for compilation. Includes starting the runtime and loading/opening the
1040 // boot class path.
1041 bool Setup() {
1042 TimingLogger::ScopedTiming t("dex2oat Setup", timings_);
1043 RuntimeOptions runtime_options;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001044 art::MemMap::Init(); // For ZipEntry::ExtractToMemMap.
1045 if (boot_image_option_.empty()) {
Richard Uhlerc2752592015-01-02 13:28:22 -08001046 std::string boot_class_path = "-Xbootclasspath:";
1047 boot_class_path += Join(dex_filenames_, ':');
1048 runtime_options.push_back(std::make_pair(boot_class_path, nullptr));
1049 std::string boot_class_path_locations = "-Xbootclasspath-locations:";
1050 boot_class_path_locations += Join(dex_locations_, ':');
1051 runtime_options.push_back(std::make_pair(boot_class_path_locations, nullptr));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001052 } else {
Richard Uhlerc2752592015-01-02 13:28:22 -08001053 runtime_options.push_back(std::make_pair(boot_image_option_, nullptr));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001054 }
1055 for (size_t i = 0; i < runtime_args_.size(); i++) {
1056 runtime_options.push_back(std::make_pair(runtime_args_[i], nullptr));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001057 }
Brian Carlstromd76e0832013-08-29 15:17:42 -07001058
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001059 verification_results_.reset(new VerificationResults(compiler_options_.get()));
1060 callbacks_.reset(new QuickCompilerCallbacks(verification_results_.get(), &method_inliner_map_));
1061 runtime_options.push_back(std::make_pair("compilercallbacks", callbacks_.get()));
1062 runtime_options.push_back(
1063 std::make_pair("imageinstructionset", GetInstructionSetString(instruction_set_)));
1064
Andreas Gampe1d00add2015-02-27 19:35:46 -08001065 // Only allow no boot image for the runtime if we're compiling one. When we compile an app,
1066 // we don't want fallback mode, it will abort as we do not push a boot classpath (it might
1067 // have been stripped in preopting, anyways).
1068 if (!image_) {
1069 runtime_options.push_back(std::make_pair("-Xno-dex-file-fallback", nullptr));
1070 }
1071
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001072 if (!CreateRuntime(runtime_options)) {
1073 return false;
1074 }
1075
1076 // Runtime::Create acquired the mutator_lock_ that is normally given away when we
1077 // Runtime::Start, give it away now so that we don't starve GC.
1078 Thread* self = Thread::Current();
1079 self->TransitionFromRunnableToSuspended(kNative);
1080 // If we're doing the image, override the compiler filter to force full compilation. Must be
1081 // done ahead of WellKnownClasses::Init that causes verification. Note: doesn't force
1082 // compilation of class initializers.
1083 // Whilst we're in native take the opportunity to initialize well known classes.
1084 WellKnownClasses::Init(self->GetJniEnv());
1085
1086 // If --image-classes was specified, calculate the full list of classes to include in the image
1087 if (image_classes_filename_ != nullptr) {
1088 std::string error_msg;
1089 if (image_classes_zip_filename_ != nullptr) {
1090 image_classes_.reset(ReadImageClassesFromZip(image_classes_zip_filename_,
1091 image_classes_filename_,
1092 &error_msg));
1093 } else {
1094 image_classes_.reset(ReadImageClassesFromFile(image_classes_filename_));
1095 }
1096 if (image_classes_.get() == nullptr) {
1097 LOG(ERROR) << "Failed to create list of image classes from '" << image_classes_filename_ <<
1098 "': " << error_msg;
1099 return false;
1100 }
1101 } else if (image_) {
1102 image_classes_.reset(new std::set<std::string>);
1103 }
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001104 // If --compiled-classes was specified, calculate the full list of classes to compile in the
1105 // image.
1106 if (compiled_classes_filename_ != nullptr) {
1107 std::string error_msg;
1108 if (compiled_classes_zip_filename_ != nullptr) {
1109 compiled_classes_.reset(ReadImageClassesFromZip(compiled_classes_zip_filename_,
1110 compiled_classes_filename_,
1111 &error_msg));
1112 } else {
1113 compiled_classes_.reset(ReadImageClassesFromFile(compiled_classes_filename_));
1114 }
1115 if (compiled_classes_.get() == nullptr) {
1116 LOG(ERROR) << "Failed to create list of compiled classes from '"
1117 << compiled_classes_filename_ << "': " << error_msg;
1118 return false;
1119 }
1120 } else if (image_) {
1121 compiled_classes_.reset(nullptr); // By default compile everything.
1122 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001123
1124 if (boot_image_option_.empty()) {
1125 dex_files_ = Runtime::Current()->GetClassLinker()->GetBootClassPath();
1126 } else {
1127 if (dex_filenames_.empty()) {
1128 ATRACE_BEGIN("Opening zip archive from file descriptor");
1129 std::string error_msg;
1130 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(zip_fd_,
1131 zip_location_.c_str(),
1132 &error_msg));
1133 if (zip_archive.get() == nullptr) {
1134 LOG(ERROR) << "Failed to open zip from file descriptor for '" << zip_location_ << "': "
1135 << error_msg;
1136 return false;
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001137 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001138 if (!DexFile::OpenFromZip(*zip_archive.get(), zip_location_, &error_msg, &opened_dex_files_)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001139 LOG(ERROR) << "Failed to open dex from file descriptor for zip file '" << zip_location_
1140 << "': " << error_msg;
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 ATRACE_END();
1147 } else {
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001148 size_t failure_count = OpenDexFiles(dex_filenames_, dex_locations_, &opened_dex_files_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001149 if (failure_count > 0) {
1150 LOG(ERROR) << "Failed to open some dex files: " << failure_count;
1151 return false;
1152 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001153 for (auto& dex_file : opened_dex_files_) {
1154 dex_files_.push_back(dex_file.get());
1155 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001156 }
1157
1158 constexpr bool kSaveDexInput = false;
1159 if (kSaveDexInput) {
1160 for (size_t i = 0; i < dex_files_.size(); ++i) {
1161 const DexFile* dex_file = dex_files_[i];
Brian Carlstrom95b033b2014-12-03 22:29:37 -08001162 std::string tmp_file_name(StringPrintf("/data/local/tmp/dex2oat.%d.%zd.dex",
1163 getpid(), i));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001164 std::unique_ptr<File> tmp_file(OS::CreateEmptyFile(tmp_file_name.c_str()));
1165 if (tmp_file.get() == nullptr) {
1166 PLOG(ERROR) << "Failed to open file " << tmp_file_name
1167 << ". Try: adb shell chmod 777 /data/local/tmp";
1168 continue;
1169 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001170 // This is just dumping files for debugging. Ignore errors, and leave remnants.
1171 UNUSED(tmp_file->WriteFully(dex_file->Begin(), dex_file->Size()));
1172 UNUSED(tmp_file->Flush());
1173 UNUSED(tmp_file->Close());
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001174 LOG(INFO) << "Wrote input to " << tmp_file_name;
1175 }
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001176 }
1177 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001178 // Ensure opened dex files are writable for dex-to-dex transformations.
1179 for (const auto& dex_file : dex_files_) {
1180 if (!dex_file->EnableWrite()) {
1181 PLOG(ERROR) << "Failed to make .dex file writeable '" << dex_file->GetLocation() << "'\n";
Andreas Gampe7ba64962014-10-23 11:37:40 -07001182 }
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001183 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001184
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001185 // If we use a swap file, ensure we are above the threshold to make it necessary.
1186 if (swap_fd_ != -1) {
1187 if (!UseSwap(image_, dex_files_)) {
1188 close(swap_fd_);
1189 swap_fd_ = -1;
1190 LOG(INFO) << "Decided to run without swap.";
1191 } else {
1192 LOG(INFO) << "Accepted running with swap.";
1193 }
1194 }
1195 // Note that dex2oat won't close the swap_fd_. The compiler driver's swap space will do that.
1196
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001197 /*
1198 * If we're not in interpret-only or verify-none mode, go ahead and compile small applications.
1199 * Don't bother to check if we're doing the image.
1200 */
Brian Carlstrom95b033b2014-12-03 22:29:37 -08001201 if (!image_ &&
1202 compiler_options_->IsCompilationEnabled() &&
1203 compiler_kind_ == Compiler::kQuick) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001204 size_t num_methods = 0;
1205 for (size_t i = 0; i != dex_files_.size(); ++i) {
1206 const DexFile* dex_file = dex_files_[i];
1207 CHECK(dex_file != nullptr);
1208 num_methods += dex_file->NumMethodIds();
1209 }
1210 if (num_methods <= compiler_options_->GetNumDexMethodsThreshold()) {
1211 compiler_options_->SetCompilerFilter(CompilerOptions::kSpeed);
1212 VLOG(compiler) << "Below method threshold, compiling anyways";
1213 }
1214 }
1215
1216 return true;
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001217 }
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001218
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001219 // Create and invoke the compiler driver. This will compile all the dex files.
1220 void Compile() {
1221 TimingLogger::ScopedTiming t("dex2oat Compile", timings_);
1222 compiler_phases_timings_.reset(new CumulativeLogger("compilation times"));
Vladimir Markof4da6752014-08-01 19:04:18 +01001223
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001224 // Handle and ClassLoader creation needs to come after Runtime::Create
1225 jobject class_loader = nullptr;
1226 Thread* self = Thread::Current();
1227 if (!boot_image_option_.empty()) {
1228 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001229 OpenClassPathFiles(runtime_->GetClassPathString(), dex_files_, &class_path_files_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001230 ScopedObjectAccess soa(self);
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001231 std::vector<const DexFile*> class_path_files(dex_files_);
1232 for (auto& class_path_file : class_path_files_) {
1233 class_path_files.push_back(class_path_file.get());
1234 }
1235
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001236 for (size_t i = 0; i < class_path_files.size(); i++) {
1237 class_linker->RegisterDexFile(*class_path_files[i]);
1238 }
1239 soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader);
1240 ScopedLocalRef<jobject> class_loader_local(soa.Env(),
1241 soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader));
1242 class_loader = soa.Env()->NewGlobalRef(class_loader_local.get());
1243 Runtime::Current()->SetCompileTimeClassPath(class_loader, class_path_files);
1244 }
1245
1246 driver_.reset(new CompilerDriver(compiler_options_.get(),
1247 verification_results_.get(),
1248 &method_inliner_map_,
1249 compiler_kind_,
1250 instruction_set_,
1251 instruction_set_features_.get(),
1252 image_,
1253 image_classes_.release(),
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001254 compiled_classes_.release(),
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001255 thread_count_,
1256 dump_stats_,
1257 dump_passes_,
David Brazdil866c0312015-01-13 21:21:31 +00001258 dump_cfg_file_name_,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001259 compiler_phases_timings_.get(),
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001260 swap_fd_,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001261 profile_file_));
1262
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001263 driver_->CompileAll(class_loader, dex_files_, timings_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001264 }
1265
Brian Carlstrom7940e442013-07-12 13:46:57 -07001266 // Notes on the interleaving of creating the image and oat file to
1267 // ensure the references between the two are correct.
1268 //
1269 // Currently we have a memory layout that looks something like this:
1270 //
1271 // +--------------+
1272 // | image |
1273 // +--------------+
1274 // | boot oat |
1275 // +--------------+
1276 // | alloc spaces |
1277 // +--------------+
1278 //
Brian Carlstrom45602482013-07-21 22:07:55 -07001279 // There are several constraints on the loading of the image and boot.oat.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001280 //
1281 // 1. The image is expected to be loaded at an absolute address and
1282 // contains Objects with absolute pointers within the image.
1283 //
1284 // 2. There are absolute pointers from Methods in the image to their
1285 // code in the oat.
1286 //
1287 // 3. There are absolute pointers from the code in the oat to Methods
1288 // in the image.
1289 //
1290 // 4. There are absolute pointers from code in the oat to other code
1291 // in the oat.
1292 //
1293 // To get this all correct, we go through several steps.
1294 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001295 // 1. We prepare offsets for all data in the oat file and calculate
1296 // the oat data size and code size. During this stage, we also set
1297 // oat code offsets in methods for use by the image writer.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001298 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001299 // 2. We prepare offsets for the objects in the image and calculate
1300 // the image size.
1301 //
1302 // 3. We create the oat file. Originally this was just our own proprietary
1303 // file but now it is contained within an ELF dynamic object (aka an .so
1304 // file). Since we know the image size and oat data size and code size we
1305 // can prepare the ELF headers and we then know the ELF memory segment
1306 // layout and we can now resolve all references. The compiler provides
1307 // LinkerPatch information in each CompiledMethod and we resolve these,
1308 // using the layout information and image object locations provided by
1309 // image writer, as we're writing the method code.
1310 //
1311 // 4. We create the image file. It needs to know where the oat file
Brian Carlstrom7940e442013-07-12 13:46:57 -07001312 // will be loaded after itself. Originally when oat file was simply
1313 // memory mapped so we could predict where its contents were based
1314 // on the file size. Now that it is an ELF file, we need to inspect
1315 // the ELF file to understand the in memory segment layout including
Vladimir Markof4da6752014-08-01 19:04:18 +01001316 // where the oat header is located within.
1317 // TODO: We could just remember this information from step 3.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001318 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001319 // 5. We fixup the ELF program headers so that dlopen will try to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001320 // load the .so at the desired location at runtime by offsetting the
1321 // Elf32_Phdr.p_vaddr values by the desired base address.
Vladimir Markof4da6752014-08-01 19:04:18 +01001322 // TODO: Do this in step 3. We already know the layout there.
1323 //
1324 // Steps 1.-3. are done by the CreateOatFile() above, steps 4.-5.
1325 // are done by the CreateImageFile() below.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001326
1327
1328 // Write out the generated code part. Calls the OatWriter and ElfBuilder. Also prepares the
1329 // ImageWriter, if necessary.
Andreas Gampe10e477d2014-11-19 12:57:42 -08001330 // Note: Flushing (and closing) the file is the caller's responsibility, except for the failure
1331 // case (when the file will be explicitly erased).
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001332 bool CreateOatFile() {
1333 CHECK(key_value_store_.get() != nullptr);
1334
1335 TimingLogger::ScopedTiming t("dex2oat Oat", timings_);
1336
1337 std::unique_ptr<OatWriter> oat_writer;
1338 {
1339 TimingLogger::ScopedTiming t2("dex2oat OatWriter", timings_);
1340 std::string image_file_location;
1341 uint32_t image_file_location_oat_checksum = 0;
1342 uintptr_t image_file_location_oat_data_begin = 0;
1343 int32_t image_patch_delta = 0;
1344 if (image_) {
1345 PrepareImageWriter(image_base_);
1346 } else {
1347 TimingLogger::ScopedTiming t3("Loading image checksum", timings_);
1348 gc::space::ImageSpace* image_space = Runtime::Current()->GetHeap()->GetImageSpace();
1349 image_file_location_oat_checksum = image_space->GetImageHeader().GetOatChecksum();
1350 image_file_location_oat_data_begin =
1351 reinterpret_cast<uintptr_t>(image_space->GetImageHeader().GetOatDataBegin());
1352 image_file_location = image_space->GetImageFilename();
1353 image_patch_delta = image_space->GetImageHeader().GetPatchDelta();
1354 }
1355
1356 if (!image_file_location.empty()) {
1357 key_value_store_->Put(OatHeader::kImageLocationKey, image_file_location);
1358 }
1359
1360 oat_writer.reset(new OatWriter(dex_files_, image_file_location_oat_checksum,
1361 image_file_location_oat_data_begin,
1362 image_patch_delta,
1363 driver_.get(),
1364 image_writer_.get(),
1365 timings_,
1366 key_value_store_.get()));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001367 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001368
1369 if (image_) {
1370 // The OatWriter constructor has already updated offsets in methods and we need to
1371 // prepare method offsets in the image address space for direct method patching.
1372 TimingLogger::ScopedTiming t2("dex2oat Prepare image address space", timings_);
1373 if (!image_writer_->PrepareImageAddressSpace()) {
1374 LOG(ERROR) << "Failed to prepare image address space.";
1375 return false;
1376 }
1377 }
1378
1379 {
1380 TimingLogger::ScopedTiming t2("dex2oat Write ELF", timings_);
1381 if (!driver_->WriteElf(android_root_, is_host_, dex_files_, oat_writer.get(),
1382 oat_file_.get())) {
1383 LOG(ERROR) << "Failed to write ELF file " << oat_file_->GetPath();
1384 return false;
1385 }
1386 }
1387
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001388 VLOG(compiler) << "Oat file written successfully (unstripped): " << oat_location_;
1389 return true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001390 }
1391
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001392 // If we are compiling an image, invoke the image creation routine. Else just skip.
1393 bool HandleImage() {
1394 if (image_) {
1395 TimingLogger::ScopedTiming t("dex2oat ImageWriter", timings_);
1396 if (!CreateImageFile()) {
1397 return false;
1398 }
1399 VLOG(compiler) << "Image written successfully: " << image_filename_;
Brian Carlstrom45602482013-07-21 22:07:55 -07001400 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001401 return true;
1402 }
1403
Andreas Gampe10e477d2014-11-19 12:57:42 -08001404 // Create a copy from unstripped to stripped.
1405 bool CopyUnstrippedToStripped() {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001406 // If we don't want to strip in place, copy from unstripped location to stripped location.
1407 // We need to strip after image creation because FixupElf needs to use .strtab.
1408 if (oat_unstripped_ != oat_stripped_) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08001409 // If the oat file is still open, flush it.
1410 if (oat_file_.get() != nullptr && oat_file_->IsOpened()) {
1411 if (!FlushCloseOatFile()) {
1412 return false;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001413 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001414 }
Andreas Gampe10e477d2014-11-19 12:57:42 -08001415
1416 TimingLogger::ScopedTiming t("dex2oat OatFile copy", timings_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001417 std::unique_ptr<File> in(OS::OpenFileForReading(oat_unstripped_.c_str()));
1418 std::unique_ptr<File> out(OS::CreateEmptyFile(oat_stripped_.c_str()));
1419 size_t buffer_size = 8192;
Dan Albert6fc59ab2014-12-11 14:09:51 -08001420 std::unique_ptr<uint8_t[]> buffer(new uint8_t[buffer_size]);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001421 while (true) {
1422 int bytes_read = TEMP_FAILURE_RETRY(read(in->Fd(), buffer.get(), buffer_size));
1423 if (bytes_read <= 0) {
1424 break;
1425 }
1426 bool write_ok = out->WriteFully(buffer.get(), bytes_read);
1427 CHECK(write_ok);
1428 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08001429 if (out->FlushCloseOrErase() != 0) {
1430 PLOG(ERROR) << "Failed to flush and close copied oat file: " << oat_stripped_;
1431 return false;
Andreas Gampe10e477d2014-11-19 12:57:42 -08001432 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001433 VLOG(compiler) << "Oat file copied successfully (stripped): " << oat_stripped_;
Nicolas Geoffrayea3fa0b2014-02-10 11:59:41 +00001434 }
Andreas Gampe10e477d2014-11-19 12:57:42 -08001435 return true;
1436 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001437
Andreas Gampe10e477d2014-11-19 12:57:42 -08001438 bool FlushOatFile() {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001439 if (oat_file_.get() != nullptr) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08001440 TimingLogger::ScopedTiming t2("dex2oat Flush ELF", timings_);
1441 if (oat_file_->Flush() != 0) {
1442 PLOG(ERROR) << "Failed to flush oat file: " << oat_location_ << " / "
1443 << oat_filename_;
1444 oat_file_->Erase();
1445 return false;
1446 }
1447 }
1448 return true;
1449 }
1450
1451 bool FlushCloseOatFile() {
1452 if (oat_file_.get() != nullptr) {
1453 std::unique_ptr<File> tmp(oat_file_.release());
1454 if (tmp->FlushCloseOrErase() != 0) {
1455 PLOG(ERROR) << "Failed to flush and close oat file: " << oat_location_ << " / "
1456 << oat_filename_;
1457 return false;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001458 }
1459 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001460 return true;
1461 }
1462
1463 void DumpTiming() {
1464 if (dump_timing_ || (dump_slow_timing_ && timings_->GetTotalNs() > MsToNs(1000))) {
1465 LOG(INFO) << Dumpable<TimingLogger>(*timings_);
1466 }
1467 if (dump_passes_) {
1468 LOG(INFO) << Dumpable<CumulativeLogger>(*driver_->GetTimingsLogger());
1469 }
1470 }
1471
1472 CompilerOptions* GetCompilerOptions() const {
1473 return compiler_options_.get();
1474 }
1475
Andreas Gampe10e477d2014-11-19 12:57:42 -08001476 bool IsImage() const {
1477 return image_;
1478 }
1479
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001480 bool IsHost() const {
1481 return is_host_;
1482 }
1483
1484 private:
1485 static size_t OpenDexFiles(const std::vector<const char*>& dex_filenames,
1486 const std::vector<const char*>& dex_locations,
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001487 std::vector<std::unique_ptr<const DexFile>>* dex_files) {
1488 DCHECK(dex_files != nullptr) << "OpenDexFiles out-param is NULL";
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001489 size_t failure_count = 0;
1490 for (size_t i = 0; i < dex_filenames.size(); i++) {
1491 const char* dex_filename = dex_filenames[i];
1492 const char* dex_location = dex_locations[i];
1493 ATRACE_BEGIN(StringPrintf("Opening dex file '%s'", dex_filenames[i]).c_str());
1494 std::string error_msg;
1495 if (!OS::FileExists(dex_filename)) {
1496 LOG(WARNING) << "Skipping non-existent dex file '" << dex_filename << "'";
1497 continue;
1498 }
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001499 if (!DexFile::Open(dex_filename, dex_location, &error_msg, dex_files)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001500 LOG(WARNING) << "Failed to open .dex from file '" << dex_filename << "': " << error_msg;
1501 ++failure_count;
1502 }
1503 ATRACE_END();
1504 }
1505 return failure_count;
1506 }
1507
1508 // Returns true if dex_files has a dex with the named location.
1509 static bool DexFilesContains(const std::vector<const DexFile*>& dex_files,
1510 const std::string& location) {
1511 for (size_t i = 0; i < dex_files.size(); ++i) {
1512 if (dex_files[i]->GetLocation() == location) {
1513 return true;
1514 }
1515 }
1516 return false;
1517 }
1518
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001519 // Appends to opened_dex_files any elements of class_path that dex_files
1520 // doesn't already contain. This will open those dex files as necessary.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001521 static void OpenClassPathFiles(const std::string& class_path,
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001522 std::vector<const DexFile*> dex_files,
1523 std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
1524 DCHECK(opened_dex_files != nullptr) << "OpenClassPathFiles out-param is NULL";
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001525 std::vector<std::string> parsed;
1526 Split(class_path, ':', &parsed);
1527 // Take Locks::mutator_lock_ so that lock ordering on the ClassLinker::dex_lock_ is maintained.
1528 ScopedObjectAccess soa(Thread::Current());
1529 for (size_t i = 0; i < parsed.size(); ++i) {
1530 if (DexFilesContains(dex_files, parsed[i])) {
1531 continue;
1532 }
1533 std::string error_msg;
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001534 if (!DexFile::Open(parsed[i].c_str(), parsed[i].c_str(), &error_msg, opened_dex_files)) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001535 LOG(WARNING) << "Failed to open dex file '" << parsed[i] << "': " << error_msg;
1536 }
1537 }
1538 }
1539
1540 // Create a runtime necessary for compilation.
1541 bool CreateRuntime(const RuntimeOptions& runtime_options)
1542 SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_) {
1543 if (!Runtime::Create(runtime_options, false)) {
1544 LOG(ERROR) << "Failed to create runtime";
1545 return false;
1546 }
1547 Runtime* runtime = Runtime::Current();
1548 runtime->SetInstructionSet(instruction_set_);
1549 for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
1550 Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i);
1551 if (!runtime->HasCalleeSaveMethod(type)) {
1552 runtime->SetCalleeSaveMethod(runtime->CreateCalleeSaveMethod(), type);
1553 }
1554 }
1555 runtime->GetClassLinker()->FixupDexCaches(runtime->GetResolutionMethod());
Andreas Gampe2969bcd2015-03-09 12:57:41 -07001556
1557 // Initialize maps for unstarted runtime. This needs to be here, as running clinits needs this
1558 // set up.
1559 interpreter::UnstartedRuntimeInitialize();
1560
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001561 runtime->GetClassLinker()->RunRootClinits();
1562 runtime_ = runtime;
Andreas Gampe2969bcd2015-03-09 12:57:41 -07001563
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001564 return true;
1565 }
1566
1567 void PrepareImageWriter(uintptr_t image_base) {
1568 image_writer_.reset(new ImageWriter(*driver_, image_base, compiler_options_->GetCompilePic()));
1569 }
1570
1571 // Let the ImageWriter write the image file. If we do not compile PIC, also fix up the oat file.
1572 bool CreateImageFile()
1573 LOCKS_EXCLUDED(Locks::mutator_lock_) {
1574 CHECK(image_writer_ != nullptr);
1575 if (!image_writer_->Write(image_filename_, oat_unstripped_, oat_location_)) {
1576 LOG(ERROR) << "Failed to create image file " << image_filename_;
1577 return false;
1578 }
1579 uintptr_t oat_data_begin = image_writer_->GetOatDataBegin();
1580
1581 // Destroy ImageWriter before doing FixupElf.
1582 image_writer_.reset();
1583
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001584 // Do not fix up the ELF file if we are --compile-pic
1585 if (!compiler_options_->GetCompilePic()) {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001586 std::unique_ptr<File> oat_file(OS::OpenFileReadWrite(oat_unstripped_.c_str()));
1587 if (oat_file.get() == nullptr) {
1588 PLOG(ERROR) << "Failed to open ELF file: " << oat_unstripped_;
1589 return false;
1590 }
1591
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001592 if (!ElfWriter::Fixup(oat_file.get(), oat_data_begin)) {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001593 oat_file->Erase();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001594 LOG(ERROR) << "Failed to fixup ELF file " << oat_file->GetPath();
1595 return false;
1596 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001597
1598 if (oat_file->FlushCloseOrErase()) {
1599 PLOG(ERROR) << "Failed to flush and close fixed ELF file " << oat_file->GetPath();
1600 return false;
1601 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001602 }
1603
1604 return true;
1605 }
1606
1607 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
1608 static std::set<std::string>* ReadImageClassesFromFile(const char* image_classes_filename) {
1609 std::unique_ptr<std::ifstream> image_classes_file(new std::ifstream(image_classes_filename,
1610 std::ifstream::in));
1611 if (image_classes_file.get() == nullptr) {
1612 LOG(ERROR) << "Failed to open image classes file " << image_classes_filename;
1613 return nullptr;
1614 }
1615 std::unique_ptr<std::set<std::string>> result(ReadImageClasses(*image_classes_file));
1616 image_classes_file->close();
1617 return result.release();
1618 }
1619
1620 static std::set<std::string>* ReadImageClasses(std::istream& image_classes_stream) {
1621 std::unique_ptr<std::set<std::string>> image_classes(new std::set<std::string>);
1622 while (image_classes_stream.good()) {
1623 std::string dot;
1624 std::getline(image_classes_stream, dot);
1625 if (StartsWith(dot, "#") || dot.empty()) {
1626 continue;
1627 }
1628 std::string descriptor(DotToDescriptor(dot.c_str()));
1629 image_classes->insert(descriptor);
1630 }
1631 return image_classes.release();
1632 }
1633
1634 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
1635 static std::set<std::string>* ReadImageClassesFromZip(const char* zip_filename,
1636 const char* image_classes_filename,
1637 std::string* error_msg) {
1638 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::Open(zip_filename, error_msg));
1639 if (zip_archive.get() == nullptr) {
1640 return nullptr;
1641 }
1642 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(image_classes_filename, error_msg));
1643 if (zip_entry.get() == nullptr) {
1644 *error_msg = StringPrintf("Failed to find '%s' within '%s': %s", image_classes_filename,
1645 zip_filename, error_msg->c_str());
1646 return nullptr;
1647 }
1648 std::unique_ptr<MemMap> image_classes_file(zip_entry->ExtractToMemMap(zip_filename,
1649 image_classes_filename,
1650 error_msg));
1651 if (image_classes_file.get() == nullptr) {
1652 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", image_classes_filename,
1653 zip_filename, error_msg->c_str());
1654 return nullptr;
1655 }
1656 const std::string image_classes_string(reinterpret_cast<char*>(image_classes_file->Begin()),
1657 image_classes_file->Size());
1658 std::istringstream image_classes_stream(image_classes_string);
1659 return ReadImageClasses(image_classes_stream);
1660 }
1661
Mathieu Chartier49285c52014-12-02 15:43:48 -08001662 void LogCompletionTime() {
Andreas Gampe1d00add2015-02-27 19:35:46 -08001663 // Note: when creation of a runtime fails, e.g., when trying to compile an app but when there
1664 // is no image, there won't be a Runtime::Current().
Brian Carlstroma11a34c2015-03-06 08:44:45 -08001665 // Note: driver creation can fail when loading an invalid dex file.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001666 LOG(INFO) << "dex2oat took " << PrettyDuration(NanoTime() - start_ns_)
Mathieu Chartierab972ef2014-12-03 17:38:22 -08001667 << " (threads: " << thread_count_ << ") "
Brian Carlstroma11a34c2015-03-06 08:44:45 -08001668 << ((Runtime::Current() != nullptr && driver_.get() != nullptr) ?
Andreas Gampe1d00add2015-02-27 19:35:46 -08001669 driver_->GetMemoryUsageString(kIsDebugBuild || VLOG_IS_ON(compiler)) :
1670 "");
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001671 }
1672
1673 std::unique_ptr<CompilerOptions> compiler_options_;
1674 Compiler::Kind compiler_kind_;
1675
1676 InstructionSet instruction_set_;
1677 std::unique_ptr<const InstructionSetFeatures> instruction_set_features_;
1678
1679 std::unique_ptr<SafeMap<std::string, std::string> > key_value_store_;
1680
1681 std::unique_ptr<VerificationResults> verification_results_;
1682 DexFileToMethodInlinerMap method_inliner_map_;
1683 std::unique_ptr<QuickCompilerCallbacks> callbacks_;
1684
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001685 // Ownership for the class path files.
1686 std::vector<std::unique_ptr<const DexFile>> class_path_files_;
1687
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001688 // Not a unique_ptr as we want to just exit on non-debug builds, not bringing the runtime down
1689 // in an orderly fashion. The destructor takes care of deleting this.
1690 Runtime* runtime_;
1691
1692 size_t thread_count_;
1693 uint64_t start_ns_;
1694 std::unique_ptr<WatchDog> watchdog_;
1695 std::unique_ptr<File> oat_file_;
1696 std::string oat_stripped_;
1697 std::string oat_unstripped_;
1698 std::string oat_location_;
1699 std::string oat_filename_;
1700 int oat_fd_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001701 std::vector<const char*> dex_filenames_;
1702 std::vector<const char*> dex_locations_;
1703 int zip_fd_;
1704 std::string zip_location_;
1705 std::string boot_image_option_;
1706 std::vector<const char*> runtime_args_;
1707 std::string image_filename_;
1708 uintptr_t image_base_;
1709 const char* image_classes_zip_filename_;
1710 const char* image_classes_filename_;
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001711 const char* compiled_classes_zip_filename_;
1712 const char* compiled_classes_filename_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001713 std::unique_ptr<std::set<std::string>> image_classes_;
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001714 std::unique_ptr<std::set<std::string>> compiled_classes_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001715 bool image_;
1716 std::unique_ptr<ImageWriter> image_writer_;
1717 bool is_host_;
1718 std::string android_root_;
1719 std::vector<const DexFile*> dex_files_;
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001720 std::vector<std::unique_ptr<const DexFile>> opened_dex_files_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001721 std::unique_ptr<CompilerDriver> driver_;
1722 std::vector<std::string> verbose_methods_;
1723 bool dump_stats_;
1724 bool dump_passes_;
1725 bool dump_timing_;
1726 bool dump_slow_timing_;
David Brazdil866c0312015-01-13 21:21:31 +00001727 std::string dump_cfg_file_name_;
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001728 std::string swap_file_name_;
1729 int swap_fd_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001730 std::string profile_file_; // Profile file to use
1731 TimingLogger* timings_;
1732 std::unique_ptr<CumulativeLogger> compiler_phases_timings_;
Andreas Gampedbfe2542014-11-25 22:21:42 -08001733 std::unique_ptr<std::ostream> init_failure_output_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001734
1735 DISALLOW_IMPLICIT_CONSTRUCTORS(Dex2Oat);
1736};
1737
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001738const unsigned int WatchDog::kWatchDogTimeoutSeconds;
1739
1740static void b13564922() {
1741#if defined(__linux__) && defined(__arm__)
1742 int major, minor;
1743 struct utsname uts;
1744 if (uname(&uts) != -1 &&
1745 sscanf(uts.release, "%d.%d", &major, &minor) == 2 &&
1746 ((major < 3) || ((major == 3) && (minor < 4)))) {
1747 // Kernels before 3.4 don't handle the ASLR well and we can run out of address
1748 // space (http://b/13564922). Work around the issue by inhibiting further mmap() randomization.
1749 int old_personality = personality(0xffffffff);
1750 if ((old_personality & ADDR_NO_RANDOMIZE) == 0) {
1751 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
1752 if (new_personality == -1) {
1753 LOG(WARNING) << "personality(. | ADDR_NO_RANDOMIZE) failed.";
1754 }
1755 }
1756 }
1757#endif
1758}
1759
Andreas Gampe10e477d2014-11-19 12:57:42 -08001760static int CompileImage(Dex2Oat& dex2oat) {
1761 dex2oat.Compile();
1762
1763 // Create the boot.oat.
1764 if (!dex2oat.CreateOatFile()) {
Andreas Gampea650e702014-12-03 14:28:02 -08001765 dex2oat.EraseOatFile();
Andreas Gampe10e477d2014-11-19 12:57:42 -08001766 return EXIT_FAILURE;
1767 }
1768
1769 // Flush and close the boot.oat. We always expect the output file by name, and it will be
1770 // re-opened from the unstripped name.
1771 if (!dex2oat.FlushCloseOatFile()) {
1772 return EXIT_FAILURE;
1773 }
1774
1775 // Creates the boot.art and patches the boot.oat.
1776 if (!dex2oat.HandleImage()) {
1777 return EXIT_FAILURE;
1778 }
1779
1780 // When given --host, finish early without stripping.
1781 if (dex2oat.IsHost()) {
1782 dex2oat.DumpTiming();
1783 return EXIT_SUCCESS;
1784 }
1785
1786 // Copy unstripped to stripped location, if necessary.
1787 if (!dex2oat.CopyUnstrippedToStripped()) {
1788 return EXIT_FAILURE;
1789 }
1790
Andreas Gampe10e477d2014-11-19 12:57:42 -08001791 // FlushClose again, as stripping might have re-opened the oat file.
1792 if (!dex2oat.FlushCloseOatFile()) {
1793 return EXIT_FAILURE;
1794 }
1795
1796 dex2oat.DumpTiming();
1797 return EXIT_SUCCESS;
1798}
1799
1800static int CompileApp(Dex2Oat& dex2oat) {
1801 dex2oat.Compile();
1802
1803 // Create the app oat.
1804 if (!dex2oat.CreateOatFile()) {
Andreas Gampea650e702014-12-03 14:28:02 -08001805 dex2oat.EraseOatFile();
Andreas Gampe10e477d2014-11-19 12:57:42 -08001806 return EXIT_FAILURE;
1807 }
1808
1809 // Do not close the oat file here. We might haven gotten the output file by file descriptor,
1810 // which we would lose.
1811 if (!dex2oat.FlushOatFile()) {
1812 return EXIT_FAILURE;
1813 }
1814
1815 // When given --host, finish early without stripping.
1816 if (dex2oat.IsHost()) {
1817 if (!dex2oat.FlushCloseOatFile()) {
1818 return EXIT_FAILURE;
1819 }
1820
1821 dex2oat.DumpTiming();
1822 return EXIT_SUCCESS;
1823 }
1824
1825 // Copy unstripped to stripped location, if necessary. This will implicitly flush & close the
1826 // unstripped version. If this is given, we expect to be able to open writable files by name.
1827 if (!dex2oat.CopyUnstrippedToStripped()) {
1828 return EXIT_FAILURE;
1829 }
1830
Andreas Gampe10e477d2014-11-19 12:57:42 -08001831 // Flush and close the file.
1832 if (!dex2oat.FlushCloseOatFile()) {
1833 return EXIT_FAILURE;
1834 }
1835
1836 dex2oat.DumpTiming();
1837 return EXIT_SUCCESS;
1838}
1839
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001840static int dex2oat(int argc, char** argv) {
1841 b13564922();
1842
1843 TimingLogger timings("compiler", false, false);
1844
1845 Dex2Oat dex2oat(&timings);
1846
1847 // Parse arguments. Argument mistakes will lead to exit(EXIT_FAILURE) in UsageError.
1848 dex2oat.ParseArgs(argc, argv);
1849
1850 // Check early that the result of compilation can be written
1851 if (!dex2oat.OpenFile()) {
1852 return EXIT_FAILURE;
1853 }
1854
1855 LOG(INFO) << CommandLine();
1856
1857 if (!dex2oat.Setup()) {
Andreas Gampea650e702014-12-03 14:28:02 -08001858 dex2oat.EraseOatFile();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001859 return EXIT_FAILURE;
1860 }
1861
Andreas Gampe10e477d2014-11-19 12:57:42 -08001862 if (dex2oat.IsImage()) {
1863 return CompileImage(dex2oat);
1864 } else {
1865 return CompileApp(dex2oat);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001866 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001867}
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001868} // namespace art
Brian Carlstrom7940e442013-07-12 13:46:57 -07001869
1870int main(int argc, char** argv) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001871 int result = art::dex2oat(argc, argv);
1872 // Everything was done, do an explicit exit here to avoid running Runtime destructors that take
1873 // time (bug 10645725) unless we're a debug build or running on valgrind. Note: The Dex2Oat class
1874 // should not destruct the runtime in this case.
1875 if (!art::kIsDebugBuild && (RUNNING_ON_VALGRIND == 0)) {
1876 exit(result);
1877 }
1878 return result;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001879}