blob: 63009bf25e6b1dddbd2bbf02dedaa5def543ecbd [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"
Ian Rogersc7dd2952014-10-21 23:31:19 -070037#include "base/dumpable.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070038#include "base/stl_util.h"
39#include "base/stringpiece.h"
40#include "base/timing_logger.h"
41#include "base/unix_file/fd_file.h"
42#include "class_linker.h"
Nicolas Geoffrayb34f69a2014-03-07 15:28:39 +000043#include "compiler.h"
Vladimir Marko2b5eaa22013-12-13 13:59:30 +000044#include "compiler_callbacks.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070045#include "dex_file-inl.h"
Jean Christophe Beyler2469e602014-05-06 20:36:55 -070046#include "dex/pass_driver_me_opts.h"
Vladimir Markoc7f83202014-01-24 17:55:18 +000047#include "dex/verification_results.h"
Ian Rogerse63db272014-07-15 15:36:11 -070048#include "dex/quick_compiler_callbacks.h"
49#include "dex/quick/dex_file_to_method_inliner_map.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070050#include "driver/compiler_driver.h"
Brian Carlstrom6449c622014-02-10 23:48:36 -080051#include "driver/compiler_options.h"
Andreas Gampe88ec7f42014-11-05 10:18:32 -080052#include "elf_file.h"
Tong Shen62d1ca32014-09-03 17:24:56 -070053#include "elf_writer.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070054#include "gc/space/image_space.h"
55#include "gc/space/space-inl.h"
56#include "image_writer.h"
57#include "leb128.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070058#include "mirror/art_method-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070059#include "mirror/class-inl.h"
60#include "mirror/class_loader.h"
61#include "mirror/object-inl.h"
62#include "mirror/object_array-inl.h"
63#include "oat_writer.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070064#include "os.h"
65#include "runtime.h"
66#include "ScopedLocalRef.h"
67#include "scoped_thread_state_change.h"
Alex Light53cb16b2014-06-12 11:26:29 -070068#include "utils.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070069#include "vector_output_stream.h"
70#include "well_known_classes.h"
71#include "zip_archive.h"
72
73namespace art {
74
Brian Carlstrom6449c622014-02-10 23:48:36 -080075static int original_argc;
76static char** original_argv;
77
78static std::string CommandLine() {
79 std::vector<std::string> command;
80 for (int i = 0; i < original_argc; ++i) {
81 command.push_back(original_argv[i]);
82 }
83 return Join(command, ' ');
84}
85
Brian Carlstrom7940e442013-07-12 13:46:57 -070086static void UsageErrorV(const char* fmt, va_list ap) {
87 std::string error;
88 StringAppendV(&error, fmt, ap);
89 LOG(ERROR) << error;
90}
91
92static void UsageError(const char* fmt, ...) {
93 va_list ap;
94 va_start(ap, fmt);
95 UsageErrorV(fmt, ap);
96 va_end(ap);
97}
98
Ian Rogers7223d442014-10-10 20:05:39 -070099[[noreturn]] static void Usage(const char* fmt, ...) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700100 va_list ap;
101 va_start(ap, fmt);
102 UsageErrorV(fmt, ap);
103 va_end(ap);
104
Brian Carlstrom6449c622014-02-10 23:48:36 -0800105 UsageError("Command: %s", CommandLine().c_str());
106
Brian Carlstrom7940e442013-07-12 13:46:57 -0700107 UsageError("Usage: dex2oat [options]...");
108 UsageError("");
109 UsageError(" --dex-file=<dex-file>: specifies a .dex file to compile.");
110 UsageError(" Example: --dex-file=/system/framework/core.jar");
111 UsageError("");
112 UsageError(" --zip-fd=<file-descriptor>: specifies a file descriptor of a zip file");
113 UsageError(" containing a classes.dex file to compile.");
114 UsageError(" Example: --zip-fd=5");
115 UsageError("");
Brian Carlstrom45602482013-07-21 22:07:55 -0700116 UsageError(" --zip-location=<zip-location>: specifies a symbolic name for the file");
117 UsageError(" corresponding to the file descriptor specified by --zip-fd.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700118 UsageError(" Example: --zip-location=/system/app/Calculator.apk");
119 UsageError("");
120 UsageError(" --oat-file=<file.oat>: specifies the oat output destination via a filename.");
121 UsageError(" Example: --oat-file=/system/framework/boot.oat");
122 UsageError("");
123 UsageError(" --oat-fd=<number>: specifies the oat output destination via a file descriptor.");
Wonil Kim9cb554a2014-04-28 11:26:55 +0900124 UsageError(" Example: --oat-fd=6");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700125 UsageError("");
126 UsageError(" --oat-location=<oat-name>: specifies a symbolic name for the file corresponding");
127 UsageError(" to the file descriptor specified by --oat-fd.");
128 UsageError(" Example: --oat-location=/data/dalvik-cache/system@app@Calculator.apk.oat");
129 UsageError("");
130 UsageError(" --oat-symbols=<file.oat>: specifies the oat output destination with full symbols.");
131 UsageError(" Example: --oat-symbols=/symbols/system/framework/boot.oat");
132 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700133 UsageError(" --image=<file.art>: specifies the output image filename.");
134 UsageError(" Example: --image=/system/framework/boot.art");
135 UsageError("");
136 UsageError(" --image-classes=<classname-file>: specifies classes to include in an image.");
137 UsageError(" Example: --image=frameworks/base/preloaded-classes");
138 UsageError("");
139 UsageError(" --base=<hex-address>: specifies the base address when creating a boot image.");
140 UsageError(" Example: --base=0x50000000");
141 UsageError("");
142 UsageError(" --boot-image=<file.art>: provide the image file for the boot class path.");
143 UsageError(" Example: --boot-image=/system/framework/boot.art");
Nicolas Geoffray9583fbc2014-02-28 15:21:07 +0000144 UsageError(" Default: $ANDROID_ROOT/system/framework/boot.art");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700145 UsageError("");
146 UsageError(" --android-root=<path>: used to locate libraries for portable linking.");
147 UsageError(" Example: --android-root=out/host/linux-x86");
148 UsageError(" Default: $ANDROID_ROOT");
149 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700150 UsageError(" --instruction-set=(arm|arm64|mips|x86|x86_64): compile for a particular");
151 UsageError(" instruction set.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700152 UsageError(" Example: --instruction-set=x86");
153 UsageError(" Default: arm");
154 UsageError("");
Dave Allison70202782013-10-22 17:52:19 -0700155 UsageError(" --instruction-set-features=...,: Specify instruction set features");
156 UsageError(" Example: --instruction-set-features=div");
157 UsageError(" Default: default");
158 UsageError("");
Igor Murashkin46774762014-10-22 11:37:02 -0700159 UsageError(" --compile-pic: Force indirect use of code, methods, and classes");
160 UsageError(" Default: disabled");
161 UsageError("");
Elliott Hughes956af0f2014-12-11 14:34:28 -0800162 UsageError(" --compiler-backend=(Quick|Optimizing): select compiler backend");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700163 UsageError(" set.");
Elliott Hughes956af0f2014-12-11 14:34:28 -0800164 UsageError(" Example: --compiler-backend=Optimizing");
165 if (kUseOptimizingCompiler) {
Nicolas Geoffray4586fb62014-11-28 16:22:11 +0000166 UsageError(" Default: Optimizing");
167 } else {
168 UsageError(" Default: Quick");
169 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700170 UsageError("");
Nicolas Geoffray88157ef2014-09-12 10:29:53 +0100171 UsageError(" --compiler-filter="
172 "(verify-none"
173 "|interpret-only"
174 "|space"
175 "|balanced"
176 "|speed"
177 "|everything"
178 "|time):");
Jeff Hao4a200f52014-04-01 14:58:49 -0700179 UsageError(" select compiler filter.");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800180 UsageError(" Example: --compiler-filter=everything");
181#if ART_SMALL_MODE
182 UsageError(" Default: interpret-only");
183#else
184 UsageError(" Default: speed");
185#endif
186 UsageError("");
187 UsageError(" --huge-method-max=<method-instruction-count>: the threshold size for a huge");
188 UsageError(" method for compiler filter tuning.");
189 UsageError(" Example: --huge-method-max=%d", CompilerOptions::kDefaultHugeMethodThreshold);
190 UsageError(" Default: %d", CompilerOptions::kDefaultHugeMethodThreshold);
191 UsageError("");
192 UsageError(" --huge-method-max=<method-instruction-count>: threshold size for a huge");
193 UsageError(" method for compiler filter tuning.");
194 UsageError(" Example: --huge-method-max=%d", CompilerOptions::kDefaultHugeMethodThreshold);
195 UsageError(" Default: %d", CompilerOptions::kDefaultHugeMethodThreshold);
196 UsageError("");
197 UsageError(" --large-method-max=<method-instruction-count>: threshold size for a large");
198 UsageError(" method for compiler filter tuning.");
199 UsageError(" Example: --large-method-max=%d", CompilerOptions::kDefaultLargeMethodThreshold);
200 UsageError(" Default: %d", CompilerOptions::kDefaultLargeMethodThreshold);
201 UsageError("");
202 UsageError(" --small-method-max=<method-instruction-count>: threshold size for a small");
203 UsageError(" method for compiler filter tuning.");
204 UsageError(" Example: --small-method-max=%d", CompilerOptions::kDefaultSmallMethodThreshold);
205 UsageError(" Default: %d", CompilerOptions::kDefaultSmallMethodThreshold);
206 UsageError("");
207 UsageError(" --tiny-method-max=<method-instruction-count>: threshold size for a tiny");
208 UsageError(" method for compiler filter tuning.");
209 UsageError(" Example: --tiny-method-max=%d", CompilerOptions::kDefaultTinyMethodThreshold);
210 UsageError(" Default: %d", CompilerOptions::kDefaultTinyMethodThreshold);
211 UsageError("");
212 UsageError(" --num-dex-methods=<method-count>: threshold size for a small dex file for");
213 UsageError(" compiler filter tuning. If the input has fewer than this many methods");
Jeff Hao4a200f52014-04-01 14:58:49 -0700214 UsageError(" and the filter is not interpret-only or verify-none, overrides the");
215 UsageError(" filter to use speed");
Brian Carlstrom6449c622014-02-10 23:48:36 -0800216 UsageError(" Example: --num-dex-method=%d", CompilerOptions::kDefaultNumDexMethodsThreshold);
217 UsageError(" Default: %d", CompilerOptions::kDefaultNumDexMethodsThreshold);
218 UsageError("");
Ian Rogers46398602013-08-20 07:50:36 -0700219 UsageError(" --dump-timing: display a breakdown of where time was spent");
220 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700221 UsageError(" --include-patch-information: Include patching information so the generated code");
222 UsageError(" can have its base address moved without full recompilation.");
223 UsageError("");
224 UsageError(" --no-include-patch-information: Do not include patching information.");
225 UsageError("");
Alex Light78382fa2014-06-06 15:45:32 -0700226 UsageError(" --include-debug-symbols: Include ELF symbols in this oat file");
227 UsageError("");
228 UsageError(" --no-include-debug-symbols: Do not include ELF symbols in this oat file");
229 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700230 UsageError(" --runtime-arg <argument>: used to specify various arguments for the runtime,");
231 UsageError(" such as initial heap size, maximum heap size, and verbose output.");
232 UsageError(" Use a separate --runtime-arg switch for each argument.");
233 UsageError(" Example: --runtime-arg -Xms256m");
Jeff Hao4a200f52014-04-01 14:58:49 -0700234 UsageError("");
Dave Allisond6ed6422014-04-09 23:36:15 +0000235 UsageError(" --profile-file=<filename>: specify profiler output file to use for compilation.");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700236 UsageError("");
Chao-ying Fucd8ce662014-03-11 14:57:19 -0700237 UsageError(" --print-pass-names: print a list of pass names");
238 UsageError("");
239 UsageError(" --disable-passes=<pass-names>: disable one or more passes separated by comma.");
240 UsageError(" Example: --disable-passes=UseCount,BBOptimizations");
241 UsageError("");
Razvan A Lupusorubd25d4b2014-07-02 18:16:51 -0700242 UsageError(" --print-pass-options: print a list of passes that have configurable options along "
243 "with the setting.");
244 UsageError(" Will print default if no overridden setting exists.");
245 UsageError("");
246 UsageError(" --pass-options=Pass1Name:Pass1OptionName:Pass1Option#,"
247 "Pass2Name:Pass2OptionName:Pass2Option#");
248 UsageError(" Used to specify a pass specific option. The setting itself must be integer.");
249 UsageError(" Separator used between options is a comma.");
250 UsageError("");
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800251 UsageError(" --swap-file=<file-name>: specifies a file to use for swap.");
252 UsageError(" Example: --swap-file=/data/tmp/swap.001");
253 UsageError("");
254 UsageError(" --swap-fd=<file-descriptor>: specifies a file to use for swap (by descriptor).");
255 UsageError(" Example: --swap-fd=10");
256 UsageError("");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700257 std::cerr << "See log for usage error information\n";
258 exit(EXIT_FAILURE);
259}
260
Brian Carlstrom7940e442013-07-12 13:46:57 -0700261// The primary goal of the watchdog is to prevent stuck build servers
262// during development when fatal aborts lead to a cascade of failures
263// that result in a deadlock.
264class WatchDog {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800265// WatchDog defines its own CHECK_PTHREAD_CALL to avoid using LOG which uses locks
Brian Carlstrom7940e442013-07-12 13:46:57 -0700266#undef CHECK_PTHREAD_CALL
267#define CHECK_WATCH_DOG_PTHREAD_CALL(call, args, what) \
268 do { \
269 int rc = call args; \
270 if (rc != 0) { \
271 errno = rc; \
272 std::string message(# call); \
273 message += " failed for "; \
274 message += reason; \
275 Fatal(message); \
276 } \
277 } while (false)
278
279 public:
Brian Carlstrom93ba8932013-07-17 21:31:49 -0700280 explicit WatchDog(bool is_watch_dog_enabled) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700281 is_watch_dog_enabled_ = is_watch_dog_enabled;
282 if (!is_watch_dog_enabled_) {
283 return;
284 }
285 shutting_down_ = false;
286 const char* reason = "dex2oat watch dog thread startup";
Kenny Root51316382014-05-13 14:59:37 -0700287 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_init, (&mutex_, nullptr), reason);
288 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_init, (&cond_, nullptr), reason);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700289 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_init, (&attr_), reason);
290 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_create, (&pthread_, &attr_, &CallBack, this), reason);
291 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_destroy, (&attr_), reason);
292 }
293 ~WatchDog() {
294 if (!is_watch_dog_enabled_) {
295 return;
296 }
297 const char* reason = "dex2oat watch dog thread shutdown";
298 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
299 shutting_down_ = true;
300 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_signal, (&cond_), reason);
301 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
302
Kenny Root51316382014-05-13 14:59:37 -0700303 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_join, (pthread_, nullptr), reason);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700304
305 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_destroy, (&cond_), reason);
306 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_destroy, (&mutex_), reason);
307 }
308
309 private:
310 static void* CallBack(void* arg) {
311 WatchDog* self = reinterpret_cast<WatchDog*>(arg);
312 ::art::SetThreadName("dex2oat watch dog");
313 self->Wait();
Kenny Root51316382014-05-13 14:59:37 -0700314 return nullptr;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700315 }
316
317 static void Message(char severity, const std::string& message) {
318 // TODO: Remove when we switch to LOG when we can guarantee it won't prevent shutdown in error
319 // cases.
320 fprintf(stderr, "dex2oat%s %c %d %d %s\n",
321 kIsDebugBuild ? "d" : "",
322 severity,
323 getpid(),
324 GetTid(),
325 message.c_str());
326 }
327
Ian Rogers7223d442014-10-10 20:05:39 -0700328 [[noreturn]] static void Fatal(const std::string& message) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700329 Message('F', message);
330 exit(1);
331 }
332
333 void Wait() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700334 // TODO: tune the multiplier for GC verification, the following is just to make the timeout
335 // large.
Mathieu Chartier4e305412014-02-19 10:54:44 -0800336 int64_t multiplier = kVerifyObjectSupport > kVerifyObjectModeFast ? 100 : 1;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700337 timespec timeout_ts;
338 InitTimeSpec(true, CLOCK_REALTIME, multiplier * kWatchDogTimeoutSeconds * 1000, 0, &timeout_ts);
339 const char* reason = "dex2oat watch dog thread waiting";
340 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason);
341 while (!shutting_down_) {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800342 int rc = TEMP_FAILURE_RETRY(pthread_cond_timedwait(&cond_, &mutex_, &timeout_ts));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700343 if (rc == ETIMEDOUT) {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800344 Fatal(StringPrintf("dex2oat did not finish after %d seconds", kWatchDogTimeoutSeconds));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700345 } else if (rc != 0) {
346 std::string message(StringPrintf("pthread_cond_timedwait failed: %s",
347 strerror(errno)));
348 Fatal(message.c_str());
349 }
350 }
351 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason);
352 }
353
354 // 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 -0700355 // Debug builds are slower so they have larger timeouts.
356 static const unsigned int kSlowdownFactor = kIsDebugBuild ? 5U : 1U;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800357
Elliott Hughes956af0f2014-12-11 14:34:28 -0800358 // 6 minutes scaled by kSlowdownFactor.
359 static const unsigned int kWatchDogTimeoutSeconds = kSlowdownFactor * 6 * 60;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700360
361 bool is_watch_dog_enabled_;
362 bool shutting_down_;
363 // TODO: Switch to Mutex when we can guarantee it won't prevent shutdown in error cases.
364 pthread_mutex_t mutex_;
365 pthread_cond_t cond_;
366 pthread_attr_t attr_;
367 pthread_t pthread_;
368};
Brian Carlstrom7940e442013-07-12 13:46:57 -0700369
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800370static void ParseStringAfterChar(const std::string& s, char c, std::string* parsed_value) {
Calin Juravlec1b643c2014-05-30 23:44:11 +0100371 std::string::size_type colon = s.find(c);
372 if (colon == std::string::npos) {
373 Usage("Missing char %c in option %s\n", c, s.c_str());
374 }
375 // Add one to remove the char we were trimming until.
376 *parsed_value = s.substr(colon + 1);
377}
378
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800379static void ParseDouble(const std::string& option, char after_char, double min, double max,
380 double* parsed_value) {
Calin Juravlec1b643c2014-05-30 23:44:11 +0100381 std::string substring;
382 ParseStringAfterChar(option, after_char, &substring);
383 bool sane_val = true;
384 double value;
385 if (false) {
386 // TODO: this doesn't seem to work on the emulator. b/15114595
387 std::stringstream iss(substring);
388 iss >> value;
389 // Ensure that we have a value, there was no cruft after it and it satisfies a sensible range.
390 sane_val = iss.eof() && (value >= min) && (value <= max);
391 } else {
392 char* end = nullptr;
393 value = strtod(substring.c_str(), &end);
394 sane_val = *end == '\0' && value >= min && value <= max;
395 }
396 if (!sane_val) {
397 Usage("Invalid double value %s for option %s\n", substring.c_str(), option.c_str());
398 }
399 *parsed_value = value;
400}
401
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800402static constexpr size_t kMinDexFilesForSwap = 2;
403static constexpr size_t kMinDexFileCumulativeSizeForSwap = 20 * MB;
404
405static bool UseSwap(bool is_image, std::vector<const DexFile*>& dex_files) {
406 if (is_image) {
407 // Don't use swap, we know generation should succeed, and we don't want to slow it down.
408 return false;
409 }
410 if (dex_files.size() < kMinDexFilesForSwap) {
411 // If there are less dex files than the threshold, assume it's gonna be fine.
412 return false;
413 }
414 size_t dex_files_size = 0;
415 for (const auto* dex_file : dex_files) {
416 dex_files_size += dex_file->GetHeader().file_size_;
417 }
418 return dex_files_size >= kMinDexFileCumulativeSizeForSwap;
419}
420
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800421class Dex2Oat FINAL {
422 public:
423 explicit Dex2Oat(TimingLogger* timings) :
Elliott Hughes956af0f2014-12-11 14:34:28 -0800424 compiler_kind_(kUseOptimizingCompiler ? Compiler::kOptimizing : Compiler::kQuick),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800425 instruction_set_(kRuntimeISA),
426 // Take the default set of instruction features from the build.
427 method_inliner_map_(),
428 runtime_(nullptr),
429 thread_count_(sysconf(_SC_NPROCESSORS_CONF)),
430 start_ns_(NanoTime()),
431 oat_fd_(-1),
432 zip_fd_(-1),
433 image_base_(0U),
434 image_classes_zip_filename_(nullptr),
435 image_classes_filename_(nullptr),
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800436 compiled_classes_zip_filename_(nullptr),
437 compiled_classes_filename_(nullptr),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800438 image_(false),
439 is_host_(false),
440 dump_stats_(false),
441 dump_passes_(false),
442 dump_timing_(false),
443 dump_slow_timing_(kIsDebugBuild),
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800444 swap_fd_(-1),
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800445 timings_(timings) {}
446
447 ~Dex2Oat() {
Mathieu Chartier49285c52014-12-02 15:43:48 -0800448 LogCompletionTime(); // Needs to be before since it accesses the runtime.
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800449 if (kIsDebugBuild || (RUNNING_ON_VALGRIND != 0)) {
450 delete runtime_; // See field declaration for why this is manual.
Vladimir Markof94b7812014-06-05 15:48:04 +0100451 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700452 }
453
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800454 // Parse the arguments from the command line. In case of an unrecognized option or impossible
455 // values/combinations, a usage error will be displayed and exit() is called. Thus, if the method
456 // returns, arguments have been successfully parsed.
457 void ParseArgs(int argc, char** argv) {
458 original_argc = argc;
459 original_argv = argv;
Dave Allison70202782013-10-22 17:52:19 -0700460
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800461 InitLogging(argv);
Dave Allison70202782013-10-22 17:52:19 -0700462
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800463 // Skip over argv[0].
464 argv++;
465 argc--;
Dave Allison70202782013-10-22 17:52:19 -0700466
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800467 if (argc == 0) {
468 Usage("No arguments specified");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700469 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800470
471 std::string oat_symbols;
472 std::string boot_image_filename;
473 const char* compiler_filter_string = nullptr;
474 bool compile_pic = false;
475 int huge_method_threshold = CompilerOptions::kDefaultHugeMethodThreshold;
476 int large_method_threshold = CompilerOptions::kDefaultLargeMethodThreshold;
477 int small_method_threshold = CompilerOptions::kDefaultSmallMethodThreshold;
478 int tiny_method_threshold = CompilerOptions::kDefaultTinyMethodThreshold;
479 int num_dex_methods_threshold = CompilerOptions::kDefaultNumDexMethodsThreshold;
480
481 // Profile file to use
482 double top_k_profile_threshold = CompilerOptions::kDefaultTopKProfileThreshold;
483
484 bool print_pass_options = false;
485 bool include_patch_information = CompilerOptions::kDefaultIncludePatchInformation;
486 bool include_debug_symbols = kIsDebugBuild;
487 bool watch_dog_enabled = true;
488 bool generate_gdb_information = kIsDebugBuild;
489
490 std::string error_msg;
491
492 for (int i = 0; i < argc; i++) {
493 const StringPiece option(argv[i]);
494 const bool log_options = false;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700495 if (log_options) {
496 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
497 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800498 if (option.starts_with("--dex-file=")) {
499 dex_filenames_.push_back(option.substr(strlen("--dex-file=")).data());
500 } else if (option.starts_with("--dex-location=")) {
501 dex_locations_.push_back(option.substr(strlen("--dex-location=")).data());
502 } else if (option.starts_with("--zip-fd=")) {
503 const char* zip_fd_str = option.substr(strlen("--zip-fd=")).data();
504 if (!ParseInt(zip_fd_str, &zip_fd_)) {
505 Usage("Failed to parse --zip-fd argument '%s' as an integer", zip_fd_str);
506 }
507 if (zip_fd_ < 0) {
508 Usage("--zip-fd passed a negative value %d", zip_fd_);
509 }
510 } else if (option.starts_with("--zip-location=")) {
511 zip_location_ = option.substr(strlen("--zip-location=")).data();
512 } else if (option.starts_with("--oat-file=")) {
513 oat_filename_ = option.substr(strlen("--oat-file=")).data();
514 } else if (option.starts_with("--oat-symbols=")) {
515 oat_symbols = option.substr(strlen("--oat-symbols=")).data();
516 } else if (option.starts_with("--oat-fd=")) {
517 const char* oat_fd_str = option.substr(strlen("--oat-fd=")).data();
518 if (!ParseInt(oat_fd_str, &oat_fd_)) {
519 Usage("Failed to parse --oat-fd argument '%s' as an integer", oat_fd_str);
520 }
521 if (oat_fd_ < 0) {
522 Usage("--oat-fd passed a negative value %d", oat_fd_);
523 }
524 } else if (option == "--watch-dog") {
525 watch_dog_enabled = true;
526 } else if (option == "--no-watch-dog") {
527 watch_dog_enabled = false;
528 } else if (option == "--gen-gdb-info") {
529 generate_gdb_information = true;
530 // Debug symbols are needed for gdb information.
531 include_debug_symbols = true;
532 } else if (option == "--no-gen-gdb-info") {
533 generate_gdb_information = false;
534 } else if (option.starts_with("-j")) {
535 const char* thread_count_str = option.substr(strlen("-j")).data();
536 if (!ParseUint(thread_count_str, &thread_count_)) {
537 Usage("Failed to parse -j argument '%s' as an integer", thread_count_str);
538 }
539 } else if (option.starts_with("--oat-location=")) {
540 oat_location_ = option.substr(strlen("--oat-location=")).data();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800541 } else if (option.starts_with("--image=")) {
542 image_filename_ = option.substr(strlen("--image=")).data();
543 } else if (option.starts_with("--image-classes=")) {
544 image_classes_filename_ = option.substr(strlen("--image-classes=")).data();
545 } else if (option.starts_with("--image-classes-zip=")) {
546 image_classes_zip_filename_ = option.substr(strlen("--image-classes-zip=")).data();
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800547 } else if (option.starts_with("--compiled-classes=")) {
548 compiled_classes_filename_ = option.substr(strlen("--compiled-classes=")).data();
549 } else if (option.starts_with("--compiled-classes-zip=")) {
550 compiled_classes_zip_filename_ = option.substr(strlen("--compiled-classes-zip=")).data();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800551 } else if (option.starts_with("--base=")) {
552 const char* image_base_str = option.substr(strlen("--base=")).data();
553 char* end;
554 image_base_ = strtoul(image_base_str, &end, 16);
555 if (end == image_base_str || *end != '\0') {
556 Usage("Failed to parse hexadecimal value for option %s", option.data());
557 }
558 } else if (option.starts_with("--boot-image=")) {
559 boot_image_filename = option.substr(strlen("--boot-image=")).data();
560 } else if (option.starts_with("--android-root=")) {
561 android_root_ = option.substr(strlen("--android-root=")).data();
562 } else if (option.starts_with("--instruction-set=")) {
563 StringPiece instruction_set_str = option.substr(strlen("--instruction-set=")).data();
564 // StringPiece is not necessarily zero-terminated, so need to make a copy and ensure it.
Dan Albert6fc59ab2014-12-11 14:09:51 -0800565 std::unique_ptr<char[]> buf(new char[instruction_set_str.length() + 1]);
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800566 strncpy(buf.get(), instruction_set_str.data(), instruction_set_str.length());
567 buf.get()[instruction_set_str.length()] = 0;
568 instruction_set_ = GetInstructionSetFromString(buf.get());
569 // arm actually means thumb2.
570 if (instruction_set_ == InstructionSet::kArm) {
571 instruction_set_ = InstructionSet::kThumb2;
572 }
573 } else if (option.starts_with("--instruction-set-variant=")) {
574 StringPiece str = option.substr(strlen("--instruction-set-variant=")).data();
575 instruction_set_features_.reset(
576 InstructionSetFeatures::FromVariant(instruction_set_, str.as_string(), &error_msg));
577 if (instruction_set_features_.get() == nullptr) {
578 Usage("%s", error_msg.c_str());
579 }
580 } else if (option.starts_with("--instruction-set-features=")) {
581 StringPiece str = option.substr(strlen("--instruction-set-features=")).data();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800582 if (instruction_set_features_.get() == nullptr) {
Ian Rogersd582fa42014-11-05 23:46:43 -0800583 instruction_set_features_.reset(
584 InstructionSetFeatures::FromVariant(instruction_set_, "default", &error_msg));
585 if (instruction_set_features_.get() == nullptr) {
586 Usage("Problem initializing default instruction set features variant: %s",
587 error_msg.c_str());
588 }
589 }
590 instruction_set_features_.reset(
591 instruction_set_features_->AddFeaturesFromString(str.as_string(), &error_msg));
592 if (instruction_set_features_.get() == nullptr) {
593 Usage("Error parsing '%s': %s", option.data(), error_msg.c_str());
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800594 }
595 } else if (option.starts_with("--compiler-backend=")) {
596 StringPiece backend_str = option.substr(strlen("--compiler-backend=")).data();
597 if (backend_str == "Quick") {
598 compiler_kind_ = Compiler::kQuick;
599 } else if (backend_str == "Optimizing") {
600 compiler_kind_ = Compiler::kOptimizing;
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800601 } else {
602 Usage("Unknown compiler backend: %s", backend_str.data());
603 }
604 } else if (option.starts_with("--compiler-filter=")) {
605 compiler_filter_string = option.substr(strlen("--compiler-filter=")).data();
606 } else if (option == "--compile-pic") {
607 compile_pic = true;
608 } else if (option.starts_with("--huge-method-max=")) {
609 const char* threshold = option.substr(strlen("--huge-method-max=")).data();
610 if (!ParseInt(threshold, &huge_method_threshold)) {
611 Usage("Failed to parse --huge-method-max '%s' as an integer", threshold);
612 }
613 if (huge_method_threshold < 0) {
614 Usage("--huge-method-max passed a negative value %s", huge_method_threshold);
615 }
616 } else if (option.starts_with("--large-method-max=")) {
617 const char* threshold = option.substr(strlen("--large-method-max=")).data();
618 if (!ParseInt(threshold, &large_method_threshold)) {
619 Usage("Failed to parse --large-method-max '%s' as an integer", threshold);
620 }
621 if (large_method_threshold < 0) {
622 Usage("--large-method-max passed a negative value %s", large_method_threshold);
623 }
624 } else if (option.starts_with("--small-method-max=")) {
625 const char* threshold = option.substr(strlen("--small-method-max=")).data();
626 if (!ParseInt(threshold, &small_method_threshold)) {
627 Usage("Failed to parse --small-method-max '%s' as an integer", threshold);
628 }
629 if (small_method_threshold < 0) {
630 Usage("--small-method-max passed a negative value %s", small_method_threshold);
631 }
632 } else if (option.starts_with("--tiny-method-max=")) {
633 const char* threshold = option.substr(strlen("--tiny-method-max=")).data();
634 if (!ParseInt(threshold, &tiny_method_threshold)) {
635 Usage("Failed to parse --tiny-method-max '%s' as an integer", threshold);
636 }
637 if (tiny_method_threshold < 0) {
638 Usage("--tiny-method-max passed a negative value %s", tiny_method_threshold);
639 }
640 } else if (option.starts_with("--num-dex-methods=")) {
641 const char* threshold = option.substr(strlen("--num-dex-methods=")).data();
642 if (!ParseInt(threshold, &num_dex_methods_threshold)) {
643 Usage("Failed to parse --num-dex-methods '%s' as an integer", threshold);
644 }
645 if (num_dex_methods_threshold < 0) {
646 Usage("--num-dex-methods passed a negative value %s", num_dex_methods_threshold);
647 }
648 } else if (option == "--host") {
649 is_host_ = true;
650 } else if (option == "--runtime-arg") {
651 if (++i >= argc) {
652 Usage("Missing required argument for --runtime-arg");
653 }
654 if (log_options) {
655 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i];
656 }
657 runtime_args_.push_back(argv[i]);
658 } else if (option == "--dump-timing") {
659 dump_timing_ = true;
660 } else if (option == "--dump-passes") {
661 dump_passes_ = true;
662 } else if (option == "--dump-stats") {
663 dump_stats_ = true;
664 } else if (option == "--include-debug-symbols" || option == "--no-strip-symbols") {
665 include_debug_symbols = true;
666 } else if (option == "--no-include-debug-symbols" || option == "--strip-symbols") {
667 include_debug_symbols = false;
668 generate_gdb_information = false; // Depends on debug symbols, see above.
669 } else if (option.starts_with("--profile-file=")) {
670 profile_file_ = option.substr(strlen("--profile-file=")).data();
671 VLOG(compiler) << "dex2oat: profile file is " << profile_file_;
672 } else if (option == "--no-profile-file") {
673 // No profile
674 } else if (option.starts_with("--top-k-profile-threshold=")) {
675 ParseDouble(option.data(), '=', 0.0, 100.0, &top_k_profile_threshold);
676 } else if (option == "--print-pass-names") {
677 PassDriverMEOpts::PrintPassNames();
678 } else if (option.starts_with("--disable-passes=")) {
679 std::string disable_passes = option.substr(strlen("--disable-passes=")).data();
680 PassDriverMEOpts::CreateDefaultPassList(disable_passes);
681 } else if (option.starts_with("--print-passes=")) {
682 std::string print_passes = option.substr(strlen("--print-passes=")).data();
683 PassDriverMEOpts::SetPrintPassList(print_passes);
684 } else if (option == "--print-all-passes") {
685 PassDriverMEOpts::SetPrintAllPasses();
686 } else if (option.starts_with("--dump-cfg-passes=")) {
687 std::string dump_passes_string = option.substr(strlen("--dump-cfg-passes=")).data();
688 PassDriverMEOpts::SetDumpPassList(dump_passes_string);
689 } else if (option == "--print-pass-options") {
690 print_pass_options = true;
691 } else if (option.starts_with("--pass-options=")) {
692 std::string options = option.substr(strlen("--pass-options=")).data();
693 PassDriverMEOpts::SetOverriddenPassOptions(options);
694 } else if (option == "--include-patch-information") {
695 include_patch_information = true;
696 } else if (option == "--no-include-patch-information") {
697 include_patch_information = false;
698 } else if (option.starts_with("--verbose-methods=")) {
Brian Carlstrom95b033b2014-12-03 22:29:37 -0800699 // TODO: rather than switch off compiler logging, make all VLOG(compiler) messages
700 // conditional on having verbost methods.
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800701 gLogVerbosity.compiler = false;
702 Split(option.substr(strlen("--verbose-methods=")).ToString(), ',', &verbose_methods_);
Andreas Gampedbfe2542014-11-25 22:21:42 -0800703 } else if (option.starts_with("--dump-init-failures=")) {
704 std::string file_name = option.substr(strlen("--dump-init-failures=")).data();
705 init_failure_output_.reset(new std::ofstream(file_name));
706 if (init_failure_output_.get() == nullptr) {
707 LOG(ERROR) << "Failed to allocate ofstream";
708 } else if (init_failure_output_->fail()) {
709 LOG(ERROR) << "Failed to open " << file_name << " for writing the initialization "
710 << "failures.";
711 init_failure_output_.reset();
712 }
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800713 } else if (option.starts_with("--swap-file=")) {
714 swap_file_name_ = option.substr(strlen("--swap-file=")).data();
715 } else if (option.starts_with("--swap-fd=")) {
716 const char* swap_fd_str = option.substr(strlen("--swap-fd=")).data();
717 if (!ParseInt(swap_fd_str, &swap_fd_)) {
718 Usage("Failed to parse --swap-fd argument '%s' as an integer", swap_fd_str);
719 }
720 if (swap_fd_ < 0) {
721 Usage("--swap-fd passed a negative value %d", swap_fd_);
722 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800723 } else {
724 Usage("Unknown argument %s", option.data());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700725 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800726 }
727
Nicolas Geoffray9bb492a2014-11-25 23:42:00 +0000728 if (compiler_kind_ == Compiler::kOptimizing) {
729 // Optimizing only supports PIC mode.
730 compile_pic = true;
731 }
732
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800733 if (oat_filename_.empty() && oat_fd_ == -1) {
734 Usage("Output must be supplied with either --oat-file or --oat-fd");
735 }
736
737 if (!oat_filename_.empty() && oat_fd_ != -1) {
738 Usage("--oat-file should not be used with --oat-fd");
739 }
740
741 if (!oat_symbols.empty() && oat_fd_ != -1) {
742 Usage("--oat-symbols should not be used with --oat-fd");
743 }
744
745 if (!oat_symbols.empty() && is_host_) {
746 Usage("--oat-symbols should not be used with --host");
747 }
748
749 if (oat_fd_ != -1 && !image_filename_.empty()) {
750 Usage("--oat-fd should not be used with --image");
751 }
752
753 if (android_root_.empty()) {
754 const char* android_root_env_var = getenv("ANDROID_ROOT");
755 if (android_root_env_var == nullptr) {
756 Usage("--android-root unspecified and ANDROID_ROOT not set");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700757 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800758 android_root_ += android_root_env_var;
759 }
760
761 image_ = (!image_filename_.empty());
762 if (!image_ && boot_image_filename.empty()) {
763 boot_image_filename += android_root_;
764 boot_image_filename += "/framework/boot.art";
765 }
766 if (!boot_image_filename.empty()) {
767 boot_image_option_ += "-Ximage:";
768 boot_image_option_ += boot_image_filename;
769 }
770
771 if (image_classes_filename_ != nullptr && !image_) {
772 Usage("--image-classes should only be used with --image");
773 }
774
775 if (image_classes_filename_ != nullptr && !boot_image_option_.empty()) {
776 Usage("--image-classes should not be used with --boot-image");
777 }
778
779 if (image_classes_zip_filename_ != nullptr && image_classes_filename_ == nullptr) {
780 Usage("--image-classes-zip should be used with --image-classes");
781 }
782
Andreas Gampe4bf3ae92014-11-11 13:28:29 -0800783 if (compiled_classes_filename_ != nullptr && !image_) {
784 Usage("--compiled-classes should only be used with --image");
785 }
786
787 if (compiled_classes_filename_ != nullptr && !boot_image_option_.empty()) {
788 Usage("--compiled-classes should not be used with --boot-image");
789 }
790
791 if (compiled_classes_zip_filename_ != nullptr && compiled_classes_filename_ == nullptr) {
792 Usage("--compiled-classes-zip should be used with --compiled-classes");
793 }
794
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800795 if (dex_filenames_.empty() && zip_fd_ == -1) {
796 Usage("Input must be supplied with either --dex-file or --zip-fd");
797 }
798
799 if (!dex_filenames_.empty() && zip_fd_ != -1) {
800 Usage("--dex-file should not be used with --zip-fd");
801 }
802
803 if (!dex_filenames_.empty() && !zip_location_.empty()) {
804 Usage("--dex-file should not be used with --zip-location");
805 }
806
807 if (dex_locations_.empty()) {
808 for (const char* dex_file_name : dex_filenames_) {
809 dex_locations_.push_back(dex_file_name);
810 }
811 } else if (dex_locations_.size() != dex_filenames_.size()) {
812 Usage("--dex-location arguments do not match --dex-file arguments");
813 }
814
815 if (zip_fd_ != -1 && zip_location_.empty()) {
816 Usage("--zip-location should be supplied with --zip-fd");
817 }
818
819 if (boot_image_option_.empty()) {
820 if (image_base_ == 0) {
821 Usage("Non-zero --base not specified");
822 }
823 }
824
825 oat_stripped_ = oat_filename_;
826 if (!oat_symbols.empty()) {
827 oat_unstripped_ = oat_symbols;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700828 } else {
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800829 oat_unstripped_ = oat_filename_;
830 }
831
832 // If no instruction set feature was given, use the default one for the target
833 // instruction set.
834 if (instruction_set_features_.get() == nullptr) {
835 instruction_set_features_.reset(
Ian Rogersd582fa42014-11-05 23:46:43 -0800836 InstructionSetFeatures::FromVariant(instruction_set_, "default", &error_msg));
837 if (instruction_set_features_.get() == nullptr) {
838 Usage("Problem initializing default instruction set features variant: %s",
839 error_msg.c_str());
840 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800841 }
842
843 if (instruction_set_ == kRuntimeISA) {
844 std::unique_ptr<const InstructionSetFeatures> runtime_features(
845 InstructionSetFeatures::FromCppDefines());
846 if (!instruction_set_features_->Equals(runtime_features.get())) {
847 LOG(WARNING) << "Mismatch between dex2oat instruction set features ("
848 << *instruction_set_features_ << ") and those of dex2oat executable ("
849 << *runtime_features <<") for the command line:\n"
850 << CommandLine();
851 }
852 }
853
854 if (compiler_filter_string == nullptr) {
855 if (instruction_set_ == kMips64) {
856 // TODO: fix compiler for Mips64.
857 compiler_filter_string = "interpret-only";
858 } else if (image_) {
859 compiler_filter_string = "speed";
860 } else {
861 // TODO: Migrate SMALL mode to command line option.
862 #if ART_SMALL_MODE
863 compiler_filter_string = "interpret-only";
864 #else
865 compiler_filter_string = "speed";
866 #endif
867 }
868 }
869 CHECK(compiler_filter_string != nullptr);
870 CompilerOptions::CompilerFilter compiler_filter = CompilerOptions::kDefaultCompilerFilter;
871 if (strcmp(compiler_filter_string, "verify-none") == 0) {
872 compiler_filter = CompilerOptions::kVerifyNone;
873 } else if (strcmp(compiler_filter_string, "interpret-only") == 0) {
874 compiler_filter = CompilerOptions::kInterpretOnly;
875 } else if (strcmp(compiler_filter_string, "space") == 0) {
876 compiler_filter = CompilerOptions::kSpace;
877 } else if (strcmp(compiler_filter_string, "balanced") == 0) {
878 compiler_filter = CompilerOptions::kBalanced;
879 } else if (strcmp(compiler_filter_string, "speed") == 0) {
880 compiler_filter = CompilerOptions::kSpeed;
881 } else if (strcmp(compiler_filter_string, "everything") == 0) {
882 compiler_filter = CompilerOptions::kEverything;
883 } else if (strcmp(compiler_filter_string, "time") == 0) {
884 compiler_filter = CompilerOptions::kTime;
885 } else {
886 Usage("Unknown --compiler-filter value %s", compiler_filter_string);
887 }
888
889 // Checks are all explicit until we know the architecture.
890 bool implicit_null_checks = false;
891 bool implicit_so_checks = false;
892 bool implicit_suspend_checks = false;
893 // Set the compilation target's implicit checks options.
894 switch (instruction_set_) {
895 case kArm:
896 case kThumb2:
897 case kArm64:
898 case kX86:
899 case kX86_64:
900 implicit_null_checks = true;
901 implicit_so_checks = true;
902 break;
903
904 default:
905 // Defaults are correct.
906 break;
907 }
908
909 if (print_pass_options) {
910 PassDriverMEOpts::PrintPassOptions();
911 }
912
913 compiler_options_.reset(new CompilerOptions(compiler_filter,
914 huge_method_threshold,
915 large_method_threshold,
916 small_method_threshold,
917 tiny_method_threshold,
918 num_dex_methods_threshold,
919 generate_gdb_information,
920 include_patch_information,
921 top_k_profile_threshold,
922 include_debug_symbols,
923 implicit_null_checks,
924 implicit_so_checks,
925 implicit_suspend_checks,
926 compile_pic,
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800927 verbose_methods_.empty() ?
928 nullptr :
Andreas Gampedbfe2542014-11-25 22:21:42 -0800929 &verbose_methods_,
930 init_failure_output_.get()));
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800931
932 // Done with usage checks, enable watchdog if requested
933 if (watch_dog_enabled) {
934 watchdog_.reset(new WatchDog(true));
935 }
936
937 // Fill some values into the key-value store for the oat header.
938 key_value_store_.reset(new SafeMap<std::string, std::string>());
939
940 // Insert some compiler things.
941 {
942 std::ostringstream oss;
943 for (int i = 0; i < argc; ++i) {
944 if (i > 0) {
945 oss << ' ';
946 }
947 oss << argv[i];
948 }
949 key_value_store_->Put(OatHeader::kDex2OatCmdLineKey, oss.str());
950 oss.str(""); // Reset.
951 oss << kRuntimeISA;
952 key_value_store_->Put(OatHeader::kDex2OatHostKey, oss.str());
953 key_value_store_->Put(OatHeader::kPicKey, compile_pic ? "true" : "false");
954 }
955 }
956
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800957 // Check whether the oat output file is writable, and open it for later. Also open a swap file,
958 // if a name is given.
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800959 bool OpenFile() {
960 bool create_file = !oat_unstripped_.empty(); // as opposed to using open file descriptor
961 if (create_file) {
962 oat_file_.reset(OS::CreateEmptyFile(oat_unstripped_.c_str()));
963 if (oat_location_.empty()) {
964 oat_location_ = oat_filename_;
965 }
966 } else {
Andreas Gampe4303ba92014-11-06 01:00:46 -0800967 oat_file_.reset(new File(oat_fd_, oat_location_, true));
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800968 oat_file_->DisableAutoClose();
Andreas Gampe4303ba92014-11-06 01:00:46 -0800969 if (oat_file_->SetLength(0) != 0) {
970 PLOG(WARNING) << "Truncating oat file " << oat_location_ << " failed.";
971 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800972 }
973 if (oat_file_.get() == nullptr) {
974 PLOG(ERROR) << "Failed to create oat file: " << oat_location_;
975 return false;
976 }
977 if (create_file && fchmod(oat_file_->Fd(), 0644) != 0) {
978 PLOG(ERROR) << "Failed to make oat file world readable: " << oat_location_;
Andreas Gampe4303ba92014-11-06 01:00:46 -0800979 oat_file_->Erase();
Andreas Gampe88ec7f42014-11-05 10:18:32 -0800980 return false;
981 }
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800982
983 // Swap file handling.
984 //
985 // If the swap fd is not -1, we assume this is the file descriptor of an open but unlinked file
986 // that we can use for swap.
987 //
988 // If the swap fd is -1 and we have a swap-file string, open the given file as a swap file. We
989 // will immediately unlink to satisfy the swap fd assumption.
990 if (swap_fd_ == -1 && !swap_file_name_.empty()) {
991 std::unique_ptr<File> swap_file(OS::CreateEmptyFile(swap_file_name_.c_str()));
992 if (swap_file.get() == nullptr) {
993 PLOG(ERROR) << "Failed to create swap file: " << swap_file_name_;
994 return false;
995 }
996 swap_fd_ = swap_file->Fd();
997 swap_file->MarkUnchecked(); // We don't we to track this, it will be unlinked immediately.
998 swap_file->DisableAutoClose(); // We'll handle it ourselves, the File object will be
999 // released immediately.
1000 unlink(swap_file_name_.c_str());
1001 }
1002
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001003 return true;
1004 }
1005
Andreas Gampea650e702014-12-03 14:28:02 -08001006 void EraseOatFile() {
1007 DCHECK(oat_file_.get() != nullptr);
1008 oat_file_->Erase();
1009 oat_file_.reset();
1010 }
1011
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001012 // Set up the environment for compilation. Includes starting the runtime and loading/opening the
1013 // boot class path.
1014 bool Setup() {
1015 TimingLogger::ScopedTiming t("dex2oat Setup", timings_);
1016 RuntimeOptions runtime_options;
1017 std::vector<const DexFile*> boot_class_path;
1018 art::MemMap::Init(); // For ZipEntry::ExtractToMemMap.
1019 if (boot_image_option_.empty()) {
1020 size_t failure_count = OpenDexFiles(dex_filenames_, dex_locations_, boot_class_path);
Brian Carlstrom3cf59d52013-11-10 21:04:10 -08001021 if (failure_count > 0) {
1022 LOG(ERROR) << "Failed to open some dex files: " << failure_count;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001023 return false;
Brian Carlstrom3cf59d52013-11-10 21:04:10 -08001024 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001025 runtime_options.push_back(std::make_pair("bootclasspath", &boot_class_path));
1026 } else {
1027 runtime_options.push_back(std::make_pair(boot_image_option_.c_str(), nullptr));
1028 }
1029 for (size_t i = 0; i < runtime_args_.size(); i++) {
1030 runtime_options.push_back(std::make_pair(runtime_args_[i], nullptr));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001031 }
Brian Carlstromd76e0832013-08-29 15:17:42 -07001032
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001033 verification_results_.reset(new VerificationResults(compiler_options_.get()));
1034 callbacks_.reset(new QuickCompilerCallbacks(verification_results_.get(), &method_inliner_map_));
1035 runtime_options.push_back(std::make_pair("compilercallbacks", callbacks_.get()));
1036 runtime_options.push_back(
1037 std::make_pair("imageinstructionset", GetInstructionSetString(instruction_set_)));
1038
1039 if (!CreateRuntime(runtime_options)) {
1040 return false;
1041 }
1042
1043 // Runtime::Create acquired the mutator_lock_ that is normally given away when we
1044 // Runtime::Start, give it away now so that we don't starve GC.
1045 Thread* self = Thread::Current();
1046 self->TransitionFromRunnableToSuspended(kNative);
1047 // If we're doing the image, override the compiler filter to force full compilation. Must be
1048 // done ahead of WellKnownClasses::Init that causes verification. Note: doesn't force
1049 // compilation of class initializers.
1050 // Whilst we're in native take the opportunity to initialize well known classes.
1051 WellKnownClasses::Init(self->GetJniEnv());
1052
1053 // If --image-classes was specified, calculate the full list of classes to include in the image
1054 if (image_classes_filename_ != nullptr) {
1055 std::string error_msg;
1056 if (image_classes_zip_filename_ != nullptr) {
1057 image_classes_.reset(ReadImageClassesFromZip(image_classes_zip_filename_,
1058 image_classes_filename_,
1059 &error_msg));
1060 } else {
1061 image_classes_.reset(ReadImageClassesFromFile(image_classes_filename_));
1062 }
1063 if (image_classes_.get() == nullptr) {
1064 LOG(ERROR) << "Failed to create list of image classes from '" << image_classes_filename_ <<
1065 "': " << error_msg;
1066 return false;
1067 }
1068 } else if (image_) {
1069 image_classes_.reset(new std::set<std::string>);
1070 }
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001071 // If --compiled-classes was specified, calculate the full list of classes to compile in the
1072 // image.
1073 if (compiled_classes_filename_ != nullptr) {
1074 std::string error_msg;
1075 if (compiled_classes_zip_filename_ != nullptr) {
1076 compiled_classes_.reset(ReadImageClassesFromZip(compiled_classes_zip_filename_,
1077 compiled_classes_filename_,
1078 &error_msg));
1079 } else {
1080 compiled_classes_.reset(ReadImageClassesFromFile(compiled_classes_filename_));
1081 }
1082 if (compiled_classes_.get() == nullptr) {
1083 LOG(ERROR) << "Failed to create list of compiled classes from '"
1084 << compiled_classes_filename_ << "': " << error_msg;
1085 return false;
1086 }
1087 } else if (image_) {
1088 compiled_classes_.reset(nullptr); // By default compile everything.
1089 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001090
1091 if (boot_image_option_.empty()) {
1092 dex_files_ = Runtime::Current()->GetClassLinker()->GetBootClassPath();
1093 } else {
1094 if (dex_filenames_.empty()) {
1095 ATRACE_BEGIN("Opening zip archive from file descriptor");
1096 std::string error_msg;
1097 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(zip_fd_,
1098 zip_location_.c_str(),
1099 &error_msg));
1100 if (zip_archive.get() == nullptr) {
1101 LOG(ERROR) << "Failed to open zip from file descriptor for '" << zip_location_ << "': "
1102 << error_msg;
1103 return false;
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001104 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001105 if (!DexFile::OpenFromZip(*zip_archive.get(), zip_location_, &error_msg, &dex_files_)) {
1106 LOG(ERROR) << "Failed to open dex from file descriptor for zip file '" << zip_location_
1107 << "': " << error_msg;
1108 return false;
1109 }
1110 ATRACE_END();
1111 } else {
1112 size_t failure_count = OpenDexFiles(dex_filenames_, dex_locations_, dex_files_);
1113 if (failure_count > 0) {
1114 LOG(ERROR) << "Failed to open some dex files: " << failure_count;
1115 return false;
1116 }
1117 }
1118
1119 constexpr bool kSaveDexInput = false;
1120 if (kSaveDexInput) {
1121 for (size_t i = 0; i < dex_files_.size(); ++i) {
1122 const DexFile* dex_file = dex_files_[i];
Brian Carlstrom95b033b2014-12-03 22:29:37 -08001123 std::string tmp_file_name(StringPrintf("/data/local/tmp/dex2oat.%d.%zd.dex",
1124 getpid(), i));
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001125 std::unique_ptr<File> tmp_file(OS::CreateEmptyFile(tmp_file_name.c_str()));
1126 if (tmp_file.get() == nullptr) {
1127 PLOG(ERROR) << "Failed to open file " << tmp_file_name
1128 << ". Try: adb shell chmod 777 /data/local/tmp";
1129 continue;
1130 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001131 // This is just dumping files for debugging. Ignore errors, and leave remnants.
1132 UNUSED(tmp_file->WriteFully(dex_file->Begin(), dex_file->Size()));
1133 UNUSED(tmp_file->Flush());
1134 UNUSED(tmp_file->Close());
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001135 LOG(INFO) << "Wrote input to " << tmp_file_name;
1136 }
Brian Carlstromf79fccb2014-02-20 08:55:10 -08001137 }
1138 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001139 // Ensure opened dex files are writable for dex-to-dex transformations.
1140 for (const auto& dex_file : dex_files_) {
1141 if (!dex_file->EnableWrite()) {
1142 PLOG(ERROR) << "Failed to make .dex file writeable '" << dex_file->GetLocation() << "'\n";
Andreas Gampe7ba64962014-10-23 11:37:40 -07001143 }
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001144 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001145
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001146 // If we use a swap file, ensure we are above the threshold to make it necessary.
1147 if (swap_fd_ != -1) {
1148 if (!UseSwap(image_, dex_files_)) {
1149 close(swap_fd_);
1150 swap_fd_ = -1;
1151 LOG(INFO) << "Decided to run without swap.";
1152 } else {
1153 LOG(INFO) << "Accepted running with swap.";
1154 }
1155 }
1156 // Note that dex2oat won't close the swap_fd_. The compiler driver's swap space will do that.
1157
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001158 /*
1159 * If we're not in interpret-only or verify-none mode, go ahead and compile small applications.
1160 * Don't bother to check if we're doing the image.
1161 */
Brian Carlstrom95b033b2014-12-03 22:29:37 -08001162 if (!image_ &&
1163 compiler_options_->IsCompilationEnabled() &&
1164 compiler_kind_ == Compiler::kQuick) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001165 size_t num_methods = 0;
1166 for (size_t i = 0; i != dex_files_.size(); ++i) {
1167 const DexFile* dex_file = dex_files_[i];
1168 CHECK(dex_file != nullptr);
1169 num_methods += dex_file->NumMethodIds();
1170 }
1171 if (num_methods <= compiler_options_->GetNumDexMethodsThreshold()) {
1172 compiler_options_->SetCompilerFilter(CompilerOptions::kSpeed);
1173 VLOG(compiler) << "Below method threshold, compiling anyways";
1174 }
1175 }
1176
1177 return true;
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001178 }
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001179
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001180 // Create and invoke the compiler driver. This will compile all the dex files.
1181 void Compile() {
1182 TimingLogger::ScopedTiming t("dex2oat Compile", timings_);
1183 compiler_phases_timings_.reset(new CumulativeLogger("compilation times"));
Vladimir Markof4da6752014-08-01 19:04:18 +01001184
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001185 // Handle and ClassLoader creation needs to come after Runtime::Create
1186 jobject class_loader = nullptr;
1187 Thread* self = Thread::Current();
1188 if (!boot_image_option_.empty()) {
1189 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1190 std::vector<const DexFile*> class_path_files(dex_files_);
1191 OpenClassPathFiles(runtime_->GetClassPathString(), class_path_files);
1192 ScopedObjectAccess soa(self);
1193 for (size_t i = 0; i < class_path_files.size(); i++) {
1194 class_linker->RegisterDexFile(*class_path_files[i]);
1195 }
1196 soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader);
1197 ScopedLocalRef<jobject> class_loader_local(soa.Env(),
1198 soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader));
1199 class_loader = soa.Env()->NewGlobalRef(class_loader_local.get());
1200 Runtime::Current()->SetCompileTimeClassPath(class_loader, class_path_files);
1201 }
1202
1203 driver_.reset(new CompilerDriver(compiler_options_.get(),
1204 verification_results_.get(),
1205 &method_inliner_map_,
1206 compiler_kind_,
1207 instruction_set_,
1208 instruction_set_features_.get(),
1209 image_,
1210 image_classes_.release(),
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001211 compiled_classes_.release(),
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001212 thread_count_,
1213 dump_stats_,
1214 dump_passes_,
1215 compiler_phases_timings_.get(),
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001216 swap_fd_,
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001217 profile_file_));
1218
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001219 driver_->CompileAll(class_loader, dex_files_, timings_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001220 }
1221
Brian Carlstrom7940e442013-07-12 13:46:57 -07001222 // Notes on the interleaving of creating the image and oat file to
1223 // ensure the references between the two are correct.
1224 //
1225 // Currently we have a memory layout that looks something like this:
1226 //
1227 // +--------------+
1228 // | image |
1229 // +--------------+
1230 // | boot oat |
1231 // +--------------+
1232 // | alloc spaces |
1233 // +--------------+
1234 //
Brian Carlstrom45602482013-07-21 22:07:55 -07001235 // There are several constraints on the loading of the image and boot.oat.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001236 //
1237 // 1. The image is expected to be loaded at an absolute address and
1238 // contains Objects with absolute pointers within the image.
1239 //
1240 // 2. There are absolute pointers from Methods in the image to their
1241 // code in the oat.
1242 //
1243 // 3. There are absolute pointers from the code in the oat to Methods
1244 // in the image.
1245 //
1246 // 4. There are absolute pointers from code in the oat to other code
1247 // in the oat.
1248 //
1249 // To get this all correct, we go through several steps.
1250 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001251 // 1. We prepare offsets for all data in the oat file and calculate
1252 // the oat data size and code size. During this stage, we also set
1253 // oat code offsets in methods for use by the image writer.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001254 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001255 // 2. We prepare offsets for the objects in the image and calculate
1256 // the image size.
1257 //
1258 // 3. We create the oat file. Originally this was just our own proprietary
1259 // file but now it is contained within an ELF dynamic object (aka an .so
1260 // file). Since we know the image size and oat data size and code size we
1261 // can prepare the ELF headers and we then know the ELF memory segment
1262 // layout and we can now resolve all references. The compiler provides
1263 // LinkerPatch information in each CompiledMethod and we resolve these,
1264 // using the layout information and image object locations provided by
1265 // image writer, as we're writing the method code.
1266 //
1267 // 4. We create the image file. It needs to know where the oat file
Brian Carlstrom7940e442013-07-12 13:46:57 -07001268 // will be loaded after itself. Originally when oat file was simply
1269 // memory mapped so we could predict where its contents were based
1270 // on the file size. Now that it is an ELF file, we need to inspect
1271 // the ELF file to understand the in memory segment layout including
Vladimir Markof4da6752014-08-01 19:04:18 +01001272 // where the oat header is located within.
1273 // TODO: We could just remember this information from step 3.
Brian Carlstrom7940e442013-07-12 13:46:57 -07001274 //
Vladimir Markof4da6752014-08-01 19:04:18 +01001275 // 5. We fixup the ELF program headers so that dlopen will try to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001276 // load the .so at the desired location at runtime by offsetting the
1277 // Elf32_Phdr.p_vaddr values by the desired base address.
Vladimir Markof4da6752014-08-01 19:04:18 +01001278 // TODO: Do this in step 3. We already know the layout there.
1279 //
1280 // Steps 1.-3. are done by the CreateOatFile() above, steps 4.-5.
1281 // are done by the CreateImageFile() below.
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001282
1283
1284 // Write out the generated code part. Calls the OatWriter and ElfBuilder. Also prepares the
1285 // ImageWriter, if necessary.
Andreas Gampe10e477d2014-11-19 12:57:42 -08001286 // Note: Flushing (and closing) the file is the caller's responsibility, except for the failure
1287 // case (when the file will be explicitly erased).
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001288 bool CreateOatFile() {
1289 CHECK(key_value_store_.get() != nullptr);
1290
1291 TimingLogger::ScopedTiming t("dex2oat Oat", timings_);
1292
1293 std::unique_ptr<OatWriter> oat_writer;
1294 {
1295 TimingLogger::ScopedTiming t2("dex2oat OatWriter", timings_);
1296 std::string image_file_location;
1297 uint32_t image_file_location_oat_checksum = 0;
1298 uintptr_t image_file_location_oat_data_begin = 0;
1299 int32_t image_patch_delta = 0;
1300 if (image_) {
1301 PrepareImageWriter(image_base_);
1302 } else {
1303 TimingLogger::ScopedTiming t3("Loading image checksum", timings_);
1304 gc::space::ImageSpace* image_space = Runtime::Current()->GetHeap()->GetImageSpace();
1305 image_file_location_oat_checksum = image_space->GetImageHeader().GetOatChecksum();
1306 image_file_location_oat_data_begin =
1307 reinterpret_cast<uintptr_t>(image_space->GetImageHeader().GetOatDataBegin());
1308 image_file_location = image_space->GetImageFilename();
1309 image_patch_delta = image_space->GetImageHeader().GetPatchDelta();
1310 }
1311
1312 if (!image_file_location.empty()) {
1313 key_value_store_->Put(OatHeader::kImageLocationKey, image_file_location);
1314 }
1315
1316 oat_writer.reset(new OatWriter(dex_files_, image_file_location_oat_checksum,
1317 image_file_location_oat_data_begin,
1318 image_patch_delta,
1319 driver_.get(),
1320 image_writer_.get(),
1321 timings_,
1322 key_value_store_.get()));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001323 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001324
1325 if (image_) {
1326 // The OatWriter constructor has already updated offsets in methods and we need to
1327 // prepare method offsets in the image address space for direct method patching.
1328 TimingLogger::ScopedTiming t2("dex2oat Prepare image address space", timings_);
1329 if (!image_writer_->PrepareImageAddressSpace()) {
1330 LOG(ERROR) << "Failed to prepare image address space.";
1331 return false;
1332 }
1333 }
1334
1335 {
1336 TimingLogger::ScopedTiming t2("dex2oat Write ELF", timings_);
1337 if (!driver_->WriteElf(android_root_, is_host_, dex_files_, oat_writer.get(),
1338 oat_file_.get())) {
1339 LOG(ERROR) << "Failed to write ELF file " << oat_file_->GetPath();
1340 return false;
1341 }
1342 }
1343
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001344 VLOG(compiler) << "Oat file written successfully (unstripped): " << oat_location_;
1345 return true;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001346 }
1347
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001348 // If we are compiling an image, invoke the image creation routine. Else just skip.
1349 bool HandleImage() {
1350 if (image_) {
1351 TimingLogger::ScopedTiming t("dex2oat ImageWriter", timings_);
1352 if (!CreateImageFile()) {
1353 return false;
1354 }
1355 VLOG(compiler) << "Image written successfully: " << image_filename_;
Brian Carlstrom45602482013-07-21 22:07:55 -07001356 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001357 return true;
1358 }
1359
Andreas Gampe10e477d2014-11-19 12:57:42 -08001360 // Create a copy from unstripped to stripped.
1361 bool CopyUnstrippedToStripped() {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001362 // If we don't want to strip in place, copy from unstripped location to stripped location.
1363 // We need to strip after image creation because FixupElf needs to use .strtab.
1364 if (oat_unstripped_ != oat_stripped_) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08001365 // If the oat file is still open, flush it.
1366 if (oat_file_.get() != nullptr && oat_file_->IsOpened()) {
1367 if (!FlushCloseOatFile()) {
1368 return false;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001369 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001370 }
Andreas Gampe10e477d2014-11-19 12:57:42 -08001371
1372 TimingLogger::ScopedTiming t("dex2oat OatFile copy", timings_);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001373 std::unique_ptr<File> in(OS::OpenFileForReading(oat_unstripped_.c_str()));
1374 std::unique_ptr<File> out(OS::CreateEmptyFile(oat_stripped_.c_str()));
1375 size_t buffer_size = 8192;
Dan Albert6fc59ab2014-12-11 14:09:51 -08001376 std::unique_ptr<uint8_t[]> buffer(new uint8_t[buffer_size]);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001377 while (true) {
1378 int bytes_read = TEMP_FAILURE_RETRY(read(in->Fd(), buffer.get(), buffer_size));
1379 if (bytes_read <= 0) {
1380 break;
1381 }
1382 bool write_ok = out->WriteFully(buffer.get(), bytes_read);
1383 CHECK(write_ok);
1384 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08001385 if (out->FlushCloseOrErase() != 0) {
1386 PLOG(ERROR) << "Failed to flush and close copied oat file: " << oat_stripped_;
1387 return false;
Andreas Gampe10e477d2014-11-19 12:57:42 -08001388 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001389 VLOG(compiler) << "Oat file copied successfully (stripped): " << oat_stripped_;
Nicolas Geoffrayea3fa0b2014-02-10 11:59:41 +00001390 }
Andreas Gampe10e477d2014-11-19 12:57:42 -08001391 return true;
1392 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001393
Andreas Gampe10e477d2014-11-19 12:57:42 -08001394 bool FlushOatFile() {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001395 if (oat_file_.get() != nullptr) {
Andreas Gampe10e477d2014-11-19 12:57:42 -08001396 TimingLogger::ScopedTiming t2("dex2oat Flush ELF", timings_);
1397 if (oat_file_->Flush() != 0) {
1398 PLOG(ERROR) << "Failed to flush oat file: " << oat_location_ << " / "
1399 << oat_filename_;
1400 oat_file_->Erase();
1401 return false;
1402 }
1403 }
1404 return true;
1405 }
1406
1407 bool FlushCloseOatFile() {
1408 if (oat_file_.get() != nullptr) {
1409 std::unique_ptr<File> tmp(oat_file_.release());
1410 if (tmp->FlushCloseOrErase() != 0) {
1411 PLOG(ERROR) << "Failed to flush and close oat file: " << oat_location_ << " / "
1412 << oat_filename_;
1413 return false;
Andreas Gampe4303ba92014-11-06 01:00:46 -08001414 }
1415 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001416 return true;
1417 }
1418
1419 void DumpTiming() {
1420 if (dump_timing_ || (dump_slow_timing_ && timings_->GetTotalNs() > MsToNs(1000))) {
1421 LOG(INFO) << Dumpable<TimingLogger>(*timings_);
1422 }
1423 if (dump_passes_) {
1424 LOG(INFO) << Dumpable<CumulativeLogger>(*driver_->GetTimingsLogger());
1425 }
1426 }
1427
1428 CompilerOptions* GetCompilerOptions() const {
1429 return compiler_options_.get();
1430 }
1431
Andreas Gampe10e477d2014-11-19 12:57:42 -08001432 bool IsImage() const {
1433 return image_;
1434 }
1435
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001436 bool IsHost() const {
1437 return is_host_;
1438 }
1439
1440 private:
1441 static size_t OpenDexFiles(const std::vector<const char*>& dex_filenames,
1442 const std::vector<const char*>& dex_locations,
1443 std::vector<const DexFile*>& dex_files) {
1444 size_t failure_count = 0;
1445 for (size_t i = 0; i < dex_filenames.size(); i++) {
1446 const char* dex_filename = dex_filenames[i];
1447 const char* dex_location = dex_locations[i];
1448 ATRACE_BEGIN(StringPrintf("Opening dex file '%s'", dex_filenames[i]).c_str());
1449 std::string error_msg;
1450 if (!OS::FileExists(dex_filename)) {
1451 LOG(WARNING) << "Skipping non-existent dex file '" << dex_filename << "'";
1452 continue;
1453 }
1454 if (!DexFile::Open(dex_filename, dex_location, &error_msg, &dex_files)) {
1455 LOG(WARNING) << "Failed to open .dex from file '" << dex_filename << "': " << error_msg;
1456 ++failure_count;
1457 }
1458 ATRACE_END();
1459 }
1460 return failure_count;
1461 }
1462
1463 // Returns true if dex_files has a dex with the named location.
1464 static bool DexFilesContains(const std::vector<const DexFile*>& dex_files,
1465 const std::string& location) {
1466 for (size_t i = 0; i < dex_files.size(); ++i) {
1467 if (dex_files[i]->GetLocation() == location) {
1468 return true;
1469 }
1470 }
1471 return false;
1472 }
1473
1474 // Appends to dex_files any elements of class_path that it doesn't already
1475 // contain. This will open those dex files as necessary.
1476 static void OpenClassPathFiles(const std::string& class_path,
1477 std::vector<const DexFile*>& dex_files) {
1478 std::vector<std::string> parsed;
1479 Split(class_path, ':', &parsed);
1480 // Take Locks::mutator_lock_ so that lock ordering on the ClassLinker::dex_lock_ is maintained.
1481 ScopedObjectAccess soa(Thread::Current());
1482 for (size_t i = 0; i < parsed.size(); ++i) {
1483 if (DexFilesContains(dex_files, parsed[i])) {
1484 continue;
1485 }
1486 std::string error_msg;
1487 if (!DexFile::Open(parsed[i].c_str(), parsed[i].c_str(), &error_msg, &dex_files)) {
1488 LOG(WARNING) << "Failed to open dex file '" << parsed[i] << "': " << error_msg;
1489 }
1490 }
1491 }
1492
1493 // Create a runtime necessary for compilation.
1494 bool CreateRuntime(const RuntimeOptions& runtime_options)
1495 SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_) {
1496 if (!Runtime::Create(runtime_options, false)) {
1497 LOG(ERROR) << "Failed to create runtime";
1498 return false;
1499 }
1500 Runtime* runtime = Runtime::Current();
1501 runtime->SetInstructionSet(instruction_set_);
1502 for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) {
1503 Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i);
1504 if (!runtime->HasCalleeSaveMethod(type)) {
1505 runtime->SetCalleeSaveMethod(runtime->CreateCalleeSaveMethod(), type);
1506 }
1507 }
1508 runtime->GetClassLinker()->FixupDexCaches(runtime->GetResolutionMethod());
1509 runtime->GetClassLinker()->RunRootClinits();
1510 runtime_ = runtime;
1511 return true;
1512 }
1513
1514 void PrepareImageWriter(uintptr_t image_base) {
1515 image_writer_.reset(new ImageWriter(*driver_, image_base, compiler_options_->GetCompilePic()));
1516 }
1517
1518 // Let the ImageWriter write the image file. If we do not compile PIC, also fix up the oat file.
1519 bool CreateImageFile()
1520 LOCKS_EXCLUDED(Locks::mutator_lock_) {
1521 CHECK(image_writer_ != nullptr);
1522 if (!image_writer_->Write(image_filename_, oat_unstripped_, oat_location_)) {
1523 LOG(ERROR) << "Failed to create image file " << image_filename_;
1524 return false;
1525 }
1526 uintptr_t oat_data_begin = image_writer_->GetOatDataBegin();
1527
1528 // Destroy ImageWriter before doing FixupElf.
1529 image_writer_.reset();
1530
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001531 // Do not fix up the ELF file if we are --compile-pic
1532 if (!compiler_options_->GetCompilePic()) {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001533 std::unique_ptr<File> oat_file(OS::OpenFileReadWrite(oat_unstripped_.c_str()));
1534 if (oat_file.get() == nullptr) {
1535 PLOG(ERROR) << "Failed to open ELF file: " << oat_unstripped_;
1536 return false;
1537 }
1538
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001539 if (!ElfWriter::Fixup(oat_file.get(), oat_data_begin)) {
Andreas Gampe4303ba92014-11-06 01:00:46 -08001540 oat_file->Erase();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001541 LOG(ERROR) << "Failed to fixup ELF file " << oat_file->GetPath();
1542 return false;
1543 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001544
1545 if (oat_file->FlushCloseOrErase()) {
1546 PLOG(ERROR) << "Failed to flush and close fixed ELF file " << oat_file->GetPath();
1547 return false;
1548 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001549 }
1550
1551 return true;
1552 }
1553
1554 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
1555 static std::set<std::string>* ReadImageClassesFromFile(const char* image_classes_filename) {
1556 std::unique_ptr<std::ifstream> image_classes_file(new std::ifstream(image_classes_filename,
1557 std::ifstream::in));
1558 if (image_classes_file.get() == nullptr) {
1559 LOG(ERROR) << "Failed to open image classes file " << image_classes_filename;
1560 return nullptr;
1561 }
1562 std::unique_ptr<std::set<std::string>> result(ReadImageClasses(*image_classes_file));
1563 image_classes_file->close();
1564 return result.release();
1565 }
1566
1567 static std::set<std::string>* ReadImageClasses(std::istream& image_classes_stream) {
1568 std::unique_ptr<std::set<std::string>> image_classes(new std::set<std::string>);
1569 while (image_classes_stream.good()) {
1570 std::string dot;
1571 std::getline(image_classes_stream, dot);
1572 if (StartsWith(dot, "#") || dot.empty()) {
1573 continue;
1574 }
1575 std::string descriptor(DotToDescriptor(dot.c_str()));
1576 image_classes->insert(descriptor);
1577 }
1578 return image_classes.release();
1579 }
1580
1581 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;)
1582 static std::set<std::string>* ReadImageClassesFromZip(const char* zip_filename,
1583 const char* image_classes_filename,
1584 std::string* error_msg) {
1585 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::Open(zip_filename, error_msg));
1586 if (zip_archive.get() == nullptr) {
1587 return nullptr;
1588 }
1589 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(image_classes_filename, error_msg));
1590 if (zip_entry.get() == nullptr) {
1591 *error_msg = StringPrintf("Failed to find '%s' within '%s': %s", image_classes_filename,
1592 zip_filename, error_msg->c_str());
1593 return nullptr;
1594 }
1595 std::unique_ptr<MemMap> image_classes_file(zip_entry->ExtractToMemMap(zip_filename,
1596 image_classes_filename,
1597 error_msg));
1598 if (image_classes_file.get() == nullptr) {
1599 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", image_classes_filename,
1600 zip_filename, error_msg->c_str());
1601 return nullptr;
1602 }
1603 const std::string image_classes_string(reinterpret_cast<char*>(image_classes_file->Begin()),
1604 image_classes_file->Size());
1605 std::istringstream image_classes_stream(image_classes_string);
1606 return ReadImageClasses(image_classes_stream);
1607 }
1608
Mathieu Chartier49285c52014-12-02 15:43:48 -08001609 void LogCompletionTime() {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001610 LOG(INFO) << "dex2oat took " << PrettyDuration(NanoTime() - start_ns_)
Mathieu Chartierab972ef2014-12-03 17:38:22 -08001611 << " (threads: " << thread_count_ << ") "
1612 << driver_->GetMemoryUsageString();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001613 }
1614
1615 std::unique_ptr<CompilerOptions> compiler_options_;
1616 Compiler::Kind compiler_kind_;
1617
1618 InstructionSet instruction_set_;
1619 std::unique_ptr<const InstructionSetFeatures> instruction_set_features_;
1620
1621 std::unique_ptr<SafeMap<std::string, std::string> > key_value_store_;
1622
1623 std::unique_ptr<VerificationResults> verification_results_;
1624 DexFileToMethodInlinerMap method_inliner_map_;
1625 std::unique_ptr<QuickCompilerCallbacks> callbacks_;
1626
1627 // Not a unique_ptr as we want to just exit on non-debug builds, not bringing the runtime down
1628 // in an orderly fashion. The destructor takes care of deleting this.
1629 Runtime* runtime_;
1630
1631 size_t thread_count_;
1632 uint64_t start_ns_;
1633 std::unique_ptr<WatchDog> watchdog_;
1634 std::unique_ptr<File> oat_file_;
1635 std::string oat_stripped_;
1636 std::string oat_unstripped_;
1637 std::string oat_location_;
1638 std::string oat_filename_;
1639 int oat_fd_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001640 std::vector<const char*> dex_filenames_;
1641 std::vector<const char*> dex_locations_;
1642 int zip_fd_;
1643 std::string zip_location_;
1644 std::string boot_image_option_;
1645 std::vector<const char*> runtime_args_;
1646 std::string image_filename_;
1647 uintptr_t image_base_;
1648 const char* image_classes_zip_filename_;
1649 const char* image_classes_filename_;
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001650 const char* compiled_classes_zip_filename_;
1651 const char* compiled_classes_filename_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001652 std::unique_ptr<std::set<std::string>> image_classes_;
Andreas Gampe4bf3ae92014-11-11 13:28:29 -08001653 std::unique_ptr<std::set<std::string>> compiled_classes_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001654 bool image_;
1655 std::unique_ptr<ImageWriter> image_writer_;
1656 bool is_host_;
1657 std::string android_root_;
1658 std::vector<const DexFile*> dex_files_;
1659 std::unique_ptr<CompilerDriver> driver_;
1660 std::vector<std::string> verbose_methods_;
1661 bool dump_stats_;
1662 bool dump_passes_;
1663 bool dump_timing_;
1664 bool dump_slow_timing_;
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001665 std::string swap_file_name_;
1666 int swap_fd_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001667 std::string profile_file_; // Profile file to use
1668 TimingLogger* timings_;
1669 std::unique_ptr<CumulativeLogger> compiler_phases_timings_;
Andreas Gampedbfe2542014-11-25 22:21:42 -08001670 std::unique_ptr<std::ostream> init_failure_output_;
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001671
1672 DISALLOW_IMPLICIT_CONSTRUCTORS(Dex2Oat);
1673};
1674
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001675const unsigned int WatchDog::kWatchDogTimeoutSeconds;
1676
1677static void b13564922() {
1678#if defined(__linux__) && defined(__arm__)
1679 int major, minor;
1680 struct utsname uts;
1681 if (uname(&uts) != -1 &&
1682 sscanf(uts.release, "%d.%d", &major, &minor) == 2 &&
1683 ((major < 3) || ((major == 3) && (minor < 4)))) {
1684 // Kernels before 3.4 don't handle the ASLR well and we can run out of address
1685 // space (http://b/13564922). Work around the issue by inhibiting further mmap() randomization.
1686 int old_personality = personality(0xffffffff);
1687 if ((old_personality & ADDR_NO_RANDOMIZE) == 0) {
1688 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE);
1689 if (new_personality == -1) {
1690 LOG(WARNING) << "personality(. | ADDR_NO_RANDOMIZE) failed.";
1691 }
1692 }
1693 }
1694#endif
1695}
1696
Andreas Gampe10e477d2014-11-19 12:57:42 -08001697static int CompileImage(Dex2Oat& dex2oat) {
1698 dex2oat.Compile();
1699
1700 // Create the boot.oat.
1701 if (!dex2oat.CreateOatFile()) {
Andreas Gampea650e702014-12-03 14:28:02 -08001702 dex2oat.EraseOatFile();
Andreas Gampe10e477d2014-11-19 12:57:42 -08001703 return EXIT_FAILURE;
1704 }
1705
1706 // Flush and close the boot.oat. We always expect the output file by name, and it will be
1707 // re-opened from the unstripped name.
1708 if (!dex2oat.FlushCloseOatFile()) {
1709 return EXIT_FAILURE;
1710 }
1711
1712 // Creates the boot.art and patches the boot.oat.
1713 if (!dex2oat.HandleImage()) {
1714 return EXIT_FAILURE;
1715 }
1716
1717 // When given --host, finish early without stripping.
1718 if (dex2oat.IsHost()) {
1719 dex2oat.DumpTiming();
1720 return EXIT_SUCCESS;
1721 }
1722
1723 // Copy unstripped to stripped location, if necessary.
1724 if (!dex2oat.CopyUnstrippedToStripped()) {
1725 return EXIT_FAILURE;
1726 }
1727
Andreas Gampe10e477d2014-11-19 12:57:42 -08001728 // FlushClose again, as stripping might have re-opened the oat file.
1729 if (!dex2oat.FlushCloseOatFile()) {
1730 return EXIT_FAILURE;
1731 }
1732
1733 dex2oat.DumpTiming();
1734 return EXIT_SUCCESS;
1735}
1736
1737static int CompileApp(Dex2Oat& dex2oat) {
1738 dex2oat.Compile();
1739
1740 // Create the app oat.
1741 if (!dex2oat.CreateOatFile()) {
Andreas Gampea650e702014-12-03 14:28:02 -08001742 dex2oat.EraseOatFile();
Andreas Gampe10e477d2014-11-19 12:57:42 -08001743 return EXIT_FAILURE;
1744 }
1745
1746 // Do not close the oat file here. We might haven gotten the output file by file descriptor,
1747 // which we would lose.
1748 if (!dex2oat.FlushOatFile()) {
1749 return EXIT_FAILURE;
1750 }
1751
1752 // When given --host, finish early without stripping.
1753 if (dex2oat.IsHost()) {
1754 if (!dex2oat.FlushCloseOatFile()) {
1755 return EXIT_FAILURE;
1756 }
1757
1758 dex2oat.DumpTiming();
1759 return EXIT_SUCCESS;
1760 }
1761
1762 // Copy unstripped to stripped location, if necessary. This will implicitly flush & close the
1763 // unstripped version. If this is given, we expect to be able to open writable files by name.
1764 if (!dex2oat.CopyUnstrippedToStripped()) {
1765 return EXIT_FAILURE;
1766 }
1767
Andreas Gampe10e477d2014-11-19 12:57:42 -08001768 // Flush and close the file.
1769 if (!dex2oat.FlushCloseOatFile()) {
1770 return EXIT_FAILURE;
1771 }
1772
1773 dex2oat.DumpTiming();
1774 return EXIT_SUCCESS;
1775}
1776
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001777static int dex2oat(int argc, char** argv) {
1778 b13564922();
1779
1780 TimingLogger timings("compiler", false, false);
1781
1782 Dex2Oat dex2oat(&timings);
1783
1784 // Parse arguments. Argument mistakes will lead to exit(EXIT_FAILURE) in UsageError.
1785 dex2oat.ParseArgs(argc, argv);
1786
1787 // Check early that the result of compilation can be written
1788 if (!dex2oat.OpenFile()) {
1789 return EXIT_FAILURE;
1790 }
1791
1792 LOG(INFO) << CommandLine();
1793
1794 if (!dex2oat.Setup()) {
Andreas Gampea650e702014-12-03 14:28:02 -08001795 dex2oat.EraseOatFile();
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001796 return EXIT_FAILURE;
1797 }
1798
Andreas Gampe10e477d2014-11-19 12:57:42 -08001799 if (dex2oat.IsImage()) {
1800 return CompileImage(dex2oat);
1801 } else {
1802 return CompileApp(dex2oat);
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001803 }
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001804}
Brian Carlstrom7934ac22013-07-26 10:54:15 -07001805} // namespace art
Brian Carlstrom7940e442013-07-12 13:46:57 -07001806
1807int main(int argc, char** argv) {
Andreas Gampe88ec7f42014-11-05 10:18:32 -08001808 int result = art::dex2oat(argc, argv);
1809 // Everything was done, do an explicit exit here to avoid running Runtime destructors that take
1810 // time (bug 10645725) unless we're a debug build or running on valgrind. Note: The Dex2Oat class
1811 // should not destruct the runtime in this case.
1812 if (!art::kIsDebugBuild && (RUNNING_ON_VALGRIND == 0)) {
1813 exit(result);
1814 }
1815 return result;
Brian Carlstrom7940e442013-07-12 13:46:57 -07001816}