dex2oat.cc revision 866c03125a3fcd74c9fff04da87865f5eb1767d9
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.starts_with("--dump-cfg=")) { 663 dump_cfg_file_name_ = option.substr(strlen("--dump-cfg=")).data(); 664 } else if (option == "--dump-stats") { 665 dump_stats_ = true; 666 } else if (option == "--include-debug-symbols" || option == "--no-strip-symbols") { 667 include_debug_symbols = true; 668 } else if (option == "--no-include-debug-symbols" || option == "--strip-symbols") { 669 include_debug_symbols = false; 670 generate_gdb_information = false; // Depends on debug symbols, see above. 671 } else if (option.starts_with("--profile-file=")) { 672 profile_file_ = option.substr(strlen("--profile-file=")).data(); 673 VLOG(compiler) << "dex2oat: profile file is " << profile_file_; 674 } else if (option == "--no-profile-file") { 675 // No profile 676 } else if (option.starts_with("--top-k-profile-threshold=")) { 677 ParseDouble(option.data(), '=', 0.0, 100.0, &top_k_profile_threshold); 678 } else if (option == "--print-pass-names") { 679 PassDriverMEOpts::PrintPassNames(); 680 } else if (option.starts_with("--disable-passes=")) { 681 std::string disable_passes = option.substr(strlen("--disable-passes=")).data(); 682 PassDriverMEOpts::CreateDefaultPassList(disable_passes); 683 } else if (option.starts_with("--print-passes=")) { 684 std::string print_passes = option.substr(strlen("--print-passes=")).data(); 685 PassDriverMEOpts::SetPrintPassList(print_passes); 686 } else if (option == "--print-all-passes") { 687 PassDriverMEOpts::SetPrintAllPasses(); 688 } else if (option.starts_with("--dump-cfg-passes=")) { 689 std::string dump_passes_string = option.substr(strlen("--dump-cfg-passes=")).data(); 690 PassDriverMEOpts::SetDumpPassList(dump_passes_string); 691 } else if (option == "--print-pass-options") { 692 print_pass_options = true; 693 } else if (option.starts_with("--pass-options=")) { 694 std::string options = option.substr(strlen("--pass-options=")).data(); 695 PassDriverMEOpts::SetOverriddenPassOptions(options); 696 } else if (option == "--include-patch-information") { 697 include_patch_information = true; 698 } else if (option == "--no-include-patch-information") { 699 include_patch_information = false; 700 } else if (option.starts_with("--verbose-methods=")) { 701 // TODO: rather than switch off compiler logging, make all VLOG(compiler) messages 702 // conditional on having verbost methods. 703 gLogVerbosity.compiler = false; 704 Split(option.substr(strlen("--verbose-methods=")).ToString(), ',', &verbose_methods_); 705 } else if (option.starts_with("--dump-init-failures=")) { 706 std::string file_name = option.substr(strlen("--dump-init-failures=")).data(); 707 init_failure_output_.reset(new std::ofstream(file_name)); 708 if (init_failure_output_.get() == nullptr) { 709 LOG(ERROR) << "Failed to allocate ofstream"; 710 } else if (init_failure_output_->fail()) { 711 LOG(ERROR) << "Failed to open " << file_name << " for writing the initialization " 712 << "failures."; 713 init_failure_output_.reset(); 714 } 715 } else if (option.starts_with("--swap-file=")) { 716 swap_file_name_ = option.substr(strlen("--swap-file=")).data(); 717 } else if (option.starts_with("--swap-fd=")) { 718 const char* swap_fd_str = option.substr(strlen("--swap-fd=")).data(); 719 if (!ParseInt(swap_fd_str, &swap_fd_)) { 720 Usage("Failed to parse --swap-fd argument '%s' as an integer", swap_fd_str); 721 } 722 if (swap_fd_ < 0) { 723 Usage("--swap-fd passed a negative value %d", swap_fd_); 724 } 725 } else { 726 Usage("Unknown argument %s", option.data()); 727 } 728 } 729 730 if (compiler_kind_ == Compiler::kOptimizing) { 731 // Optimizing only supports PIC mode. 732 compile_pic = true; 733 } 734 735 if (oat_filename_.empty() && oat_fd_ == -1) { 736 Usage("Output must be supplied with either --oat-file or --oat-fd"); 737 } 738 739 if (!oat_filename_.empty() && oat_fd_ != -1) { 740 Usage("--oat-file should not be used with --oat-fd"); 741 } 742 743 if (!oat_symbols.empty() && oat_fd_ != -1) { 744 Usage("--oat-symbols should not be used with --oat-fd"); 745 } 746 747 if (!oat_symbols.empty() && is_host_) { 748 Usage("--oat-symbols should not be used with --host"); 749 } 750 751 if (oat_fd_ != -1 && !image_filename_.empty()) { 752 Usage("--oat-fd should not be used with --image"); 753 } 754 755 if (android_root_.empty()) { 756 const char* android_root_env_var = getenv("ANDROID_ROOT"); 757 if (android_root_env_var == nullptr) { 758 Usage("--android-root unspecified and ANDROID_ROOT not set"); 759 } 760 android_root_ += android_root_env_var; 761 } 762 763 image_ = (!image_filename_.empty()); 764 if (!image_ && boot_image_filename.empty()) { 765 boot_image_filename += android_root_; 766 boot_image_filename += "/framework/boot.art"; 767 } 768 if (!boot_image_filename.empty()) { 769 boot_image_option_ += "-Ximage:"; 770 boot_image_option_ += boot_image_filename; 771 } 772 773 if (image_classes_filename_ != nullptr && !image_) { 774 Usage("--image-classes should only be used with --image"); 775 } 776 777 if (image_classes_filename_ != nullptr && !boot_image_option_.empty()) { 778 Usage("--image-classes should not be used with --boot-image"); 779 } 780 781 if (image_classes_zip_filename_ != nullptr && image_classes_filename_ == nullptr) { 782 Usage("--image-classes-zip should be used with --image-classes"); 783 } 784 785 if (compiled_classes_filename_ != nullptr && !image_) { 786 Usage("--compiled-classes should only be used with --image"); 787 } 788 789 if (compiled_classes_filename_ != nullptr && !boot_image_option_.empty()) { 790 Usage("--compiled-classes should not be used with --boot-image"); 791 } 792 793 if (compiled_classes_zip_filename_ != nullptr && compiled_classes_filename_ == nullptr) { 794 Usage("--compiled-classes-zip should be used with --compiled-classes"); 795 } 796 797 if (dex_filenames_.empty() && zip_fd_ == -1) { 798 Usage("Input must be supplied with either --dex-file or --zip-fd"); 799 } 800 801 if (!dex_filenames_.empty() && zip_fd_ != -1) { 802 Usage("--dex-file should not be used with --zip-fd"); 803 } 804 805 if (!dex_filenames_.empty() && !zip_location_.empty()) { 806 Usage("--dex-file should not be used with --zip-location"); 807 } 808 809 if (dex_locations_.empty()) { 810 for (const char* dex_file_name : dex_filenames_) { 811 dex_locations_.push_back(dex_file_name); 812 } 813 } else if (dex_locations_.size() != dex_filenames_.size()) { 814 Usage("--dex-location arguments do not match --dex-file arguments"); 815 } 816 817 if (zip_fd_ != -1 && zip_location_.empty()) { 818 Usage("--zip-location should be supplied with --zip-fd"); 819 } 820 821 if (boot_image_option_.empty()) { 822 if (image_base_ == 0) { 823 Usage("Non-zero --base not specified"); 824 } 825 } 826 827 oat_stripped_ = oat_filename_; 828 if (!oat_symbols.empty()) { 829 oat_unstripped_ = oat_symbols; 830 } else { 831 oat_unstripped_ = oat_filename_; 832 } 833 834 // If no instruction set feature was given, use the default one for the target 835 // instruction set. 836 if (instruction_set_features_.get() == nullptr) { 837 instruction_set_features_.reset( 838 InstructionSetFeatures::FromVariant(instruction_set_, "default", &error_msg)); 839 if (instruction_set_features_.get() == nullptr) { 840 Usage("Problem initializing default instruction set features variant: %s", 841 error_msg.c_str()); 842 } 843 } 844 845 if (instruction_set_ == kRuntimeISA) { 846 std::unique_ptr<const InstructionSetFeatures> runtime_features( 847 InstructionSetFeatures::FromCppDefines()); 848 if (!instruction_set_features_->Equals(runtime_features.get())) { 849 LOG(WARNING) << "Mismatch between dex2oat instruction set features (" 850 << *instruction_set_features_ << ") and those of dex2oat executable (" 851 << *runtime_features <<") for the command line:\n" 852 << CommandLine(); 853 } 854 } 855 856 if (compiler_filter_string == nullptr) { 857 if (instruction_set_ == kMips64) { 858 // TODO: fix compiler for Mips64. 859 compiler_filter_string = "interpret-only"; 860 } else if (image_) { 861 compiler_filter_string = "speed"; 862 } else { 863 // TODO: Migrate SMALL mode to command line option. 864 #if ART_SMALL_MODE 865 compiler_filter_string = "interpret-only"; 866 #else 867 compiler_filter_string = "speed"; 868 #endif 869 } 870 } 871 CHECK(compiler_filter_string != nullptr); 872 CompilerOptions::CompilerFilter compiler_filter = CompilerOptions::kDefaultCompilerFilter; 873 if (strcmp(compiler_filter_string, "verify-none") == 0) { 874 compiler_filter = CompilerOptions::kVerifyNone; 875 } else if (strcmp(compiler_filter_string, "interpret-only") == 0) { 876 compiler_filter = CompilerOptions::kInterpretOnly; 877 } else if (strcmp(compiler_filter_string, "space") == 0) { 878 compiler_filter = CompilerOptions::kSpace; 879 } else if (strcmp(compiler_filter_string, "balanced") == 0) { 880 compiler_filter = CompilerOptions::kBalanced; 881 } else if (strcmp(compiler_filter_string, "speed") == 0) { 882 compiler_filter = CompilerOptions::kSpeed; 883 } else if (strcmp(compiler_filter_string, "everything") == 0) { 884 compiler_filter = CompilerOptions::kEverything; 885 } else if (strcmp(compiler_filter_string, "time") == 0) { 886 compiler_filter = CompilerOptions::kTime; 887 } else { 888 Usage("Unknown --compiler-filter value %s", compiler_filter_string); 889 } 890 891 // Checks are all explicit until we know the architecture. 892 bool implicit_null_checks = false; 893 bool implicit_so_checks = false; 894 bool implicit_suspend_checks = false; 895 // Set the compilation target's implicit checks options. 896 switch (instruction_set_) { 897 case kArm: 898 case kThumb2: 899 case kArm64: 900 case kX86: 901 case kX86_64: 902 implicit_null_checks = true; 903 implicit_so_checks = true; 904 break; 905 906 default: 907 // Defaults are correct. 908 break; 909 } 910 911 if (print_pass_options) { 912 PassDriverMEOpts::PrintPassOptions(); 913 } 914 915 compiler_options_.reset(new CompilerOptions(compiler_filter, 916 huge_method_threshold, 917 large_method_threshold, 918 small_method_threshold, 919 tiny_method_threshold, 920 num_dex_methods_threshold, 921 generate_gdb_information, 922 include_patch_information, 923 top_k_profile_threshold, 924 include_debug_symbols, 925 implicit_null_checks, 926 implicit_so_checks, 927 implicit_suspend_checks, 928 compile_pic, 929 verbose_methods_.empty() ? 930 nullptr : 931 &verbose_methods_, 932 init_failure_output_.get())); 933 934 // Done with usage checks, enable watchdog if requested 935 if (watch_dog_enabled) { 936 watchdog_.reset(new WatchDog(true)); 937 } 938 939 // Fill some values into the key-value store for the oat header. 940 key_value_store_.reset(new SafeMap<std::string, std::string>()); 941 942 // Insert some compiler things. 943 { 944 std::ostringstream oss; 945 for (int i = 0; i < argc; ++i) { 946 if (i > 0) { 947 oss << ' '; 948 } 949 oss << argv[i]; 950 } 951 key_value_store_->Put(OatHeader::kDex2OatCmdLineKey, oss.str()); 952 oss.str(""); // Reset. 953 oss << kRuntimeISA; 954 key_value_store_->Put(OatHeader::kDex2OatHostKey, oss.str()); 955 key_value_store_->Put(OatHeader::kPicKey, compile_pic ? "true" : "false"); 956 } 957 } 958 959 // Check whether the oat output file is writable, and open it for later. Also open a swap file, 960 // if a name is given. 961 bool OpenFile() { 962 bool create_file = !oat_unstripped_.empty(); // as opposed to using open file descriptor 963 if (create_file) { 964 oat_file_.reset(OS::CreateEmptyFile(oat_unstripped_.c_str())); 965 if (oat_location_.empty()) { 966 oat_location_ = oat_filename_; 967 } 968 } else { 969 oat_file_.reset(new File(oat_fd_, oat_location_, true)); 970 oat_file_->DisableAutoClose(); 971 if (oat_file_->SetLength(0) != 0) { 972 PLOG(WARNING) << "Truncating oat file " << oat_location_ << " failed."; 973 } 974 } 975 if (oat_file_.get() == nullptr) { 976 PLOG(ERROR) << "Failed to create oat file: " << oat_location_; 977 return false; 978 } 979 if (create_file && fchmod(oat_file_->Fd(), 0644) != 0) { 980 PLOG(ERROR) << "Failed to make oat file world readable: " << oat_location_; 981 oat_file_->Erase(); 982 return false; 983 } 984 985 // Swap file handling. 986 // 987 // If the swap fd is not -1, we assume this is the file descriptor of an open but unlinked file 988 // that we can use for swap. 989 // 990 // If the swap fd is -1 and we have a swap-file string, open the given file as a swap file. We 991 // will immediately unlink to satisfy the swap fd assumption. 992 if (swap_fd_ == -1 && !swap_file_name_.empty()) { 993 std::unique_ptr<File> swap_file(OS::CreateEmptyFile(swap_file_name_.c_str())); 994 if (swap_file.get() == nullptr) { 995 PLOG(ERROR) << "Failed to create swap file: " << swap_file_name_; 996 return false; 997 } 998 swap_fd_ = swap_file->Fd(); 999 swap_file->MarkUnchecked(); // We don't we to track this, it will be unlinked immediately. 1000 swap_file->DisableAutoClose(); // We'll handle it ourselves, the File object will be 1001 // released immediately. 1002 unlink(swap_file_name_.c_str()); 1003 } 1004 1005 return true; 1006 } 1007 1008 void EraseOatFile() { 1009 DCHECK(oat_file_.get() != nullptr); 1010 oat_file_->Erase(); 1011 oat_file_.reset(); 1012 } 1013 1014 // Set up the environment for compilation. Includes starting the runtime and loading/opening the 1015 // boot class path. 1016 bool Setup() { 1017 TimingLogger::ScopedTiming t("dex2oat Setup", timings_); 1018 RuntimeOptions runtime_options; 1019 art::MemMap::Init(); // For ZipEntry::ExtractToMemMap. 1020 if (boot_image_option_.empty()) { 1021 std::string boot_class_path = "-Xbootclasspath:"; 1022 boot_class_path += Join(dex_filenames_, ':'); 1023 runtime_options.push_back(std::make_pair(boot_class_path, nullptr)); 1024 std::string boot_class_path_locations = "-Xbootclasspath-locations:"; 1025 boot_class_path_locations += Join(dex_locations_, ':'); 1026 runtime_options.push_back(std::make_pair(boot_class_path_locations, nullptr)); 1027 } else { 1028 runtime_options.push_back(std::make_pair(boot_image_option_, nullptr)); 1029 } 1030 for (size_t i = 0; i < runtime_args_.size(); i++) { 1031 runtime_options.push_back(std::make_pair(runtime_args_[i], nullptr)); 1032 } 1033 1034 verification_results_.reset(new VerificationResults(compiler_options_.get())); 1035 callbacks_.reset(new QuickCompilerCallbacks(verification_results_.get(), &method_inliner_map_)); 1036 runtime_options.push_back(std::make_pair("compilercallbacks", callbacks_.get())); 1037 runtime_options.push_back( 1038 std::make_pair("imageinstructionset", GetInstructionSetString(instruction_set_))); 1039 1040 if (!CreateRuntime(runtime_options)) { 1041 return false; 1042 } 1043 1044 // Runtime::Create acquired the mutator_lock_ that is normally given away when we 1045 // Runtime::Start, give it away now so that we don't starve GC. 1046 Thread* self = Thread::Current(); 1047 self->TransitionFromRunnableToSuspended(kNative); 1048 // If we're doing the image, override the compiler filter to force full compilation. Must be 1049 // done ahead of WellKnownClasses::Init that causes verification. Note: doesn't force 1050 // compilation of class initializers. 1051 // Whilst we're in native take the opportunity to initialize well known classes. 1052 WellKnownClasses::Init(self->GetJniEnv()); 1053 1054 // If --image-classes was specified, calculate the full list of classes to include in the image 1055 if (image_classes_filename_ != nullptr) { 1056 std::string error_msg; 1057 if (image_classes_zip_filename_ != nullptr) { 1058 image_classes_.reset(ReadImageClassesFromZip(image_classes_zip_filename_, 1059 image_classes_filename_, 1060 &error_msg)); 1061 } else { 1062 image_classes_.reset(ReadImageClassesFromFile(image_classes_filename_)); 1063 } 1064 if (image_classes_.get() == nullptr) { 1065 LOG(ERROR) << "Failed to create list of image classes from '" << image_classes_filename_ << 1066 "': " << error_msg; 1067 return false; 1068 } 1069 } else if (image_) { 1070 image_classes_.reset(new std::set<std::string>); 1071 } 1072 // If --compiled-classes was specified, calculate the full list of classes to compile in the 1073 // image. 1074 if (compiled_classes_filename_ != nullptr) { 1075 std::string error_msg; 1076 if (compiled_classes_zip_filename_ != nullptr) { 1077 compiled_classes_.reset(ReadImageClassesFromZip(compiled_classes_zip_filename_, 1078 compiled_classes_filename_, 1079 &error_msg)); 1080 } else { 1081 compiled_classes_.reset(ReadImageClassesFromFile(compiled_classes_filename_)); 1082 } 1083 if (compiled_classes_.get() == nullptr) { 1084 LOG(ERROR) << "Failed to create list of compiled classes from '" 1085 << compiled_classes_filename_ << "': " << error_msg; 1086 return false; 1087 } 1088 } else if (image_) { 1089 compiled_classes_.reset(nullptr); // By default compile everything. 1090 } 1091 1092 if (boot_image_option_.empty()) { 1093 dex_files_ = Runtime::Current()->GetClassLinker()->GetBootClassPath(); 1094 } else { 1095 if (dex_filenames_.empty()) { 1096 ATRACE_BEGIN("Opening zip archive from file descriptor"); 1097 std::string error_msg; 1098 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(zip_fd_, 1099 zip_location_.c_str(), 1100 &error_msg)); 1101 if (zip_archive.get() == nullptr) { 1102 LOG(ERROR) << "Failed to open zip from file descriptor for '" << zip_location_ << "': " 1103 << error_msg; 1104 return false; 1105 } 1106 if (!DexFile::OpenFromZip(*zip_archive.get(), zip_location_, &error_msg, &dex_files_)) { 1107 LOG(ERROR) << "Failed to open dex from file descriptor for zip file '" << zip_location_ 1108 << "': " << error_msg; 1109 return false; 1110 } 1111 ATRACE_END(); 1112 } else { 1113 size_t failure_count = OpenDexFiles(dex_filenames_, dex_locations_, dex_files_); 1114 if (failure_count > 0) { 1115 LOG(ERROR) << "Failed to open some dex files: " << failure_count; 1116 return false; 1117 } 1118 } 1119 1120 constexpr bool kSaveDexInput = false; 1121 if (kSaveDexInput) { 1122 for (size_t i = 0; i < dex_files_.size(); ++i) { 1123 const DexFile* dex_file = dex_files_[i]; 1124 std::string tmp_file_name(StringPrintf("/data/local/tmp/dex2oat.%d.%zd.dex", 1125 getpid(), i)); 1126 std::unique_ptr<File> tmp_file(OS::CreateEmptyFile(tmp_file_name.c_str())); 1127 if (tmp_file.get() == nullptr) { 1128 PLOG(ERROR) << "Failed to open file " << tmp_file_name 1129 << ". Try: adb shell chmod 777 /data/local/tmp"; 1130 continue; 1131 } 1132 // This is just dumping files for debugging. Ignore errors, and leave remnants. 1133 UNUSED(tmp_file->WriteFully(dex_file->Begin(), dex_file->Size())); 1134 UNUSED(tmp_file->Flush()); 1135 UNUSED(tmp_file->Close()); 1136 LOG(INFO) << "Wrote input to " << tmp_file_name; 1137 } 1138 } 1139 } 1140 // Ensure opened dex files are writable for dex-to-dex transformations. 1141 for (const auto& dex_file : dex_files_) { 1142 if (!dex_file->EnableWrite()) { 1143 PLOG(ERROR) << "Failed to make .dex file writeable '" << dex_file->GetLocation() << "'\n"; 1144 } 1145 } 1146 1147 // If we use a swap file, ensure we are above the threshold to make it necessary. 1148 if (swap_fd_ != -1) { 1149 if (!UseSwap(image_, dex_files_)) { 1150 close(swap_fd_); 1151 swap_fd_ = -1; 1152 LOG(INFO) << "Decided to run without swap."; 1153 } else { 1154 LOG(INFO) << "Accepted running with swap."; 1155 } 1156 } 1157 // Note that dex2oat won't close the swap_fd_. The compiler driver's swap space will do that. 1158 1159 /* 1160 * If we're not in interpret-only or verify-none mode, go ahead and compile small applications. 1161 * Don't bother to check if we're doing the image. 1162 */ 1163 if (!image_ && 1164 compiler_options_->IsCompilationEnabled() && 1165 compiler_kind_ == Compiler::kQuick) { 1166 size_t num_methods = 0; 1167 for (size_t i = 0; i != dex_files_.size(); ++i) { 1168 const DexFile* dex_file = dex_files_[i]; 1169 CHECK(dex_file != nullptr); 1170 num_methods += dex_file->NumMethodIds(); 1171 } 1172 if (num_methods <= compiler_options_->GetNumDexMethodsThreshold()) { 1173 compiler_options_->SetCompilerFilter(CompilerOptions::kSpeed); 1174 VLOG(compiler) << "Below method threshold, compiling anyways"; 1175 } 1176 } 1177 1178 return true; 1179 } 1180 1181 // Create and invoke the compiler driver. This will compile all the dex files. 1182 void Compile() { 1183 TimingLogger::ScopedTiming t("dex2oat Compile", timings_); 1184 compiler_phases_timings_.reset(new CumulativeLogger("compilation times")); 1185 1186 // Handle and ClassLoader creation needs to come after Runtime::Create 1187 jobject class_loader = nullptr; 1188 Thread* self = Thread::Current(); 1189 if (!boot_image_option_.empty()) { 1190 ClassLinker* class_linker = Runtime::Current()->GetClassLinker(); 1191 std::vector<const DexFile*> class_path_files(dex_files_); 1192 OpenClassPathFiles(runtime_->GetClassPathString(), class_path_files); 1193 ScopedObjectAccess soa(self); 1194 for (size_t i = 0; i < class_path_files.size(); i++) { 1195 class_linker->RegisterDexFile(*class_path_files[i]); 1196 } 1197 soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader); 1198 ScopedLocalRef<jobject> class_loader_local(soa.Env(), 1199 soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader)); 1200 class_loader = soa.Env()->NewGlobalRef(class_loader_local.get()); 1201 Runtime::Current()->SetCompileTimeClassPath(class_loader, class_path_files); 1202 } 1203 1204 driver_.reset(new CompilerDriver(compiler_options_.get(), 1205 verification_results_.get(), 1206 &method_inliner_map_, 1207 compiler_kind_, 1208 instruction_set_, 1209 instruction_set_features_.get(), 1210 image_, 1211 image_classes_.release(), 1212 compiled_classes_.release(), 1213 thread_count_, 1214 dump_stats_, 1215 dump_passes_, 1216 dump_cfg_file_name_, 1217 compiler_phases_timings_.get(), 1218 swap_fd_, 1219 profile_file_)); 1220 1221 driver_->CompileAll(class_loader, dex_files_, timings_); 1222 } 1223 1224 // Notes on the interleaving of creating the image and oat file to 1225 // ensure the references between the two are correct. 1226 // 1227 // Currently we have a memory layout that looks something like this: 1228 // 1229 // +--------------+ 1230 // | image | 1231 // +--------------+ 1232 // | boot oat | 1233 // +--------------+ 1234 // | alloc spaces | 1235 // +--------------+ 1236 // 1237 // There are several constraints on the loading of the image and boot.oat. 1238 // 1239 // 1. The image is expected to be loaded at an absolute address and 1240 // contains Objects with absolute pointers within the image. 1241 // 1242 // 2. There are absolute pointers from Methods in the image to their 1243 // code in the oat. 1244 // 1245 // 3. There are absolute pointers from the code in the oat to Methods 1246 // in the image. 1247 // 1248 // 4. There are absolute pointers from code in the oat to other code 1249 // in the oat. 1250 // 1251 // To get this all correct, we go through several steps. 1252 // 1253 // 1. We prepare offsets for all data in the oat file and calculate 1254 // the oat data size and code size. During this stage, we also set 1255 // oat code offsets in methods for use by the image writer. 1256 // 1257 // 2. We prepare offsets for the objects in the image and calculate 1258 // the image size. 1259 // 1260 // 3. We create the oat file. Originally this was just our own proprietary 1261 // file but now it is contained within an ELF dynamic object (aka an .so 1262 // file). Since we know the image size and oat data size and code size we 1263 // can prepare the ELF headers and we then know the ELF memory segment 1264 // layout and we can now resolve all references. The compiler provides 1265 // LinkerPatch information in each CompiledMethod and we resolve these, 1266 // using the layout information and image object locations provided by 1267 // image writer, as we're writing the method code. 1268 // 1269 // 4. We create the image file. It needs to know where the oat file 1270 // will be loaded after itself. Originally when oat file was simply 1271 // memory mapped so we could predict where its contents were based 1272 // on the file size. Now that it is an ELF file, we need to inspect 1273 // the ELF file to understand the in memory segment layout including 1274 // where the oat header is located within. 1275 // TODO: We could just remember this information from step 3. 1276 // 1277 // 5. We fixup the ELF program headers so that dlopen will try to 1278 // load the .so at the desired location at runtime by offsetting the 1279 // Elf32_Phdr.p_vaddr values by the desired base address. 1280 // TODO: Do this in step 3. We already know the layout there. 1281 // 1282 // Steps 1.-3. are done by the CreateOatFile() above, steps 4.-5. 1283 // are done by the CreateImageFile() below. 1284 1285 1286 // Write out the generated code part. Calls the OatWriter and ElfBuilder. Also prepares the 1287 // ImageWriter, if necessary. 1288 // Note: Flushing (and closing) the file is the caller's responsibility, except for the failure 1289 // case (when the file will be explicitly erased). 1290 bool CreateOatFile() { 1291 CHECK(key_value_store_.get() != nullptr); 1292 1293 TimingLogger::ScopedTiming t("dex2oat Oat", timings_); 1294 1295 std::unique_ptr<OatWriter> oat_writer; 1296 { 1297 TimingLogger::ScopedTiming t2("dex2oat OatWriter", timings_); 1298 std::string image_file_location; 1299 uint32_t image_file_location_oat_checksum = 0; 1300 uintptr_t image_file_location_oat_data_begin = 0; 1301 int32_t image_patch_delta = 0; 1302 if (image_) { 1303 PrepareImageWriter(image_base_); 1304 } else { 1305 TimingLogger::ScopedTiming t3("Loading image checksum", timings_); 1306 gc::space::ImageSpace* image_space = Runtime::Current()->GetHeap()->GetImageSpace(); 1307 image_file_location_oat_checksum = image_space->GetImageHeader().GetOatChecksum(); 1308 image_file_location_oat_data_begin = 1309 reinterpret_cast<uintptr_t>(image_space->GetImageHeader().GetOatDataBegin()); 1310 image_file_location = image_space->GetImageFilename(); 1311 image_patch_delta = image_space->GetImageHeader().GetPatchDelta(); 1312 } 1313 1314 if (!image_file_location.empty()) { 1315 key_value_store_->Put(OatHeader::kImageLocationKey, image_file_location); 1316 } 1317 1318 oat_writer.reset(new OatWriter(dex_files_, image_file_location_oat_checksum, 1319 image_file_location_oat_data_begin, 1320 image_patch_delta, 1321 driver_.get(), 1322 image_writer_.get(), 1323 timings_, 1324 key_value_store_.get())); 1325 } 1326 1327 if (image_) { 1328 // The OatWriter constructor has already updated offsets in methods and we need to 1329 // prepare method offsets in the image address space for direct method patching. 1330 TimingLogger::ScopedTiming t2("dex2oat Prepare image address space", timings_); 1331 if (!image_writer_->PrepareImageAddressSpace()) { 1332 LOG(ERROR) << "Failed to prepare image address space."; 1333 return false; 1334 } 1335 } 1336 1337 { 1338 TimingLogger::ScopedTiming t2("dex2oat Write ELF", timings_); 1339 if (!driver_->WriteElf(android_root_, is_host_, dex_files_, oat_writer.get(), 1340 oat_file_.get())) { 1341 LOG(ERROR) << "Failed to write ELF file " << oat_file_->GetPath(); 1342 return false; 1343 } 1344 } 1345 1346 VLOG(compiler) << "Oat file written successfully (unstripped): " << oat_location_; 1347 return true; 1348 } 1349 1350 // If we are compiling an image, invoke the image creation routine. Else just skip. 1351 bool HandleImage() { 1352 if (image_) { 1353 TimingLogger::ScopedTiming t("dex2oat ImageWriter", timings_); 1354 if (!CreateImageFile()) { 1355 return false; 1356 } 1357 VLOG(compiler) << "Image written successfully: " << image_filename_; 1358 } 1359 return true; 1360 } 1361 1362 // Create a copy from unstripped to stripped. 1363 bool CopyUnstrippedToStripped() { 1364 // If we don't want to strip in place, copy from unstripped location to stripped location. 1365 // We need to strip after image creation because FixupElf needs to use .strtab. 1366 if (oat_unstripped_ != oat_stripped_) { 1367 // If the oat file is still open, flush it. 1368 if (oat_file_.get() != nullptr && oat_file_->IsOpened()) { 1369 if (!FlushCloseOatFile()) { 1370 return false; 1371 } 1372 } 1373 1374 TimingLogger::ScopedTiming t("dex2oat OatFile copy", timings_); 1375 std::unique_ptr<File> in(OS::OpenFileForReading(oat_unstripped_.c_str())); 1376 std::unique_ptr<File> out(OS::CreateEmptyFile(oat_stripped_.c_str())); 1377 size_t buffer_size = 8192; 1378 std::unique_ptr<uint8_t[]> buffer(new uint8_t[buffer_size]); 1379 while (true) { 1380 int bytes_read = TEMP_FAILURE_RETRY(read(in->Fd(), buffer.get(), buffer_size)); 1381 if (bytes_read <= 0) { 1382 break; 1383 } 1384 bool write_ok = out->WriteFully(buffer.get(), bytes_read); 1385 CHECK(write_ok); 1386 } 1387 if (out->FlushCloseOrErase() != 0) { 1388 PLOG(ERROR) << "Failed to flush and close copied oat file: " << oat_stripped_; 1389 return false; 1390 } 1391 VLOG(compiler) << "Oat file copied successfully (stripped): " << oat_stripped_; 1392 } 1393 return true; 1394 } 1395 1396 bool FlushOatFile() { 1397 if (oat_file_.get() != nullptr) { 1398 TimingLogger::ScopedTiming t2("dex2oat Flush ELF", timings_); 1399 if (oat_file_->Flush() != 0) { 1400 PLOG(ERROR) << "Failed to flush oat file: " << oat_location_ << " / " 1401 << oat_filename_; 1402 oat_file_->Erase(); 1403 return false; 1404 } 1405 } 1406 return true; 1407 } 1408 1409 bool FlushCloseOatFile() { 1410 if (oat_file_.get() != nullptr) { 1411 std::unique_ptr<File> tmp(oat_file_.release()); 1412 if (tmp->FlushCloseOrErase() != 0) { 1413 PLOG(ERROR) << "Failed to flush and close oat file: " << oat_location_ << " / " 1414 << oat_filename_; 1415 return false; 1416 } 1417 } 1418 return true; 1419 } 1420 1421 void DumpTiming() { 1422 if (dump_timing_ || (dump_slow_timing_ && timings_->GetTotalNs() > MsToNs(1000))) { 1423 LOG(INFO) << Dumpable<TimingLogger>(*timings_); 1424 } 1425 if (dump_passes_) { 1426 LOG(INFO) << Dumpable<CumulativeLogger>(*driver_->GetTimingsLogger()); 1427 } 1428 } 1429 1430 CompilerOptions* GetCompilerOptions() const { 1431 return compiler_options_.get(); 1432 } 1433 1434 bool IsImage() const { 1435 return image_; 1436 } 1437 1438 bool IsHost() const { 1439 return is_host_; 1440 } 1441 1442 private: 1443 static size_t OpenDexFiles(const std::vector<const char*>& dex_filenames, 1444 const std::vector<const char*>& dex_locations, 1445 std::vector<const DexFile*>& dex_files) { 1446 size_t failure_count = 0; 1447 for (size_t i = 0; i < dex_filenames.size(); i++) { 1448 const char* dex_filename = dex_filenames[i]; 1449 const char* dex_location = dex_locations[i]; 1450 ATRACE_BEGIN(StringPrintf("Opening dex file '%s'", dex_filenames[i]).c_str()); 1451 std::string error_msg; 1452 if (!OS::FileExists(dex_filename)) { 1453 LOG(WARNING) << "Skipping non-existent dex file '" << dex_filename << "'"; 1454 continue; 1455 } 1456 if (!DexFile::Open(dex_filename, dex_location, &error_msg, &dex_files)) { 1457 LOG(WARNING) << "Failed to open .dex from file '" << dex_filename << "': " << error_msg; 1458 ++failure_count; 1459 } 1460 ATRACE_END(); 1461 } 1462 return failure_count; 1463 } 1464 1465 // Returns true if dex_files has a dex with the named location. 1466 static bool DexFilesContains(const std::vector<const DexFile*>& dex_files, 1467 const std::string& location) { 1468 for (size_t i = 0; i < dex_files.size(); ++i) { 1469 if (dex_files[i]->GetLocation() == location) { 1470 return true; 1471 } 1472 } 1473 return false; 1474 } 1475 1476 // Appends to dex_files any elements of class_path that it doesn't already 1477 // contain. This will open those dex files as necessary. 1478 static void OpenClassPathFiles(const std::string& class_path, 1479 std::vector<const DexFile*>& dex_files) { 1480 std::vector<std::string> parsed; 1481 Split(class_path, ':', &parsed); 1482 // Take Locks::mutator_lock_ so that lock ordering on the ClassLinker::dex_lock_ is maintained. 1483 ScopedObjectAccess soa(Thread::Current()); 1484 for (size_t i = 0; i < parsed.size(); ++i) { 1485 if (DexFilesContains(dex_files, parsed[i])) { 1486 continue; 1487 } 1488 std::string error_msg; 1489 if (!DexFile::Open(parsed[i].c_str(), parsed[i].c_str(), &error_msg, &dex_files)) { 1490 LOG(WARNING) << "Failed to open dex file '" << parsed[i] << "': " << error_msg; 1491 } 1492 } 1493 } 1494 1495 // Create a runtime necessary for compilation. 1496 bool CreateRuntime(const RuntimeOptions& runtime_options) 1497 SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_) { 1498 if (!Runtime::Create(runtime_options, false)) { 1499 LOG(ERROR) << "Failed to create runtime"; 1500 return false; 1501 } 1502 Runtime* runtime = Runtime::Current(); 1503 runtime->SetInstructionSet(instruction_set_); 1504 for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) { 1505 Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i); 1506 if (!runtime->HasCalleeSaveMethod(type)) { 1507 runtime->SetCalleeSaveMethod(runtime->CreateCalleeSaveMethod(), type); 1508 } 1509 } 1510 runtime->GetClassLinker()->FixupDexCaches(runtime->GetResolutionMethod()); 1511 runtime->GetClassLinker()->RunRootClinits(); 1512 runtime_ = runtime; 1513 return true; 1514 } 1515 1516 void PrepareImageWriter(uintptr_t image_base) { 1517 image_writer_.reset(new ImageWriter(*driver_, image_base, compiler_options_->GetCompilePic())); 1518 } 1519 1520 // Let the ImageWriter write the image file. If we do not compile PIC, also fix up the oat file. 1521 bool CreateImageFile() 1522 LOCKS_EXCLUDED(Locks::mutator_lock_) { 1523 CHECK(image_writer_ != nullptr); 1524 if (!image_writer_->Write(image_filename_, oat_unstripped_, oat_location_)) { 1525 LOG(ERROR) << "Failed to create image file " << image_filename_; 1526 return false; 1527 } 1528 uintptr_t oat_data_begin = image_writer_->GetOatDataBegin(); 1529 1530 // Destroy ImageWriter before doing FixupElf. 1531 image_writer_.reset(); 1532 1533 // Do not fix up the ELF file if we are --compile-pic 1534 if (!compiler_options_->GetCompilePic()) { 1535 std::unique_ptr<File> oat_file(OS::OpenFileReadWrite(oat_unstripped_.c_str())); 1536 if (oat_file.get() == nullptr) { 1537 PLOG(ERROR) << "Failed to open ELF file: " << oat_unstripped_; 1538 return false; 1539 } 1540 1541 if (!ElfWriter::Fixup(oat_file.get(), oat_data_begin)) { 1542 oat_file->Erase(); 1543 LOG(ERROR) << "Failed to fixup ELF file " << oat_file->GetPath(); 1544 return false; 1545 } 1546 1547 if (oat_file->FlushCloseOrErase()) { 1548 PLOG(ERROR) << "Failed to flush and close fixed ELF file " << oat_file->GetPath(); 1549 return false; 1550 } 1551 } 1552 1553 return true; 1554 } 1555 1556 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;) 1557 static std::set<std::string>* ReadImageClassesFromFile(const char* image_classes_filename) { 1558 std::unique_ptr<std::ifstream> image_classes_file(new std::ifstream(image_classes_filename, 1559 std::ifstream::in)); 1560 if (image_classes_file.get() == nullptr) { 1561 LOG(ERROR) << "Failed to open image classes file " << image_classes_filename; 1562 return nullptr; 1563 } 1564 std::unique_ptr<std::set<std::string>> result(ReadImageClasses(*image_classes_file)); 1565 image_classes_file->close(); 1566 return result.release(); 1567 } 1568 1569 static std::set<std::string>* ReadImageClasses(std::istream& image_classes_stream) { 1570 std::unique_ptr<std::set<std::string>> image_classes(new std::set<std::string>); 1571 while (image_classes_stream.good()) { 1572 std::string dot; 1573 std::getline(image_classes_stream, dot); 1574 if (StartsWith(dot, "#") || dot.empty()) { 1575 continue; 1576 } 1577 std::string descriptor(DotToDescriptor(dot.c_str())); 1578 image_classes->insert(descriptor); 1579 } 1580 return image_classes.release(); 1581 } 1582 1583 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;) 1584 static std::set<std::string>* ReadImageClassesFromZip(const char* zip_filename, 1585 const char* image_classes_filename, 1586 std::string* error_msg) { 1587 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::Open(zip_filename, error_msg)); 1588 if (zip_archive.get() == nullptr) { 1589 return nullptr; 1590 } 1591 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(image_classes_filename, error_msg)); 1592 if (zip_entry.get() == nullptr) { 1593 *error_msg = StringPrintf("Failed to find '%s' within '%s': %s", image_classes_filename, 1594 zip_filename, error_msg->c_str()); 1595 return nullptr; 1596 } 1597 std::unique_ptr<MemMap> image_classes_file(zip_entry->ExtractToMemMap(zip_filename, 1598 image_classes_filename, 1599 error_msg)); 1600 if (image_classes_file.get() == nullptr) { 1601 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", image_classes_filename, 1602 zip_filename, error_msg->c_str()); 1603 return nullptr; 1604 } 1605 const std::string image_classes_string(reinterpret_cast<char*>(image_classes_file->Begin()), 1606 image_classes_file->Size()); 1607 std::istringstream image_classes_stream(image_classes_string); 1608 return ReadImageClasses(image_classes_stream); 1609 } 1610 1611 void LogCompletionTime() { 1612 LOG(INFO) << "dex2oat took " << PrettyDuration(NanoTime() - start_ns_) 1613 << " (threads: " << thread_count_ << ") " 1614 << driver_->GetMemoryUsageString(); 1615 } 1616 1617 std::unique_ptr<CompilerOptions> compiler_options_; 1618 Compiler::Kind compiler_kind_; 1619 1620 InstructionSet instruction_set_; 1621 std::unique_ptr<const InstructionSetFeatures> instruction_set_features_; 1622 1623 std::unique_ptr<SafeMap<std::string, std::string> > key_value_store_; 1624 1625 std::unique_ptr<VerificationResults> verification_results_; 1626 DexFileToMethodInlinerMap method_inliner_map_; 1627 std::unique_ptr<QuickCompilerCallbacks> callbacks_; 1628 1629 // Not a unique_ptr as we want to just exit on non-debug builds, not bringing the runtime down 1630 // in an orderly fashion. The destructor takes care of deleting this. 1631 Runtime* runtime_; 1632 1633 size_t thread_count_; 1634 uint64_t start_ns_; 1635 std::unique_ptr<WatchDog> watchdog_; 1636 std::unique_ptr<File> oat_file_; 1637 std::string oat_stripped_; 1638 std::string oat_unstripped_; 1639 std::string oat_location_; 1640 std::string oat_filename_; 1641 int oat_fd_; 1642 std::vector<const char*> dex_filenames_; 1643 std::vector<const char*> dex_locations_; 1644 int zip_fd_; 1645 std::string zip_location_; 1646 std::string boot_image_option_; 1647 std::vector<const char*> runtime_args_; 1648 std::string image_filename_; 1649 uintptr_t image_base_; 1650 const char* image_classes_zip_filename_; 1651 const char* image_classes_filename_; 1652 const char* compiled_classes_zip_filename_; 1653 const char* compiled_classes_filename_; 1654 std::unique_ptr<std::set<std::string>> image_classes_; 1655 std::unique_ptr<std::set<std::string>> compiled_classes_; 1656 bool image_; 1657 std::unique_ptr<ImageWriter> image_writer_; 1658 bool is_host_; 1659 std::string android_root_; 1660 std::vector<const DexFile*> dex_files_; 1661 std::unique_ptr<CompilerDriver> driver_; 1662 std::vector<std::string> verbose_methods_; 1663 bool dump_stats_; 1664 bool dump_passes_; 1665 bool dump_timing_; 1666 bool dump_slow_timing_; 1667 std::string dump_cfg_file_name_; 1668 std::string swap_file_name_; 1669 int swap_fd_; 1670 std::string profile_file_; // Profile file to use 1671 TimingLogger* timings_; 1672 std::unique_ptr<CumulativeLogger> compiler_phases_timings_; 1673 std::unique_ptr<std::ostream> init_failure_output_; 1674 1675 DISALLOW_IMPLICIT_CONSTRUCTORS(Dex2Oat); 1676}; 1677 1678const unsigned int WatchDog::kWatchDogTimeoutSeconds; 1679 1680static void b13564922() { 1681#if defined(__linux__) && defined(__arm__) 1682 int major, minor; 1683 struct utsname uts; 1684 if (uname(&uts) != -1 && 1685 sscanf(uts.release, "%d.%d", &major, &minor) == 2 && 1686 ((major < 3) || ((major == 3) && (minor < 4)))) { 1687 // Kernels before 3.4 don't handle the ASLR well and we can run out of address 1688 // space (http://b/13564922). Work around the issue by inhibiting further mmap() randomization. 1689 int old_personality = personality(0xffffffff); 1690 if ((old_personality & ADDR_NO_RANDOMIZE) == 0) { 1691 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE); 1692 if (new_personality == -1) { 1693 LOG(WARNING) << "personality(. | ADDR_NO_RANDOMIZE) failed."; 1694 } 1695 } 1696 } 1697#endif 1698} 1699 1700static int CompileImage(Dex2Oat& dex2oat) { 1701 dex2oat.Compile(); 1702 1703 // Create the boot.oat. 1704 if (!dex2oat.CreateOatFile()) { 1705 dex2oat.EraseOatFile(); 1706 return EXIT_FAILURE; 1707 } 1708 1709 // Flush and close the boot.oat. We always expect the output file by name, and it will be 1710 // re-opened from the unstripped name. 1711 if (!dex2oat.FlushCloseOatFile()) { 1712 return EXIT_FAILURE; 1713 } 1714 1715 // Creates the boot.art and patches the boot.oat. 1716 if (!dex2oat.HandleImage()) { 1717 return EXIT_FAILURE; 1718 } 1719 1720 // When given --host, finish early without stripping. 1721 if (dex2oat.IsHost()) { 1722 dex2oat.DumpTiming(); 1723 return EXIT_SUCCESS; 1724 } 1725 1726 // Copy unstripped to stripped location, if necessary. 1727 if (!dex2oat.CopyUnstrippedToStripped()) { 1728 return EXIT_FAILURE; 1729 } 1730 1731 // FlushClose again, as stripping might have re-opened the oat file. 1732 if (!dex2oat.FlushCloseOatFile()) { 1733 return EXIT_FAILURE; 1734 } 1735 1736 dex2oat.DumpTiming(); 1737 return EXIT_SUCCESS; 1738} 1739 1740static int CompileApp(Dex2Oat& dex2oat) { 1741 dex2oat.Compile(); 1742 1743 // Create the app oat. 1744 if (!dex2oat.CreateOatFile()) { 1745 dex2oat.EraseOatFile(); 1746 return EXIT_FAILURE; 1747 } 1748 1749 // Do not close the oat file here. We might haven gotten the output file by file descriptor, 1750 // which we would lose. 1751 if (!dex2oat.FlushOatFile()) { 1752 return EXIT_FAILURE; 1753 } 1754 1755 // When given --host, finish early without stripping. 1756 if (dex2oat.IsHost()) { 1757 if (!dex2oat.FlushCloseOatFile()) { 1758 return EXIT_FAILURE; 1759 } 1760 1761 dex2oat.DumpTiming(); 1762 return EXIT_SUCCESS; 1763 } 1764 1765 // Copy unstripped to stripped location, if necessary. This will implicitly flush & close the 1766 // unstripped version. If this is given, we expect to be able to open writable files by name. 1767 if (!dex2oat.CopyUnstrippedToStripped()) { 1768 return EXIT_FAILURE; 1769 } 1770 1771 // Flush and close the file. 1772 if (!dex2oat.FlushCloseOatFile()) { 1773 return EXIT_FAILURE; 1774 } 1775 1776 dex2oat.DumpTiming(); 1777 return EXIT_SUCCESS; 1778} 1779 1780static int dex2oat(int argc, char** argv) { 1781 b13564922(); 1782 1783 TimingLogger timings("compiler", false, false); 1784 1785 Dex2Oat dex2oat(&timings); 1786 1787 // Parse arguments. Argument mistakes will lead to exit(EXIT_FAILURE) in UsageError. 1788 dex2oat.ParseArgs(argc, argv); 1789 1790 // Check early that the result of compilation can be written 1791 if (!dex2oat.OpenFile()) { 1792 return EXIT_FAILURE; 1793 } 1794 1795 LOG(INFO) << CommandLine(); 1796 1797 if (!dex2oat.Setup()) { 1798 dex2oat.EraseOatFile(); 1799 return EXIT_FAILURE; 1800 } 1801 1802 if (dex2oat.IsImage()) { 1803 return CompileImage(dex2oat); 1804 } else { 1805 return CompileApp(dex2oat); 1806 } 1807} 1808} // namespace art 1809 1810int main(int argc, char** argv) { 1811 int result = art::dex2oat(argc, argv); 1812 // Everything was done, do an explicit exit here to avoid running Runtime destructors that take 1813 // time (bug 10645725) unless we're a debug build or running on valgrind. Note: The Dex2Oat class 1814 // should not destruct the runtime in this case. 1815 if (!art::kIsDebugBuild && (RUNNING_ON_VALGRIND == 0)) { 1816 exit(result); 1817 } 1818 return result; 1819} 1820