dex2oat.cc revision c275259449ec57987e52d3ab1eda3272b994488f
1/* 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> 20#include <valgrind.h> 21 22#include <fstream> 23#include <iostream> 24#include <sstream> 25#include <string> 26#include <vector> 27 28#if defined(__linux__) && defined(__arm__) 29#include <sys/personality.h> 30#include <sys/utsname.h> 31#endif 32 33#define ATRACE_TAG ATRACE_TAG_DALVIK 34#include <cutils/trace.h> 35 36#include "arch/instruction_set_features.h" 37#include "base/dumpable.h" 38#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" 43#include "compiler.h" 44#include "compiler_callbacks.h" 45#include "dex_file-inl.h" 46#include "dex/pass_driver_me_opts.h" 47#include "dex/verification_results.h" 48#include "dex/quick_compiler_callbacks.h" 49#include "dex/quick/dex_file_to_method_inliner_map.h" 50#include "driver/compiler_driver.h" 51#include "driver/compiler_options.h" 52#include "elf_file.h" 53#include "elf_writer.h" 54#include "gc/space/image_space.h" 55#include "gc/space/space-inl.h" 56#include "image_writer.h" 57#include "leb128.h" 58#include "mirror/art_method-inl.h" 59#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" 64#include "os.h" 65#include "runtime.h" 66#include "ScopedLocalRef.h" 67#include "scoped_thread_state_change.h" 68#include "utils.h" 69#include "vector_output_stream.h" 70#include "well_known_classes.h" 71#include "zip_archive.h" 72 73namespace art { 74 75static 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 86static 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 99[[noreturn]] static void Usage(const char* fmt, ...) { 100 va_list ap; 101 va_start(ap, fmt); 102 UsageErrorV(fmt, ap); 103 va_end(ap); 104 105 UsageError("Command: %s", CommandLine().c_str()); 106 107 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(""); 116 UsageError(" --zip-location=<zip-location>: specifies a symbolic name for the file"); 117 UsageError(" corresponding to the file descriptor specified by --zip-fd."); 118 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."); 124 UsageError(" Example: --oat-fd=6"); 125 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(""); 133 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"); 144 UsageError(" Default: $ANDROID_ROOT/system/framework/boot.art"); 145 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(""); 150 UsageError(" --instruction-set=(arm|arm64|mips|x86|x86_64): compile for a particular"); 151 UsageError(" instruction set."); 152 UsageError(" Example: --instruction-set=x86"); 153 UsageError(" Default: arm"); 154 UsageError(""); 155 UsageError(" --instruction-set-features=...,: Specify instruction set features"); 156 UsageError(" Example: --instruction-set-features=div"); 157 UsageError(" Default: default"); 158 UsageError(""); 159 UsageError(" --compile-pic: Force indirect use of code, methods, and classes"); 160 UsageError(" Default: disabled"); 161 UsageError(""); 162 UsageError(" --compiler-backend=(Quick|Optimizing): select compiler backend"); 163 UsageError(" set."); 164 UsageError(" Example: --compiler-backend=Optimizing"); 165 if (kUseOptimizingCompiler) { 166 UsageError(" Default: Optimizing"); 167 } else { 168 UsageError(" Default: Quick"); 169 } 170 UsageError(""); 171 UsageError(" --compiler-filter=" 172 "(verify-none" 173 "|interpret-only" 174 "|space" 175 "|balanced" 176 "|speed" 177 "|everything" 178 "|time):"); 179 UsageError(" select compiler filter."); 180 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"); 214 UsageError(" and the filter is not interpret-only or verify-none, overrides the"); 215 UsageError(" filter to use speed"); 216 UsageError(" Example: --num-dex-method=%d", CompilerOptions::kDefaultNumDexMethodsThreshold); 217 UsageError(" Default: %d", CompilerOptions::kDefaultNumDexMethodsThreshold); 218 UsageError(""); 219 UsageError(" --dump-timing: display a breakdown of where time was spent"); 220 UsageError(""); 221 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(""); 226 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(""); 230 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"); 234 UsageError(""); 235 UsageError(" --profile-file=<filename>: specify profiler output file to use for compilation."); 236 UsageError(""); 237 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(""); 242 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(""); 251 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(""); 257 std::cerr << "See log for usage error information\n"; 258 exit(EXIT_FAILURE); 259} 260 261// 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 { 265// WatchDog defines its own CHECK_PTHREAD_CALL to avoid using LOG which uses locks 266#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: 280 explicit WatchDog(bool is_watch_dog_enabled) { 281 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"; 287 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_init, (&mutex_, nullptr), reason); 288 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_init, (&cond_, nullptr), reason); 289 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 303 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_join, (pthread_, nullptr), reason); 304 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(); 314 return nullptr; 315 } 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 328 [[noreturn]] static void Fatal(const std::string& message) { 329 Message('F', message); 330 exit(1); 331 } 332 333 void Wait() { 334 // TODO: tune the multiplier for GC verification, the following is just to make the timeout 335 // large. 336 int64_t multiplier = kVerifyObjectSupport > kVerifyObjectModeFast ? 100 : 1; 337 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_) { 342 int rc = TEMP_FAILURE_RETRY(pthread_cond_timedwait(&cond_, &mutex_, &timeout_ts)); 343 if (rc == ETIMEDOUT) { 344 Fatal(StringPrintf("dex2oat did not finish after %d seconds", kWatchDogTimeoutSeconds)); 345 } 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. 355 // Debug builds are slower so they have larger timeouts. 356 static const unsigned int kSlowdownFactor = kIsDebugBuild ? 5U : 1U; 357 358 // 6 minutes scaled by kSlowdownFactor. 359 static const unsigned int kWatchDogTimeoutSeconds = kSlowdownFactor * 6 * 60; 360 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}; 369 370static void ParseStringAfterChar(const std::string& s, char c, std::string* parsed_value) { 371 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 379static void ParseDouble(const std::string& option, char after_char, double min, double max, 380 double* parsed_value) { 381 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 402static 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 421class Dex2Oat FINAL { 422 public: 423 explicit Dex2Oat(TimingLogger* timings) : 424 compiler_kind_(kUseOptimizingCompiler ? Compiler::kOptimizing : Compiler::kQuick), 425 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), 436 compiled_classes_zip_filename_(nullptr), 437 compiled_classes_filename_(nullptr), 438 image_(false), 439 is_host_(false), 440 dump_stats_(false), 441 dump_passes_(false), 442 dump_timing_(false), 443 dump_slow_timing_(kIsDebugBuild), 444 swap_fd_(-1), 445 timings_(timings) {} 446 447 ~Dex2Oat() { 448 LogCompletionTime(); // Needs to be before since it accesses the runtime. 449 if (kIsDebugBuild || (RUNNING_ON_VALGRIND != 0)) { 450 delete runtime_; // See field declaration for why this is manual. 451 } 452 } 453 454 // 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; 460 461 InitLogging(argv); 462 463 // Skip over argv[0]. 464 argv++; 465 argc--; 466 467 if (argc == 0) { 468 Usage("No arguments specified"); 469 } 470 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; 495 if (log_options) { 496 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i]; 497 } 498 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(); 541 } 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(); 547 } 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(); 551 } 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. 565 std::unique_ptr<char[]> buf(new char[instruction_set_str.length() + 1]); 566 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(); 582 if (instruction_set_features_.get() == nullptr) { 583 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()); 594 } 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; 601 } 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=")) { 699 // TODO: rather than switch off compiler logging, make all VLOG(compiler) messages 700 // conditional on having verbost methods. 701 gLogVerbosity.compiler = false; 702 Split(option.substr(strlen("--verbose-methods=")).ToString(), ',', &verbose_methods_); 703 } 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 } 713 } 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 } 723 } else { 724 Usage("Unknown argument %s", option.data()); 725 } 726 } 727 728 if (compiler_kind_ == Compiler::kOptimizing) { 729 // Optimizing only supports PIC mode. 730 compile_pic = true; 731 } 732 733 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"); 757 } 758 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 783 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 795 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; 828 } else { 829 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( 836 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 } 841 } 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, 927 verbose_methods_.empty() ? 928 nullptr : 929 &verbose_methods_, 930 init_failure_output_.get())); 931 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 957 // Check whether the oat output file is writable, and open it for later. Also open a swap file, 958 // if a name is given. 959 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 { 967 oat_file_.reset(new File(oat_fd_, oat_location_, true)); 968 oat_file_->DisableAutoClose(); 969 if (oat_file_->SetLength(0) != 0) { 970 PLOG(WARNING) << "Truncating oat file " << oat_location_ << " failed."; 971 } 972 } 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_; 979 oat_file_->Erase(); 980 return false; 981 } 982 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 1003 return true; 1004 } 1005 1006 void EraseOatFile() { 1007 DCHECK(oat_file_.get() != nullptr); 1008 oat_file_->Erase(); 1009 oat_file_.reset(); 1010 } 1011 1012 // 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 art::MemMap::Init(); // For ZipEntry::ExtractToMemMap. 1018 if (boot_image_option_.empty()) { 1019 std::string boot_class_path = "-Xbootclasspath:"; 1020 boot_class_path += Join(dex_filenames_, ':'); 1021 runtime_options.push_back(std::make_pair(boot_class_path, nullptr)); 1022 std::string boot_class_path_locations = "-Xbootclasspath-locations:"; 1023 boot_class_path_locations += Join(dex_locations_, ':'); 1024 runtime_options.push_back(std::make_pair(boot_class_path_locations, nullptr)); 1025 } else { 1026 runtime_options.push_back(std::make_pair(boot_image_option_, nullptr)); 1027 } 1028 for (size_t i = 0; i < runtime_args_.size(); i++) { 1029 runtime_options.push_back(std::make_pair(runtime_args_[i], nullptr)); 1030 } 1031 1032 verification_results_.reset(new VerificationResults(compiler_options_.get())); 1033 callbacks_.reset(new QuickCompilerCallbacks(verification_results_.get(), &method_inliner_map_)); 1034 runtime_options.push_back(std::make_pair("compilercallbacks", callbacks_.get())); 1035 runtime_options.push_back( 1036 std::make_pair("imageinstructionset", GetInstructionSetString(instruction_set_))); 1037 1038 if (!CreateRuntime(runtime_options)) { 1039 return false; 1040 } 1041 1042 // Runtime::Create acquired the mutator_lock_ that is normally given away when we 1043 // Runtime::Start, give it away now so that we don't starve GC. 1044 Thread* self = Thread::Current(); 1045 self->TransitionFromRunnableToSuspended(kNative); 1046 // If we're doing the image, override the compiler filter to force full compilation. Must be 1047 // done ahead of WellKnownClasses::Init that causes verification. Note: doesn't force 1048 // compilation of class initializers. 1049 // Whilst we're in native take the opportunity to initialize well known classes. 1050 WellKnownClasses::Init(self->GetJniEnv()); 1051 1052 // If --image-classes was specified, calculate the full list of classes to include in the image 1053 if (image_classes_filename_ != nullptr) { 1054 std::string error_msg; 1055 if (image_classes_zip_filename_ != nullptr) { 1056 image_classes_.reset(ReadImageClassesFromZip(image_classes_zip_filename_, 1057 image_classes_filename_, 1058 &error_msg)); 1059 } else { 1060 image_classes_.reset(ReadImageClassesFromFile(image_classes_filename_)); 1061 } 1062 if (image_classes_.get() == nullptr) { 1063 LOG(ERROR) << "Failed to create list of image classes from '" << image_classes_filename_ << 1064 "': " << error_msg; 1065 return false; 1066 } 1067 } else if (image_) { 1068 image_classes_.reset(new std::set<std::string>); 1069 } 1070 // If --compiled-classes was specified, calculate the full list of classes to compile in the 1071 // image. 1072 if (compiled_classes_filename_ != nullptr) { 1073 std::string error_msg; 1074 if (compiled_classes_zip_filename_ != nullptr) { 1075 compiled_classes_.reset(ReadImageClassesFromZip(compiled_classes_zip_filename_, 1076 compiled_classes_filename_, 1077 &error_msg)); 1078 } else { 1079 compiled_classes_.reset(ReadImageClassesFromFile(compiled_classes_filename_)); 1080 } 1081 if (compiled_classes_.get() == nullptr) { 1082 LOG(ERROR) << "Failed to create list of compiled classes from '" 1083 << compiled_classes_filename_ << "': " << error_msg; 1084 return false; 1085 } 1086 } else if (image_) { 1087 compiled_classes_.reset(nullptr); // By default compile everything. 1088 } 1089 1090 if (boot_image_option_.empty()) { 1091 dex_files_ = Runtime::Current()->GetClassLinker()->GetBootClassPath(); 1092 } else { 1093 if (dex_filenames_.empty()) { 1094 ATRACE_BEGIN("Opening zip archive from file descriptor"); 1095 std::string error_msg; 1096 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(zip_fd_, 1097 zip_location_.c_str(), 1098 &error_msg)); 1099 if (zip_archive.get() == nullptr) { 1100 LOG(ERROR) << "Failed to open zip from file descriptor for '" << zip_location_ << "': " 1101 << error_msg; 1102 return false; 1103 } 1104 if (!DexFile::OpenFromZip(*zip_archive.get(), zip_location_, &error_msg, &dex_files_)) { 1105 LOG(ERROR) << "Failed to open dex from file descriptor for zip file '" << zip_location_ 1106 << "': " << error_msg; 1107 return false; 1108 } 1109 ATRACE_END(); 1110 } else { 1111 size_t failure_count = OpenDexFiles(dex_filenames_, dex_locations_, dex_files_); 1112 if (failure_count > 0) { 1113 LOG(ERROR) << "Failed to open some dex files: " << failure_count; 1114 return false; 1115 } 1116 } 1117 1118 constexpr bool kSaveDexInput = false; 1119 if (kSaveDexInput) { 1120 for (size_t i = 0; i < dex_files_.size(); ++i) { 1121 const DexFile* dex_file = dex_files_[i]; 1122 std::string tmp_file_name(StringPrintf("/data/local/tmp/dex2oat.%d.%zd.dex", 1123 getpid(), i)); 1124 std::unique_ptr<File> tmp_file(OS::CreateEmptyFile(tmp_file_name.c_str())); 1125 if (tmp_file.get() == nullptr) { 1126 PLOG(ERROR) << "Failed to open file " << tmp_file_name 1127 << ". Try: adb shell chmod 777 /data/local/tmp"; 1128 continue; 1129 } 1130 // This is just dumping files for debugging. Ignore errors, and leave remnants. 1131 UNUSED(tmp_file->WriteFully(dex_file->Begin(), dex_file->Size())); 1132 UNUSED(tmp_file->Flush()); 1133 UNUSED(tmp_file->Close()); 1134 LOG(INFO) << "Wrote input to " << tmp_file_name; 1135 } 1136 } 1137 } 1138 // Ensure opened dex files are writable for dex-to-dex transformations. 1139 for (const auto& dex_file : dex_files_) { 1140 if (!dex_file->EnableWrite()) { 1141 PLOG(ERROR) << "Failed to make .dex file writeable '" << dex_file->GetLocation() << "'\n"; 1142 } 1143 } 1144 1145 // If we use a swap file, ensure we are above the threshold to make it necessary. 1146 if (swap_fd_ != -1) { 1147 if (!UseSwap(image_, dex_files_)) { 1148 close(swap_fd_); 1149 swap_fd_ = -1; 1150 LOG(INFO) << "Decided to run without swap."; 1151 } else { 1152 LOG(INFO) << "Accepted running with swap."; 1153 } 1154 } 1155 // Note that dex2oat won't close the swap_fd_. The compiler driver's swap space will do that. 1156 1157 /* 1158 * If we're not in interpret-only or verify-none mode, go ahead and compile small applications. 1159 * Don't bother to check if we're doing the image. 1160 */ 1161 if (!image_ && 1162 compiler_options_->IsCompilationEnabled() && 1163 compiler_kind_ == Compiler::kQuick) { 1164 size_t num_methods = 0; 1165 for (size_t i = 0; i != dex_files_.size(); ++i) { 1166 const DexFile* dex_file = dex_files_[i]; 1167 CHECK(dex_file != nullptr); 1168 num_methods += dex_file->NumMethodIds(); 1169 } 1170 if (num_methods <= compiler_options_->GetNumDexMethodsThreshold()) { 1171 compiler_options_->SetCompilerFilter(CompilerOptions::kSpeed); 1172 VLOG(compiler) << "Below method threshold, compiling anyways"; 1173 } 1174 } 1175 1176 return true; 1177 } 1178 1179 // Create and invoke the compiler driver. This will compile all the dex files. 1180 void Compile() { 1181 TimingLogger::ScopedTiming t("dex2oat Compile", timings_); 1182 compiler_phases_timings_.reset(new CumulativeLogger("compilation times")); 1183 1184 // Handle and ClassLoader creation needs to come after Runtime::Create 1185 jobject class_loader = nullptr; 1186 Thread* self = Thread::Current(); 1187 if (!boot_image_option_.empty()) { 1188 ClassLinker* class_linker = Runtime::Current()->GetClassLinker(); 1189 std::vector<const DexFile*> class_path_files(dex_files_); 1190 OpenClassPathFiles(runtime_->GetClassPathString(), class_path_files); 1191 ScopedObjectAccess soa(self); 1192 for (size_t i = 0; i < class_path_files.size(); i++) { 1193 class_linker->RegisterDexFile(*class_path_files[i]); 1194 } 1195 soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader); 1196 ScopedLocalRef<jobject> class_loader_local(soa.Env(), 1197 soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader)); 1198 class_loader = soa.Env()->NewGlobalRef(class_loader_local.get()); 1199 Runtime::Current()->SetCompileTimeClassPath(class_loader, class_path_files); 1200 } 1201 1202 driver_.reset(new CompilerDriver(compiler_options_.get(), 1203 verification_results_.get(), 1204 &method_inliner_map_, 1205 compiler_kind_, 1206 instruction_set_, 1207 instruction_set_features_.get(), 1208 image_, 1209 image_classes_.release(), 1210 compiled_classes_.release(), 1211 thread_count_, 1212 dump_stats_, 1213 dump_passes_, 1214 compiler_phases_timings_.get(), 1215 swap_fd_, 1216 profile_file_)); 1217 1218 driver_->CompileAll(class_loader, dex_files_, timings_); 1219 } 1220 1221 // Notes on the interleaving of creating the image and oat file to 1222 // ensure the references between the two are correct. 1223 // 1224 // Currently we have a memory layout that looks something like this: 1225 // 1226 // +--------------+ 1227 // | image | 1228 // +--------------+ 1229 // | boot oat | 1230 // +--------------+ 1231 // | alloc spaces | 1232 // +--------------+ 1233 // 1234 // There are several constraints on the loading of the image and boot.oat. 1235 // 1236 // 1. The image is expected to be loaded at an absolute address and 1237 // contains Objects with absolute pointers within the image. 1238 // 1239 // 2. There are absolute pointers from Methods in the image to their 1240 // code in the oat. 1241 // 1242 // 3. There are absolute pointers from the code in the oat to Methods 1243 // in the image. 1244 // 1245 // 4. There are absolute pointers from code in the oat to other code 1246 // in the oat. 1247 // 1248 // To get this all correct, we go through several steps. 1249 // 1250 // 1. We prepare offsets for all data in the oat file and calculate 1251 // the oat data size and code size. During this stage, we also set 1252 // oat code offsets in methods for use by the image writer. 1253 // 1254 // 2. We prepare offsets for the objects in the image and calculate 1255 // the image size. 1256 // 1257 // 3. We create the oat file. Originally this was just our own proprietary 1258 // file but now it is contained within an ELF dynamic object (aka an .so 1259 // file). Since we know the image size and oat data size and code size we 1260 // can prepare the ELF headers and we then know the ELF memory segment 1261 // layout and we can now resolve all references. The compiler provides 1262 // LinkerPatch information in each CompiledMethod and we resolve these, 1263 // using the layout information and image object locations provided by 1264 // image writer, as we're writing the method code. 1265 // 1266 // 4. We create the image file. It needs to know where the oat file 1267 // will be loaded after itself. Originally when oat file was simply 1268 // memory mapped so we could predict where its contents were based 1269 // on the file size. Now that it is an ELF file, we need to inspect 1270 // the ELF file to understand the in memory segment layout including 1271 // where the oat header is located within. 1272 // TODO: We could just remember this information from step 3. 1273 // 1274 // 5. We fixup the ELF program headers so that dlopen will try to 1275 // load the .so at the desired location at runtime by offsetting the 1276 // Elf32_Phdr.p_vaddr values by the desired base address. 1277 // TODO: Do this in step 3. We already know the layout there. 1278 // 1279 // Steps 1.-3. are done by the CreateOatFile() above, steps 4.-5. 1280 // are done by the CreateImageFile() below. 1281 1282 1283 // Write out the generated code part. Calls the OatWriter and ElfBuilder. Also prepares the 1284 // ImageWriter, if necessary. 1285 // Note: Flushing (and closing) the file is the caller's responsibility, except for the failure 1286 // case (when the file will be explicitly erased). 1287 bool CreateOatFile() { 1288 CHECK(key_value_store_.get() != nullptr); 1289 1290 TimingLogger::ScopedTiming t("dex2oat Oat", timings_); 1291 1292 std::unique_ptr<OatWriter> oat_writer; 1293 { 1294 TimingLogger::ScopedTiming t2("dex2oat OatWriter", timings_); 1295 std::string image_file_location; 1296 uint32_t image_file_location_oat_checksum = 0; 1297 uintptr_t image_file_location_oat_data_begin = 0; 1298 int32_t image_patch_delta = 0; 1299 if (image_) { 1300 PrepareImageWriter(image_base_); 1301 } else { 1302 TimingLogger::ScopedTiming t3("Loading image checksum", timings_); 1303 gc::space::ImageSpace* image_space = Runtime::Current()->GetHeap()->GetImageSpace(); 1304 image_file_location_oat_checksum = image_space->GetImageHeader().GetOatChecksum(); 1305 image_file_location_oat_data_begin = 1306 reinterpret_cast<uintptr_t>(image_space->GetImageHeader().GetOatDataBegin()); 1307 image_file_location = image_space->GetImageFilename(); 1308 image_patch_delta = image_space->GetImageHeader().GetPatchDelta(); 1309 } 1310 1311 if (!image_file_location.empty()) { 1312 key_value_store_->Put(OatHeader::kImageLocationKey, image_file_location); 1313 } 1314 1315 oat_writer.reset(new OatWriter(dex_files_, image_file_location_oat_checksum, 1316 image_file_location_oat_data_begin, 1317 image_patch_delta, 1318 driver_.get(), 1319 image_writer_.get(), 1320 timings_, 1321 key_value_store_.get())); 1322 } 1323 1324 if (image_) { 1325 // The OatWriter constructor has already updated offsets in methods and we need to 1326 // prepare method offsets in the image address space for direct method patching. 1327 TimingLogger::ScopedTiming t2("dex2oat Prepare image address space", timings_); 1328 if (!image_writer_->PrepareImageAddressSpace()) { 1329 LOG(ERROR) << "Failed to prepare image address space."; 1330 return false; 1331 } 1332 } 1333 1334 { 1335 TimingLogger::ScopedTiming t2("dex2oat Write ELF", timings_); 1336 if (!driver_->WriteElf(android_root_, is_host_, dex_files_, oat_writer.get(), 1337 oat_file_.get())) { 1338 LOG(ERROR) << "Failed to write ELF file " << oat_file_->GetPath(); 1339 return false; 1340 } 1341 } 1342 1343 VLOG(compiler) << "Oat file written successfully (unstripped): " << oat_location_; 1344 return true; 1345 } 1346 1347 // If we are compiling an image, invoke the image creation routine. Else just skip. 1348 bool HandleImage() { 1349 if (image_) { 1350 TimingLogger::ScopedTiming t("dex2oat ImageWriter", timings_); 1351 if (!CreateImageFile()) { 1352 return false; 1353 } 1354 VLOG(compiler) << "Image written successfully: " << image_filename_; 1355 } 1356 return true; 1357 } 1358 1359 // Create a copy from unstripped to stripped. 1360 bool CopyUnstrippedToStripped() { 1361 // If we don't want to strip in place, copy from unstripped location to stripped location. 1362 // We need to strip after image creation because FixupElf needs to use .strtab. 1363 if (oat_unstripped_ != oat_stripped_) { 1364 // If the oat file is still open, flush it. 1365 if (oat_file_.get() != nullptr && oat_file_->IsOpened()) { 1366 if (!FlushCloseOatFile()) { 1367 return false; 1368 } 1369 } 1370 1371 TimingLogger::ScopedTiming t("dex2oat OatFile copy", timings_); 1372 std::unique_ptr<File> in(OS::OpenFileForReading(oat_unstripped_.c_str())); 1373 std::unique_ptr<File> out(OS::CreateEmptyFile(oat_stripped_.c_str())); 1374 size_t buffer_size = 8192; 1375 std::unique_ptr<uint8_t[]> buffer(new uint8_t[buffer_size]); 1376 while (true) { 1377 int bytes_read = TEMP_FAILURE_RETRY(read(in->Fd(), buffer.get(), buffer_size)); 1378 if (bytes_read <= 0) { 1379 break; 1380 } 1381 bool write_ok = out->WriteFully(buffer.get(), bytes_read); 1382 CHECK(write_ok); 1383 } 1384 if (out->FlushCloseOrErase() != 0) { 1385 PLOG(ERROR) << "Failed to flush and close copied oat file: " << oat_stripped_; 1386 return false; 1387 } 1388 VLOG(compiler) << "Oat file copied successfully (stripped): " << oat_stripped_; 1389 } 1390 return true; 1391 } 1392 1393 bool FlushOatFile() { 1394 if (oat_file_.get() != nullptr) { 1395 TimingLogger::ScopedTiming t2("dex2oat Flush ELF", timings_); 1396 if (oat_file_->Flush() != 0) { 1397 PLOG(ERROR) << "Failed to flush oat file: " << oat_location_ << " / " 1398 << oat_filename_; 1399 oat_file_->Erase(); 1400 return false; 1401 } 1402 } 1403 return true; 1404 } 1405 1406 bool FlushCloseOatFile() { 1407 if (oat_file_.get() != nullptr) { 1408 std::unique_ptr<File> tmp(oat_file_.release()); 1409 if (tmp->FlushCloseOrErase() != 0) { 1410 PLOG(ERROR) << "Failed to flush and close oat file: " << oat_location_ << " / " 1411 << oat_filename_; 1412 return false; 1413 } 1414 } 1415 return true; 1416 } 1417 1418 void DumpTiming() { 1419 if (dump_timing_ || (dump_slow_timing_ && timings_->GetTotalNs() > MsToNs(1000))) { 1420 LOG(INFO) << Dumpable<TimingLogger>(*timings_); 1421 } 1422 if (dump_passes_) { 1423 LOG(INFO) << Dumpable<CumulativeLogger>(*driver_->GetTimingsLogger()); 1424 } 1425 } 1426 1427 CompilerOptions* GetCompilerOptions() const { 1428 return compiler_options_.get(); 1429 } 1430 1431 bool IsImage() const { 1432 return image_; 1433 } 1434 1435 bool IsHost() const { 1436 return is_host_; 1437 } 1438 1439 private: 1440 static size_t OpenDexFiles(const std::vector<const char*>& dex_filenames, 1441 const std::vector<const char*>& dex_locations, 1442 std::vector<const DexFile*>& dex_files) { 1443 size_t failure_count = 0; 1444 for (size_t i = 0; i < dex_filenames.size(); i++) { 1445 const char* dex_filename = dex_filenames[i]; 1446 const char* dex_location = dex_locations[i]; 1447 ATRACE_BEGIN(StringPrintf("Opening dex file '%s'", dex_filenames[i]).c_str()); 1448 std::string error_msg; 1449 if (!OS::FileExists(dex_filename)) { 1450 LOG(WARNING) << "Skipping non-existent dex file '" << dex_filename << "'"; 1451 continue; 1452 } 1453 if (!DexFile::Open(dex_filename, dex_location, &error_msg, &dex_files)) { 1454 LOG(WARNING) << "Failed to open .dex from file '" << dex_filename << "': " << error_msg; 1455 ++failure_count; 1456 } 1457 ATRACE_END(); 1458 } 1459 return failure_count; 1460 } 1461 1462 // Returns true if dex_files has a dex with the named location. 1463 static bool DexFilesContains(const std::vector<const DexFile*>& dex_files, 1464 const std::string& location) { 1465 for (size_t i = 0; i < dex_files.size(); ++i) { 1466 if (dex_files[i]->GetLocation() == location) { 1467 return true; 1468 } 1469 } 1470 return false; 1471 } 1472 1473 // Appends to dex_files any elements of class_path that it doesn't already 1474 // contain. This will open those dex files as necessary. 1475 static void OpenClassPathFiles(const std::string& class_path, 1476 std::vector<const DexFile*>& dex_files) { 1477 std::vector<std::string> parsed; 1478 Split(class_path, ':', &parsed); 1479 // Take Locks::mutator_lock_ so that lock ordering on the ClassLinker::dex_lock_ is maintained. 1480 ScopedObjectAccess soa(Thread::Current()); 1481 for (size_t i = 0; i < parsed.size(); ++i) { 1482 if (DexFilesContains(dex_files, parsed[i])) { 1483 continue; 1484 } 1485 std::string error_msg; 1486 if (!DexFile::Open(parsed[i].c_str(), parsed[i].c_str(), &error_msg, &dex_files)) { 1487 LOG(WARNING) << "Failed to open dex file '" << parsed[i] << "': " << error_msg; 1488 } 1489 } 1490 } 1491 1492 // Create a runtime necessary for compilation. 1493 bool CreateRuntime(const RuntimeOptions& runtime_options) 1494 SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_) { 1495 if (!Runtime::Create(runtime_options, false)) { 1496 LOG(ERROR) << "Failed to create runtime"; 1497 return false; 1498 } 1499 Runtime* runtime = Runtime::Current(); 1500 runtime->SetInstructionSet(instruction_set_); 1501 for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) { 1502 Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i); 1503 if (!runtime->HasCalleeSaveMethod(type)) { 1504 runtime->SetCalleeSaveMethod(runtime->CreateCalleeSaveMethod(), type); 1505 } 1506 } 1507 runtime->GetClassLinker()->FixupDexCaches(runtime->GetResolutionMethod()); 1508 runtime->GetClassLinker()->RunRootClinits(); 1509 runtime_ = runtime; 1510 return true; 1511 } 1512 1513 void PrepareImageWriter(uintptr_t image_base) { 1514 image_writer_.reset(new ImageWriter(*driver_, image_base, compiler_options_->GetCompilePic())); 1515 } 1516 1517 // Let the ImageWriter write the image file. If we do not compile PIC, also fix up the oat file. 1518 bool CreateImageFile() 1519 LOCKS_EXCLUDED(Locks::mutator_lock_) { 1520 CHECK(image_writer_ != nullptr); 1521 if (!image_writer_->Write(image_filename_, oat_unstripped_, oat_location_)) { 1522 LOG(ERROR) << "Failed to create image file " << image_filename_; 1523 return false; 1524 } 1525 uintptr_t oat_data_begin = image_writer_->GetOatDataBegin(); 1526 1527 // Destroy ImageWriter before doing FixupElf. 1528 image_writer_.reset(); 1529 1530 // Do not fix up the ELF file if we are --compile-pic 1531 if (!compiler_options_->GetCompilePic()) { 1532 std::unique_ptr<File> oat_file(OS::OpenFileReadWrite(oat_unstripped_.c_str())); 1533 if (oat_file.get() == nullptr) { 1534 PLOG(ERROR) << "Failed to open ELF file: " << oat_unstripped_; 1535 return false; 1536 } 1537 1538 if (!ElfWriter::Fixup(oat_file.get(), oat_data_begin)) { 1539 oat_file->Erase(); 1540 LOG(ERROR) << "Failed to fixup ELF file " << oat_file->GetPath(); 1541 return false; 1542 } 1543 1544 if (oat_file->FlushCloseOrErase()) { 1545 PLOG(ERROR) << "Failed to flush and close fixed ELF file " << oat_file->GetPath(); 1546 return false; 1547 } 1548 } 1549 1550 return true; 1551 } 1552 1553 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;) 1554 static std::set<std::string>* ReadImageClassesFromFile(const char* image_classes_filename) { 1555 std::unique_ptr<std::ifstream> image_classes_file(new std::ifstream(image_classes_filename, 1556 std::ifstream::in)); 1557 if (image_classes_file.get() == nullptr) { 1558 LOG(ERROR) << "Failed to open image classes file " << image_classes_filename; 1559 return nullptr; 1560 } 1561 std::unique_ptr<std::set<std::string>> result(ReadImageClasses(*image_classes_file)); 1562 image_classes_file->close(); 1563 return result.release(); 1564 } 1565 1566 static std::set<std::string>* ReadImageClasses(std::istream& image_classes_stream) { 1567 std::unique_ptr<std::set<std::string>> image_classes(new std::set<std::string>); 1568 while (image_classes_stream.good()) { 1569 std::string dot; 1570 std::getline(image_classes_stream, dot); 1571 if (StartsWith(dot, "#") || dot.empty()) { 1572 continue; 1573 } 1574 std::string descriptor(DotToDescriptor(dot.c_str())); 1575 image_classes->insert(descriptor); 1576 } 1577 return image_classes.release(); 1578 } 1579 1580 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;) 1581 static std::set<std::string>* ReadImageClassesFromZip(const char* zip_filename, 1582 const char* image_classes_filename, 1583 std::string* error_msg) { 1584 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::Open(zip_filename, error_msg)); 1585 if (zip_archive.get() == nullptr) { 1586 return nullptr; 1587 } 1588 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(image_classes_filename, error_msg)); 1589 if (zip_entry.get() == nullptr) { 1590 *error_msg = StringPrintf("Failed to find '%s' within '%s': %s", image_classes_filename, 1591 zip_filename, error_msg->c_str()); 1592 return nullptr; 1593 } 1594 std::unique_ptr<MemMap> image_classes_file(zip_entry->ExtractToMemMap(zip_filename, 1595 image_classes_filename, 1596 error_msg)); 1597 if (image_classes_file.get() == nullptr) { 1598 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", image_classes_filename, 1599 zip_filename, error_msg->c_str()); 1600 return nullptr; 1601 } 1602 const std::string image_classes_string(reinterpret_cast<char*>(image_classes_file->Begin()), 1603 image_classes_file->Size()); 1604 std::istringstream image_classes_stream(image_classes_string); 1605 return ReadImageClasses(image_classes_stream); 1606 } 1607 1608 void LogCompletionTime() { 1609 LOG(INFO) << "dex2oat took " << PrettyDuration(NanoTime() - start_ns_) 1610 << " (threads: " << thread_count_ << ") " 1611 << driver_->GetMemoryUsageString(); 1612 } 1613 1614 std::unique_ptr<CompilerOptions> compiler_options_; 1615 Compiler::Kind compiler_kind_; 1616 1617 InstructionSet instruction_set_; 1618 std::unique_ptr<const InstructionSetFeatures> instruction_set_features_; 1619 1620 std::unique_ptr<SafeMap<std::string, std::string> > key_value_store_; 1621 1622 std::unique_ptr<VerificationResults> verification_results_; 1623 DexFileToMethodInlinerMap method_inliner_map_; 1624 std::unique_ptr<QuickCompilerCallbacks> callbacks_; 1625 1626 // Not a unique_ptr as we want to just exit on non-debug builds, not bringing the runtime down 1627 // in an orderly fashion. The destructor takes care of deleting this. 1628 Runtime* runtime_; 1629 1630 size_t thread_count_; 1631 uint64_t start_ns_; 1632 std::unique_ptr<WatchDog> watchdog_; 1633 std::unique_ptr<File> oat_file_; 1634 std::string oat_stripped_; 1635 std::string oat_unstripped_; 1636 std::string oat_location_; 1637 std::string oat_filename_; 1638 int oat_fd_; 1639 std::vector<const char*> dex_filenames_; 1640 std::vector<const char*> dex_locations_; 1641 int zip_fd_; 1642 std::string zip_location_; 1643 std::string boot_image_option_; 1644 std::vector<const char*> runtime_args_; 1645 std::string image_filename_; 1646 uintptr_t image_base_; 1647 const char* image_classes_zip_filename_; 1648 const char* image_classes_filename_; 1649 const char* compiled_classes_zip_filename_; 1650 const char* compiled_classes_filename_; 1651 std::unique_ptr<std::set<std::string>> image_classes_; 1652 std::unique_ptr<std::set<std::string>> compiled_classes_; 1653 bool image_; 1654 std::unique_ptr<ImageWriter> image_writer_; 1655 bool is_host_; 1656 std::string android_root_; 1657 std::vector<const DexFile*> dex_files_; 1658 std::unique_ptr<CompilerDriver> driver_; 1659 std::vector<std::string> verbose_methods_; 1660 bool dump_stats_; 1661 bool dump_passes_; 1662 bool dump_timing_; 1663 bool dump_slow_timing_; 1664 std::string swap_file_name_; 1665 int swap_fd_; 1666 std::string profile_file_; // Profile file to use 1667 TimingLogger* timings_; 1668 std::unique_ptr<CumulativeLogger> compiler_phases_timings_; 1669 std::unique_ptr<std::ostream> init_failure_output_; 1670 1671 DISALLOW_IMPLICIT_CONSTRUCTORS(Dex2Oat); 1672}; 1673 1674const unsigned int WatchDog::kWatchDogTimeoutSeconds; 1675 1676static void b13564922() { 1677#if defined(__linux__) && defined(__arm__) 1678 int major, minor; 1679 struct utsname uts; 1680 if (uname(&uts) != -1 && 1681 sscanf(uts.release, "%d.%d", &major, &minor) == 2 && 1682 ((major < 3) || ((major == 3) && (minor < 4)))) { 1683 // Kernels before 3.4 don't handle the ASLR well and we can run out of address 1684 // space (http://b/13564922). Work around the issue by inhibiting further mmap() randomization. 1685 int old_personality = personality(0xffffffff); 1686 if ((old_personality & ADDR_NO_RANDOMIZE) == 0) { 1687 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE); 1688 if (new_personality == -1) { 1689 LOG(WARNING) << "personality(. | ADDR_NO_RANDOMIZE) failed."; 1690 } 1691 } 1692 } 1693#endif 1694} 1695 1696static int CompileImage(Dex2Oat& dex2oat) { 1697 dex2oat.Compile(); 1698 1699 // Create the boot.oat. 1700 if (!dex2oat.CreateOatFile()) { 1701 dex2oat.EraseOatFile(); 1702 return EXIT_FAILURE; 1703 } 1704 1705 // Flush and close the boot.oat. We always expect the output file by name, and it will be 1706 // re-opened from the unstripped name. 1707 if (!dex2oat.FlushCloseOatFile()) { 1708 return EXIT_FAILURE; 1709 } 1710 1711 // Creates the boot.art and patches the boot.oat. 1712 if (!dex2oat.HandleImage()) { 1713 return EXIT_FAILURE; 1714 } 1715 1716 // When given --host, finish early without stripping. 1717 if (dex2oat.IsHost()) { 1718 dex2oat.DumpTiming(); 1719 return EXIT_SUCCESS; 1720 } 1721 1722 // Copy unstripped to stripped location, if necessary. 1723 if (!dex2oat.CopyUnstrippedToStripped()) { 1724 return EXIT_FAILURE; 1725 } 1726 1727 // FlushClose again, as stripping might have re-opened the oat file. 1728 if (!dex2oat.FlushCloseOatFile()) { 1729 return EXIT_FAILURE; 1730 } 1731 1732 dex2oat.DumpTiming(); 1733 return EXIT_SUCCESS; 1734} 1735 1736static int CompileApp(Dex2Oat& dex2oat) { 1737 dex2oat.Compile(); 1738 1739 // Create the app oat. 1740 if (!dex2oat.CreateOatFile()) { 1741 dex2oat.EraseOatFile(); 1742 return EXIT_FAILURE; 1743 } 1744 1745 // Do not close the oat file here. We might haven gotten the output file by file descriptor, 1746 // which we would lose. 1747 if (!dex2oat.FlushOatFile()) { 1748 return EXIT_FAILURE; 1749 } 1750 1751 // When given --host, finish early without stripping. 1752 if (dex2oat.IsHost()) { 1753 if (!dex2oat.FlushCloseOatFile()) { 1754 return EXIT_FAILURE; 1755 } 1756 1757 dex2oat.DumpTiming(); 1758 return EXIT_SUCCESS; 1759 } 1760 1761 // Copy unstripped to stripped location, if necessary. This will implicitly flush & close the 1762 // unstripped version. If this is given, we expect to be able to open writable files by name. 1763 if (!dex2oat.CopyUnstrippedToStripped()) { 1764 return EXIT_FAILURE; 1765 } 1766 1767 // Flush and close the file. 1768 if (!dex2oat.FlushCloseOatFile()) { 1769 return EXIT_FAILURE; 1770 } 1771 1772 dex2oat.DumpTiming(); 1773 return EXIT_SUCCESS; 1774} 1775 1776static int dex2oat(int argc, char** argv) { 1777 b13564922(); 1778 1779 TimingLogger timings("compiler", false, false); 1780 1781 Dex2Oat dex2oat(&timings); 1782 1783 // Parse arguments. Argument mistakes will lead to exit(EXIT_FAILURE) in UsageError. 1784 dex2oat.ParseArgs(argc, argv); 1785 1786 // Check early that the result of compilation can be written 1787 if (!dex2oat.OpenFile()) { 1788 return EXIT_FAILURE; 1789 } 1790 1791 LOG(INFO) << CommandLine(); 1792 1793 if (!dex2oat.Setup()) { 1794 dex2oat.EraseOatFile(); 1795 return EXIT_FAILURE; 1796 } 1797 1798 if (dex2oat.IsImage()) { 1799 return CompileImage(dex2oat); 1800 } else { 1801 return CompileApp(dex2oat); 1802 } 1803} 1804} // namespace art 1805 1806int main(int argc, char** argv) { 1807 int result = art::dex2oat(argc, argv); 1808 // Everything was done, do an explicit exit here to avoid running Runtime destructors that take 1809 // time (bug 10645725) unless we're a debug build or running on valgrind. Note: The Dex2Oat class 1810 // should not destruct the runtime in this case. 1811 if (!art::kIsDebugBuild && (RUNNING_ON_VALGRIND == 0)) { 1812 exit(result); 1813 } 1814 return result; 1815} 1816