dex2oat.cc revision 8363c772581bf00ebcdc2e38391b4bfae51beb75
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 <inttypes.h> 18#include <stdio.h> 19#include <stdlib.h> 20#include <sys/stat.h> 21#include <valgrind.h> 22 23#include <fstream> 24#include <iostream> 25#include <sstream> 26#include <string> 27#include <unordered_set> 28#include <vector> 29 30#if defined(__linux__) && defined(__arm__) 31#include <sys/personality.h> 32#include <sys/utsname.h> 33#endif 34 35#define ATRACE_TAG ATRACE_TAG_DALVIK 36#include <cutils/trace.h> 37 38#include "arch/instruction_set_features.h" 39#include "arch/mips/instruction_set_features_mips.h" 40#include "base/dumpable.h" 41#include "base/macros.h" 42#include "base/stl_util.h" 43#include "base/stringpiece.h" 44#include "base/time_utils.h" 45#include "base/timing_logger.h" 46#include "base/unix_file/fd_file.h" 47#include "class_linker.h" 48#include "compiler.h" 49#include "compiler_callbacks.h" 50#include "dex_file-inl.h" 51#include "dex/pass_manager.h" 52#include "dex/verification_results.h" 53#include "dex/quick_compiler_callbacks.h" 54#include "dex/quick/dex_file_to_method_inliner_map.h" 55#include "driver/compiler_driver.h" 56#include "driver/compiler_options.h" 57#include "elf_file.h" 58#include "elf_writer.h" 59#include "gc/space/image_space.h" 60#include "gc/space/space-inl.h" 61#include "image_writer.h" 62#include "interpreter/unstarted_runtime.h" 63#include "leb128.h" 64#include "mirror/art_method-inl.h" 65#include "mirror/class-inl.h" 66#include "mirror/class_loader.h" 67#include "mirror/object-inl.h" 68#include "mirror/object_array-inl.h" 69#include "oat_writer.h" 70#include "os.h" 71#include "runtime.h" 72#include "ScopedLocalRef.h" 73#include "scoped_thread_state_change.h" 74#include "utils.h" 75#include "vector_output_stream.h" 76#include "well_known_classes.h" 77#include "zip_archive.h" 78 79namespace art { 80 81static int original_argc; 82static char** original_argv; 83 84static std::string CommandLine() { 85 std::vector<std::string> command; 86 for (int i = 0; i < original_argc; ++i) { 87 command.push_back(original_argv[i]); 88 } 89 return Join(command, ' '); 90} 91 92static void UsageErrorV(const char* fmt, va_list ap) { 93 std::string error; 94 StringAppendV(&error, fmt, ap); 95 LOG(ERROR) << error; 96} 97 98static void UsageError(const char* fmt, ...) { 99 va_list ap; 100 va_start(ap, fmt); 101 UsageErrorV(fmt, ap); 102 va_end(ap); 103} 104 105NO_RETURN static void Usage(const char* fmt, ...) { 106 va_list ap; 107 va_start(ap, fmt); 108 UsageErrorV(fmt, ap); 109 va_end(ap); 110 111 UsageError("Command: %s", CommandLine().c_str()); 112 113 UsageError("Usage: dex2oat [options]..."); 114 UsageError(""); 115 UsageError(" -j<number>: specifies the number of threads used for compilation."); 116 UsageError(" Default is the number of detected hardware threads available on the"); 117 UsageError(" host system."); 118 UsageError(" Example: -j12"); 119 UsageError(""); 120 UsageError(" --dex-file=<dex-file>: specifies a .dex, .jar, or .apk file to compile."); 121 UsageError(" Example: --dex-file=/system/framework/core.jar"); 122 UsageError(""); 123 UsageError(" --dex-location=<dex-location>: specifies an alternative dex location to"); 124 UsageError(" encode in the oat file for the corresponding --dex-file argument."); 125 UsageError(" Example: --dex-file=/home/build/out/system/framework/core.jar"); 126 UsageError(" --dex-location=/system/framework/core.jar"); 127 UsageError(""); 128 UsageError(" --zip-fd=<file-descriptor>: specifies a file descriptor of a zip file"); 129 UsageError(" containing a classes.dex file to compile."); 130 UsageError(" Example: --zip-fd=5"); 131 UsageError(""); 132 UsageError(" --zip-location=<zip-location>: specifies a symbolic name for the file"); 133 UsageError(" corresponding to the file descriptor specified by --zip-fd."); 134 UsageError(" Example: --zip-location=/system/app/Calculator.apk"); 135 UsageError(""); 136 UsageError(" --oat-file=<file.oat>: specifies the oat output destination via a filename."); 137 UsageError(" Example: --oat-file=/system/framework/boot.oat"); 138 UsageError(""); 139 UsageError(" --oat-fd=<number>: specifies the oat output destination via a file descriptor."); 140 UsageError(" Example: --oat-fd=6"); 141 UsageError(""); 142 UsageError(" --oat-location=<oat-name>: specifies a symbolic name for the file corresponding"); 143 UsageError(" to the file descriptor specified by --oat-fd."); 144 UsageError(" Example: --oat-location=/data/dalvik-cache/system@app@Calculator.apk.oat"); 145 UsageError(""); 146 UsageError(" --oat-symbols=<file.oat>: specifies the oat output destination with full symbols."); 147 UsageError(" Example: --oat-symbols=/symbols/system/framework/boot.oat"); 148 UsageError(""); 149 UsageError(" --image=<file.art>: specifies the output image filename."); 150 UsageError(" Example: --image=/system/framework/boot.art"); 151 UsageError(""); 152 UsageError(" --image-classes=<classname-file>: specifies classes to include in an image."); 153 UsageError(" Example: --image=frameworks/base/preloaded-classes"); 154 UsageError(""); 155 UsageError(" --base=<hex-address>: specifies the base address when creating a boot image."); 156 UsageError(" Example: --base=0x50000000"); 157 UsageError(""); 158 UsageError(" --boot-image=<file.art>: provide the image file for the boot class path."); 159 UsageError(" Example: --boot-image=/system/framework/boot.art"); 160 UsageError(" Default: $ANDROID_ROOT/system/framework/boot.art"); 161 UsageError(""); 162 UsageError(" --android-root=<path>: used to locate libraries for portable linking."); 163 UsageError(" Example: --android-root=out/host/linux-x86"); 164 UsageError(" Default: $ANDROID_ROOT"); 165 UsageError(""); 166 UsageError(" --instruction-set=(arm|arm64|mips|mips64|x86|x86_64): compile for a particular"); 167 UsageError(" instruction set."); 168 UsageError(" Example: --instruction-set=x86"); 169 UsageError(" Default: arm"); 170 UsageError(""); 171 UsageError(" --instruction-set-features=...,: Specify instruction set features"); 172 UsageError(" Example: --instruction-set-features=div"); 173 UsageError(" Default: default"); 174 UsageError(""); 175 UsageError(" --compile-pic: Force indirect use of code, methods, and classes"); 176 UsageError(" Default: disabled"); 177 UsageError(""); 178 UsageError(" --compiler-backend=(Quick|Optimizing): select compiler backend"); 179 UsageError(" set."); 180 UsageError(" Example: --compiler-backend=Optimizing"); 181 if (kUseOptimizingCompiler) { 182 UsageError(" Default: Optimizing"); 183 } else { 184 UsageError(" Default: Quick"); 185 } 186 UsageError(""); 187 UsageError(" --compiler-filter=" 188 "(verify-none" 189 "|interpret-only" 190 "|space" 191 "|balanced" 192 "|speed" 193 "|everything" 194 "|time):"); 195 UsageError(" select compiler filter."); 196 UsageError(" Example: --compiler-filter=everything"); 197 UsageError(" Default: speed"); 198 UsageError(""); 199 UsageError(" --huge-method-max=<method-instruction-count>: threshold size for a huge"); 200 UsageError(" method for compiler filter tuning."); 201 UsageError(" Example: --huge-method-max=%d", CompilerOptions::kDefaultHugeMethodThreshold); 202 UsageError(" Default: %d", CompilerOptions::kDefaultHugeMethodThreshold); 203 UsageError(""); 204 UsageError(" --large-method-max=<method-instruction-count>: threshold size for a large"); 205 UsageError(" method for compiler filter tuning."); 206 UsageError(" Example: --large-method-max=%d", CompilerOptions::kDefaultLargeMethodThreshold); 207 UsageError(" Default: %d", CompilerOptions::kDefaultLargeMethodThreshold); 208 UsageError(""); 209 UsageError(" --small-method-max=<method-instruction-count>: threshold size for a small"); 210 UsageError(" method for compiler filter tuning."); 211 UsageError(" Example: --small-method-max=%d", CompilerOptions::kDefaultSmallMethodThreshold); 212 UsageError(" Default: %d", CompilerOptions::kDefaultSmallMethodThreshold); 213 UsageError(""); 214 UsageError(" --tiny-method-max=<method-instruction-count>: threshold size for a tiny"); 215 UsageError(" method for compiler filter tuning."); 216 UsageError(" Example: --tiny-method-max=%d", CompilerOptions::kDefaultTinyMethodThreshold); 217 UsageError(" Default: %d", CompilerOptions::kDefaultTinyMethodThreshold); 218 UsageError(""); 219 UsageError(" --num-dex-methods=<method-count>: threshold size for a small dex file for"); 220 UsageError(" compiler filter tuning. If the input has fewer than this many methods"); 221 UsageError(" and the filter is not interpret-only or verify-none, overrides the"); 222 UsageError(" filter to use speed"); 223 UsageError(" Example: --num-dex-method=%d", CompilerOptions::kDefaultNumDexMethodsThreshold); 224 UsageError(" Default: %d", CompilerOptions::kDefaultNumDexMethodsThreshold); 225 UsageError(""); 226 UsageError(" --dump-timing: display a breakdown of where time was spent"); 227 UsageError(""); 228 UsageError(" --include-patch-information: Include patching information so the generated code"); 229 UsageError(" can have its base address moved without full recompilation."); 230 UsageError(""); 231 UsageError(" --no-include-patch-information: Do not include patching information."); 232 UsageError(""); 233 UsageError(" -g"); 234 UsageError(" --generate-debug-info: Generate debug information for native debugging,"); 235 UsageError(" such as stack unwinding information, ELF symbols and DWARF sections."); 236 UsageError(" This generates all the available information. Unneeded parts can be"); 237 UsageError(" stripped using standard command line tools such as strip or objcopy."); 238 UsageError(" (enabled by default in debug builds, disabled by default otherwise)"); 239 UsageError(""); 240 UsageError(" --no-generate-debug-info: Do not generate debug information for native debugging."); 241 UsageError(""); 242 UsageError(" --runtime-arg <argument>: used to specify various arguments for the runtime,"); 243 UsageError(" such as initial heap size, maximum heap size, and verbose output."); 244 UsageError(" Use a separate --runtime-arg switch for each argument."); 245 UsageError(" Example: --runtime-arg -Xms256m"); 246 UsageError(""); 247 UsageError(" --profile-file=<filename>: specify profiler output file to use for compilation."); 248 UsageError(""); 249 UsageError(" --print-pass-names: print a list of pass names"); 250 UsageError(""); 251 UsageError(" --disable-passes=<pass-names>: disable one or more passes separated by comma."); 252 UsageError(" Example: --disable-passes=UseCount,BBOptimizations"); 253 UsageError(""); 254 UsageError(" --print-pass-options: print a list of passes that have configurable options along " 255 "with the setting."); 256 UsageError(" Will print default if no overridden setting exists."); 257 UsageError(""); 258 UsageError(" --pass-options=Pass1Name:Pass1OptionName:Pass1Option#," 259 "Pass2Name:Pass2OptionName:Pass2Option#"); 260 UsageError(" Used to specify a pass specific option. The setting itself must be integer."); 261 UsageError(" Separator used between options is a comma."); 262 UsageError(""); 263 UsageError(" --swap-file=<file-name>: specifies a file to use for swap."); 264 UsageError(" Example: --swap-file=/data/tmp/swap.001"); 265 UsageError(""); 266 UsageError(" --swap-fd=<file-descriptor>: specifies a file to use for swap (by descriptor)."); 267 UsageError(" Example: --swap-fd=10"); 268 UsageError(""); 269 std::cerr << "See log for usage error information\n"; 270 exit(EXIT_FAILURE); 271} 272 273// The primary goal of the watchdog is to prevent stuck build servers 274// during development when fatal aborts lead to a cascade of failures 275// that result in a deadlock. 276class WatchDog { 277// WatchDog defines its own CHECK_PTHREAD_CALL to avoid using LOG which uses locks 278#undef CHECK_PTHREAD_CALL 279#define CHECK_WATCH_DOG_PTHREAD_CALL(call, args, what) \ 280 do { \ 281 int rc = call args; \ 282 if (rc != 0) { \ 283 errno = rc; \ 284 std::string message(# call); \ 285 message += " failed for "; \ 286 message += reason; \ 287 Fatal(message); \ 288 } \ 289 } while (false) 290 291 public: 292 explicit WatchDog(bool is_watch_dog_enabled) { 293 is_watch_dog_enabled_ = is_watch_dog_enabled; 294 if (!is_watch_dog_enabled_) { 295 return; 296 } 297 shutting_down_ = false; 298 const char* reason = "dex2oat watch dog thread startup"; 299 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_init, (&mutex_, nullptr), reason); 300 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_init, (&cond_, nullptr), reason); 301 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_init, (&attr_), reason); 302 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_create, (&pthread_, &attr_, &CallBack, this), reason); 303 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_destroy, (&attr_), reason); 304 } 305 ~WatchDog() { 306 if (!is_watch_dog_enabled_) { 307 return; 308 } 309 const char* reason = "dex2oat watch dog thread shutdown"; 310 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason); 311 shutting_down_ = true; 312 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_signal, (&cond_), reason); 313 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason); 314 315 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_join, (pthread_, nullptr), reason); 316 317 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_destroy, (&cond_), reason); 318 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_destroy, (&mutex_), reason); 319 } 320 321 private: 322 static void* CallBack(void* arg) { 323 WatchDog* self = reinterpret_cast<WatchDog*>(arg); 324 ::art::SetThreadName("dex2oat watch dog"); 325 self->Wait(); 326 return nullptr; 327 } 328 329 NO_RETURN static void Fatal(const std::string& message) { 330 // TODO: When we can guarantee it won't prevent shutdown in error cases, move to LOG. However, 331 // it's rather easy to hang in unwinding. 332 // LogLine also avoids ART logging lock issues, as it's really only a wrapper around 333 // logcat logging or stderr output. 334 LogMessage::LogLine(__FILE__, __LINE__, LogSeverity::FATAL, message.c_str()); 335 exit(1); 336 } 337 338 void Wait() { 339 // TODO: tune the multiplier for GC verification, the following is just to make the timeout 340 // large. 341 constexpr int64_t multiplier = kVerifyObjectSupport > kVerifyObjectModeFast ? 100 : 1; 342 timespec timeout_ts; 343 InitTimeSpec(true, CLOCK_REALTIME, multiplier * kWatchDogTimeoutSeconds * 1000, 0, &timeout_ts); 344 const char* reason = "dex2oat watch dog thread waiting"; 345 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason); 346 while (!shutting_down_) { 347 int rc = TEMP_FAILURE_RETRY(pthread_cond_timedwait(&cond_, &mutex_, &timeout_ts)); 348 if (rc == ETIMEDOUT) { 349 Fatal(StringPrintf("dex2oat did not finish after %" PRId64 " seconds", 350 kWatchDogTimeoutSeconds)); 351 } else if (rc != 0) { 352 std::string message(StringPrintf("pthread_cond_timedwait failed: %s", 353 strerror(errno))); 354 Fatal(message.c_str()); 355 } 356 } 357 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason); 358 } 359 360 // When setting timeouts, keep in mind that the build server may not be as fast as your desktop. 361 // Debug builds are slower so they have larger timeouts. 362 static constexpr int64_t kSlowdownFactor = kIsDebugBuild ? 5U : 1U; 363 364 // 10 minutes scaled by kSlowdownFactor. 365 static constexpr int64_t kWatchDogTimeoutSeconds = kSlowdownFactor * 10 * 60; 366 367 bool is_watch_dog_enabled_; 368 bool shutting_down_; 369 // TODO: Switch to Mutex when we can guarantee it won't prevent shutdown in error cases. 370 pthread_mutex_t mutex_; 371 pthread_cond_t cond_; 372 pthread_attr_t attr_; 373 pthread_t pthread_; 374}; 375 376static void ParseStringAfterChar(const std::string& s, char c, std::string* parsed_value) { 377 std::string::size_type colon = s.find(c); 378 if (colon == std::string::npos) { 379 Usage("Missing char %c in option %s\n", c, s.c_str()); 380 } 381 // Add one to remove the char we were trimming until. 382 *parsed_value = s.substr(colon + 1); 383} 384 385static void ParseDouble(const std::string& option, char after_char, double min, double max, 386 double* parsed_value) { 387 std::string substring; 388 ParseStringAfterChar(option, after_char, &substring); 389 bool sane_val = true; 390 double value; 391 if (false) { 392 // TODO: this doesn't seem to work on the emulator. b/15114595 393 std::stringstream iss(substring); 394 iss >> value; 395 // Ensure that we have a value, there was no cruft after it and it satisfies a sensible range. 396 sane_val = iss.eof() && (value >= min) && (value <= max); 397 } else { 398 char* end = nullptr; 399 value = strtod(substring.c_str(), &end); 400 sane_val = *end == '\0' && value >= min && value <= max; 401 } 402 if (!sane_val) { 403 Usage("Invalid double value %s for option %s\n", substring.c_str(), option.c_str()); 404 } 405 *parsed_value = value; 406} 407 408static constexpr size_t kMinDexFilesForSwap = 2; 409static constexpr size_t kMinDexFileCumulativeSizeForSwap = 20 * MB; 410 411static bool UseSwap(bool is_image, std::vector<const DexFile*>& dex_files) { 412 if (is_image) { 413 // Don't use swap, we know generation should succeed, and we don't want to slow it down. 414 return false; 415 } 416 if (dex_files.size() < kMinDexFilesForSwap) { 417 // If there are less dex files than the threshold, assume it's gonna be fine. 418 return false; 419 } 420 size_t dex_files_size = 0; 421 for (const auto* dex_file : dex_files) { 422 dex_files_size += dex_file->GetHeader().file_size_; 423 } 424 return dex_files_size >= kMinDexFileCumulativeSizeForSwap; 425} 426 427class Dex2Oat FINAL { 428 public: 429 explicit Dex2Oat(TimingLogger* timings) : 430 compiler_kind_(kUseOptimizingCompiler ? Compiler::kOptimizing : Compiler::kQuick), 431 instruction_set_(kRuntimeISA), 432 // Take the default set of instruction features from the build. 433 method_inliner_map_(), 434 runtime_(nullptr), 435 thread_count_(sysconf(_SC_NPROCESSORS_CONF)), 436 start_ns_(NanoTime()), 437 oat_fd_(-1), 438 zip_fd_(-1), 439 image_base_(0U), 440 image_classes_zip_filename_(nullptr), 441 image_classes_filename_(nullptr), 442 compiled_classes_zip_filename_(nullptr), 443 compiled_classes_filename_(nullptr), 444 compiled_methods_zip_filename_(nullptr), 445 compiled_methods_filename_(nullptr), 446 image_(false), 447 is_host_(false), 448 dump_stats_(false), 449 dump_passes_(false), 450 dump_timing_(false), 451 dump_slow_timing_(kIsDebugBuild), 452 swap_fd_(-1), 453 timings_(timings) {} 454 455 ~Dex2Oat() { 456 // Free opened dex files before deleting the runtime_, because ~DexFile 457 // uses MemMap, which is shut down by ~Runtime. 458 class_path_files_.clear(); 459 opened_dex_files_.clear(); 460 461 // Log completion time before deleting the runtime_, because this accesses 462 // the runtime. 463 LogCompletionTime(); 464 465 if (kIsDebugBuild || (RUNNING_ON_VALGRIND != 0)) { 466 delete runtime_; // See field declaration for why this is manual. 467 } 468 } 469 470 // Parse the arguments from the command line. In case of an unrecognized option or impossible 471 // values/combinations, a usage error will be displayed and exit() is called. Thus, if the method 472 // returns, arguments have been successfully parsed. 473 void ParseArgs(int argc, char** argv) { 474 original_argc = argc; 475 original_argv = argv; 476 477 InitLogging(argv); 478 479 // Skip over argv[0]. 480 argv++; 481 argc--; 482 483 if (argc == 0) { 484 Usage("No arguments specified"); 485 } 486 487 std::string oat_symbols; 488 std::string boot_image_filename; 489 const char* compiler_filter_string = nullptr; 490 bool compile_pic = false; 491 int huge_method_threshold = CompilerOptions::kDefaultHugeMethodThreshold; 492 int large_method_threshold = CompilerOptions::kDefaultLargeMethodThreshold; 493 int small_method_threshold = CompilerOptions::kDefaultSmallMethodThreshold; 494 int tiny_method_threshold = CompilerOptions::kDefaultTinyMethodThreshold; 495 int num_dex_methods_threshold = CompilerOptions::kDefaultNumDexMethodsThreshold; 496 497 // Profile file to use 498 double top_k_profile_threshold = CompilerOptions::kDefaultTopKProfileThreshold; 499 500 bool debuggable = false; 501 bool include_patch_information = CompilerOptions::kDefaultIncludePatchInformation; 502 bool generate_debug_info = kIsDebugBuild; 503 bool watch_dog_enabled = true; 504 bool abort_on_hard_verifier_error = false; 505 bool requested_specific_compiler = false; 506 507 PassManagerOptions pass_manager_options; 508 509 std::string error_msg; 510 511 for (int i = 0; i < argc; i++) { 512 const StringPiece option(argv[i]); 513 const bool log_options = false; 514 if (log_options) { 515 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i]; 516 } 517 if (option.starts_with("--dex-file=")) { 518 dex_filenames_.push_back(option.substr(strlen("--dex-file=")).data()); 519 } else if (option.starts_with("--dex-location=")) { 520 dex_locations_.push_back(option.substr(strlen("--dex-location=")).data()); 521 } else if (option.starts_with("--zip-fd=")) { 522 const char* zip_fd_str = option.substr(strlen("--zip-fd=")).data(); 523 if (!ParseInt(zip_fd_str, &zip_fd_)) { 524 Usage("Failed to parse --zip-fd argument '%s' as an integer", zip_fd_str); 525 } 526 if (zip_fd_ < 0) { 527 Usage("--zip-fd passed a negative value %d", zip_fd_); 528 } 529 } else if (option.starts_with("--zip-location=")) { 530 zip_location_ = option.substr(strlen("--zip-location=")).data(); 531 } else if (option.starts_with("--oat-file=")) { 532 oat_filename_ = option.substr(strlen("--oat-file=")).data(); 533 } else if (option.starts_with("--oat-symbols=")) { 534 oat_symbols = option.substr(strlen("--oat-symbols=")).data(); 535 } else if (option.starts_with("--oat-fd=")) { 536 const char* oat_fd_str = option.substr(strlen("--oat-fd=")).data(); 537 if (!ParseInt(oat_fd_str, &oat_fd_)) { 538 Usage("Failed to parse --oat-fd argument '%s' as an integer", oat_fd_str); 539 } 540 if (oat_fd_ < 0) { 541 Usage("--oat-fd passed a negative value %d", oat_fd_); 542 } 543 } else if (option == "--watch-dog") { 544 watch_dog_enabled = true; 545 } else if (option == "--no-watch-dog") { 546 watch_dog_enabled = false; 547 } else if (option.starts_with("-j")) { 548 const char* thread_count_str = option.substr(strlen("-j")).data(); 549 if (!ParseUint(thread_count_str, &thread_count_)) { 550 Usage("Failed to parse -j argument '%s' as an integer", thread_count_str); 551 } 552 } else if (option.starts_with("--oat-location=")) { 553 oat_location_ = option.substr(strlen("--oat-location=")).data(); 554 } else if (option.starts_with("--image=")) { 555 image_filename_ = option.substr(strlen("--image=")).data(); 556 } else if (option.starts_with("--image-classes=")) { 557 image_classes_filename_ = option.substr(strlen("--image-classes=")).data(); 558 } else if (option.starts_with("--image-classes-zip=")) { 559 image_classes_zip_filename_ = option.substr(strlen("--image-classes-zip=")).data(); 560 } else if (option.starts_with("--compiled-classes=")) { 561 compiled_classes_filename_ = option.substr(strlen("--compiled-classes=")).data(); 562 } else if (option.starts_with("--compiled-classes-zip=")) { 563 compiled_classes_zip_filename_ = option.substr(strlen("--compiled-classes-zip=")).data(); 564 } else if (option.starts_with("--compiled-methods=")) { 565 compiled_methods_filename_ = option.substr(strlen("--compiled-methods=")).data(); 566 } else if (option.starts_with("--compiled-methods-zip=")) { 567 compiled_methods_zip_filename_ = option.substr(strlen("--compiled-methods-zip=")).data(); 568 } else if (option.starts_with("--base=")) { 569 const char* image_base_str = option.substr(strlen("--base=")).data(); 570 char* end; 571 image_base_ = strtoul(image_base_str, &end, 16); 572 if (end == image_base_str || *end != '\0') { 573 Usage("Failed to parse hexadecimal value for option %s", option.data()); 574 } 575 } else if (option.starts_with("--boot-image=")) { 576 boot_image_filename = option.substr(strlen("--boot-image=")).data(); 577 } else if (option.starts_with("--android-root=")) { 578 android_root_ = option.substr(strlen("--android-root=")).data(); 579 } else if (option.starts_with("--instruction-set=")) { 580 StringPiece instruction_set_str = option.substr(strlen("--instruction-set=")).data(); 581 // StringPiece is not necessarily zero-terminated, so need to make a copy and ensure it. 582 std::unique_ptr<char[]> buf(new char[instruction_set_str.length() + 1]); 583 strncpy(buf.get(), instruction_set_str.data(), instruction_set_str.length()); 584 buf.get()[instruction_set_str.length()] = 0; 585 instruction_set_ = GetInstructionSetFromString(buf.get()); 586 // arm actually means thumb2. 587 if (instruction_set_ == InstructionSet::kArm) { 588 instruction_set_ = InstructionSet::kThumb2; 589 } 590 } else if (option.starts_with("--instruction-set-variant=")) { 591 StringPiece str = option.substr(strlen("--instruction-set-variant=")).data(); 592 instruction_set_features_.reset( 593 InstructionSetFeatures::FromVariant(instruction_set_, str.as_string(), &error_msg)); 594 if (instruction_set_features_.get() == nullptr) { 595 Usage("%s", error_msg.c_str()); 596 } 597 } else if (option.starts_with("--instruction-set-features=")) { 598 StringPiece str = option.substr(strlen("--instruction-set-features=")).data(); 599 if (instruction_set_features_.get() == nullptr) { 600 instruction_set_features_.reset( 601 InstructionSetFeatures::FromVariant(instruction_set_, "default", &error_msg)); 602 if (instruction_set_features_.get() == nullptr) { 603 Usage("Problem initializing default instruction set features variant: %s", 604 error_msg.c_str()); 605 } 606 } 607 instruction_set_features_.reset( 608 instruction_set_features_->AddFeaturesFromString(str.as_string(), &error_msg)); 609 if (instruction_set_features_.get() == nullptr) { 610 Usage("Error parsing '%s': %s", option.data(), error_msg.c_str()); 611 } 612 } else if (option.starts_with("--compiler-backend=")) { 613 requested_specific_compiler = true; 614 StringPiece backend_str = option.substr(strlen("--compiler-backend=")).data(); 615 if (backend_str == "Quick") { 616 compiler_kind_ = Compiler::kQuick; 617 } else if (backend_str == "Optimizing") { 618 compiler_kind_ = Compiler::kOptimizing; 619 } else { 620 Usage("Unknown compiler backend: %s", backend_str.data()); 621 } 622 } else if (option.starts_with("--compiler-filter=")) { 623 compiler_filter_string = option.substr(strlen("--compiler-filter=")).data(); 624 } else if (option == "--compile-pic") { 625 compile_pic = true; 626 } else if (option.starts_with("--huge-method-max=")) { 627 const char* threshold = option.substr(strlen("--huge-method-max=")).data(); 628 if (!ParseInt(threshold, &huge_method_threshold)) { 629 Usage("Failed to parse --huge-method-max '%s' as an integer", threshold); 630 } 631 if (huge_method_threshold < 0) { 632 Usage("--huge-method-max passed a negative value %s", huge_method_threshold); 633 } 634 } else if (option.starts_with("--large-method-max=")) { 635 const char* threshold = option.substr(strlen("--large-method-max=")).data(); 636 if (!ParseInt(threshold, &large_method_threshold)) { 637 Usage("Failed to parse --large-method-max '%s' as an integer", threshold); 638 } 639 if (large_method_threshold < 0) { 640 Usage("--large-method-max passed a negative value %s", large_method_threshold); 641 } 642 } else if (option.starts_with("--small-method-max=")) { 643 const char* threshold = option.substr(strlen("--small-method-max=")).data(); 644 if (!ParseInt(threshold, &small_method_threshold)) { 645 Usage("Failed to parse --small-method-max '%s' as an integer", threshold); 646 } 647 if (small_method_threshold < 0) { 648 Usage("--small-method-max passed a negative value %s", small_method_threshold); 649 } 650 } else if (option.starts_with("--tiny-method-max=")) { 651 const char* threshold = option.substr(strlen("--tiny-method-max=")).data(); 652 if (!ParseInt(threshold, &tiny_method_threshold)) { 653 Usage("Failed to parse --tiny-method-max '%s' as an integer", threshold); 654 } 655 if (tiny_method_threshold < 0) { 656 Usage("--tiny-method-max passed a negative value %s", tiny_method_threshold); 657 } 658 } else if (option.starts_with("--num-dex-methods=")) { 659 const char* threshold = option.substr(strlen("--num-dex-methods=")).data(); 660 if (!ParseInt(threshold, &num_dex_methods_threshold)) { 661 Usage("Failed to parse --num-dex-methods '%s' as an integer", threshold); 662 } 663 if (num_dex_methods_threshold < 0) { 664 Usage("--num-dex-methods passed a negative value %s", num_dex_methods_threshold); 665 } 666 } else if (option == "--host") { 667 is_host_ = true; 668 } else if (option == "--runtime-arg") { 669 if (++i >= argc) { 670 Usage("Missing required argument for --runtime-arg"); 671 } 672 if (log_options) { 673 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i]; 674 } 675 runtime_args_.push_back(argv[i]); 676 } else if (option == "--dump-timing") { 677 dump_timing_ = true; 678 } else if (option == "--dump-passes") { 679 dump_passes_ = true; 680 } else if (option.starts_with("--dump-cfg=")) { 681 dump_cfg_file_name_ = option.substr(strlen("--dump-cfg=")).data(); 682 } else if (option == "--dump-stats") { 683 dump_stats_ = true; 684 } else if (option == "--generate-debug-info" || option == "-g") { 685 generate_debug_info = true; 686 } else if (option == "--no-generate-debug-info") { 687 generate_debug_info = false; 688 } else if (option == "--debuggable") { 689 debuggable = true; 690 generate_debug_info = true; 691 } else if (option.starts_with("--profile-file=")) { 692 profile_file_ = option.substr(strlen("--profile-file=")).data(); 693 VLOG(compiler) << "dex2oat: profile file is " << profile_file_; 694 } else if (option == "--no-profile-file") { 695 // No profile 696 } else if (option.starts_with("--top-k-profile-threshold=")) { 697 ParseDouble(option.data(), '=', 0.0, 100.0, &top_k_profile_threshold); 698 } else if (option == "--print-pass-names") { 699 pass_manager_options.SetPrintPassNames(true); 700 } else if (option.starts_with("--disable-passes=")) { 701 const std::string disable_passes = option.substr(strlen("--disable-passes=")).data(); 702 pass_manager_options.SetDisablePassList(disable_passes); 703 } else if (option.starts_with("--print-passes=")) { 704 const std::string print_passes = option.substr(strlen("--print-passes=")).data(); 705 pass_manager_options.SetPrintPassList(print_passes); 706 } else if (option == "--print-all-passes") { 707 pass_manager_options.SetPrintAllPasses(); 708 } else if (option.starts_with("--dump-cfg-passes=")) { 709 const std::string dump_passes_string = option.substr(strlen("--dump-cfg-passes=")).data(); 710 pass_manager_options.SetDumpPassList(dump_passes_string); 711 } else if (option == "--print-pass-options") { 712 pass_manager_options.SetPrintPassOptions(true); 713 } else if (option.starts_with("--pass-options=")) { 714 const std::string options = option.substr(strlen("--pass-options=")).data(); 715 pass_manager_options.SetOverriddenPassOptions(options); 716 } else if (option == "--include-patch-information") { 717 include_patch_information = true; 718 } else if (option == "--no-include-patch-information") { 719 include_patch_information = false; 720 } else if (option.starts_with("--verbose-methods=")) { 721 // TODO: rather than switch off compiler logging, make all VLOG(compiler) messages 722 // conditional on having verbost methods. 723 gLogVerbosity.compiler = false; 724 Split(option.substr(strlen("--verbose-methods=")).ToString(), ',', &verbose_methods_); 725 } else if (option.starts_with("--dump-init-failures=")) { 726 std::string file_name = option.substr(strlen("--dump-init-failures=")).data(); 727 init_failure_output_.reset(new std::ofstream(file_name)); 728 if (init_failure_output_.get() == nullptr) { 729 LOG(ERROR) << "Failed to allocate ofstream"; 730 } else if (init_failure_output_->fail()) { 731 LOG(ERROR) << "Failed to open " << file_name << " for writing the initialization " 732 << "failures."; 733 init_failure_output_.reset(); 734 } 735 } else if (option.starts_with("--swap-file=")) { 736 swap_file_name_ = option.substr(strlen("--swap-file=")).data(); 737 } else if (option.starts_with("--swap-fd=")) { 738 const char* swap_fd_str = option.substr(strlen("--swap-fd=")).data(); 739 if (!ParseInt(swap_fd_str, &swap_fd_)) { 740 Usage("Failed to parse --swap-fd argument '%s' as an integer", swap_fd_str); 741 } 742 if (swap_fd_ < 0) { 743 Usage("--swap-fd passed a negative value %d", swap_fd_); 744 } 745 } else if (option == "--abort-on-hard-verifier-error") { 746 abort_on_hard_verifier_error = true; 747 } else { 748 Usage("Unknown argument %s", option.data()); 749 } 750 } 751 752 image_ = (!image_filename_.empty()); 753 if (!requested_specific_compiler && !kUseOptimizingCompiler) { 754 // If no specific compiler is requested, the current behavior is 755 // to compile the boot image with Quick, and the rest with Optimizing. 756 compiler_kind_ = image_ ? Compiler::kQuick : Compiler::kOptimizing; 757 } 758 759 if (compiler_kind_ == Compiler::kOptimizing) { 760 // Optimizing only supports PIC mode. 761 compile_pic = true; 762 } 763 764 if (oat_filename_.empty() && oat_fd_ == -1) { 765 Usage("Output must be supplied with either --oat-file or --oat-fd"); 766 } 767 768 if (!oat_filename_.empty() && oat_fd_ != -1) { 769 Usage("--oat-file should not be used with --oat-fd"); 770 } 771 772 if (!oat_symbols.empty() && oat_fd_ != -1) { 773 Usage("--oat-symbols should not be used with --oat-fd"); 774 } 775 776 if (!oat_symbols.empty() && is_host_) { 777 Usage("--oat-symbols should not be used with --host"); 778 } 779 780 if (oat_fd_ != -1 && !image_filename_.empty()) { 781 Usage("--oat-fd should not be used with --image"); 782 } 783 784 if (android_root_.empty()) { 785 const char* android_root_env_var = getenv("ANDROID_ROOT"); 786 if (android_root_env_var == nullptr) { 787 Usage("--android-root unspecified and ANDROID_ROOT not set"); 788 } 789 android_root_ += android_root_env_var; 790 } 791 792 if (!image_ && boot_image_filename.empty()) { 793 boot_image_filename += android_root_; 794 boot_image_filename += "/framework/boot.art"; 795 } 796 if (!boot_image_filename.empty()) { 797 boot_image_option_ += "-Ximage:"; 798 boot_image_option_ += boot_image_filename; 799 } 800 801 if (image_classes_filename_ != nullptr && !image_) { 802 Usage("--image-classes should only be used with --image"); 803 } 804 805 if (image_classes_filename_ != nullptr && !boot_image_option_.empty()) { 806 Usage("--image-classes should not be used with --boot-image"); 807 } 808 809 if (image_classes_zip_filename_ != nullptr && image_classes_filename_ == nullptr) { 810 Usage("--image-classes-zip should be used with --image-classes"); 811 } 812 813 if (compiled_classes_filename_ != nullptr && !image_) { 814 Usage("--compiled-classes should only be used with --image"); 815 } 816 817 if (compiled_classes_filename_ != nullptr && !boot_image_option_.empty()) { 818 Usage("--compiled-classes should not be used with --boot-image"); 819 } 820 821 if (compiled_classes_zip_filename_ != nullptr && compiled_classes_filename_ == nullptr) { 822 Usage("--compiled-classes-zip should be used with --compiled-classes"); 823 } 824 825 if (dex_filenames_.empty() && zip_fd_ == -1) { 826 Usage("Input must be supplied with either --dex-file or --zip-fd"); 827 } 828 829 if (!dex_filenames_.empty() && zip_fd_ != -1) { 830 Usage("--dex-file should not be used with --zip-fd"); 831 } 832 833 if (!dex_filenames_.empty() && !zip_location_.empty()) { 834 Usage("--dex-file should not be used with --zip-location"); 835 } 836 837 if (dex_locations_.empty()) { 838 for (const char* dex_file_name : dex_filenames_) { 839 dex_locations_.push_back(dex_file_name); 840 } 841 } else if (dex_locations_.size() != dex_filenames_.size()) { 842 Usage("--dex-location arguments do not match --dex-file arguments"); 843 } 844 845 if (zip_fd_ != -1 && zip_location_.empty()) { 846 Usage("--zip-location should be supplied with --zip-fd"); 847 } 848 849 if (boot_image_option_.empty()) { 850 if (image_base_ == 0) { 851 Usage("Non-zero --base not specified"); 852 } 853 } 854 855 oat_stripped_ = oat_filename_; 856 if (!oat_symbols.empty()) { 857 oat_unstripped_ = oat_symbols; 858 } else { 859 oat_unstripped_ = oat_filename_; 860 } 861 862 // If no instruction set feature was given, use the default one for the target 863 // instruction set. 864 if (instruction_set_features_.get() == nullptr) { 865 instruction_set_features_.reset( 866 InstructionSetFeatures::FromVariant(instruction_set_, "default", &error_msg)); 867 if (instruction_set_features_.get() == nullptr) { 868 Usage("Problem initializing default instruction set features variant: %s", 869 error_msg.c_str()); 870 } 871 } 872 873 if (instruction_set_ == kRuntimeISA) { 874 std::unique_ptr<const InstructionSetFeatures> runtime_features( 875 InstructionSetFeatures::FromCppDefines()); 876 if (!instruction_set_features_->Equals(runtime_features.get())) { 877 LOG(WARNING) << "Mismatch between dex2oat instruction set features (" 878 << *instruction_set_features_ << ") and those of dex2oat executable (" 879 << *runtime_features <<") for the command line:\n" 880 << CommandLine(); 881 } 882 } 883 884 if (compiler_filter_string == nullptr) { 885 compiler_filter_string = "speed"; 886 } 887 888 CHECK(compiler_filter_string != nullptr); 889 CompilerOptions::CompilerFilter compiler_filter = CompilerOptions::kDefaultCompilerFilter; 890 if (strcmp(compiler_filter_string, "verify-none") == 0) { 891 compiler_filter = CompilerOptions::kVerifyNone; 892 } else if (strcmp(compiler_filter_string, "interpret-only") == 0) { 893 compiler_filter = CompilerOptions::kInterpretOnly; 894 } else if (strcmp(compiler_filter_string, "verify-at-runtime") == 0) { 895 compiler_filter = CompilerOptions::kVerifyAtRuntime; 896 } else if (strcmp(compiler_filter_string, "space") == 0) { 897 compiler_filter = CompilerOptions::kSpace; 898 } else if (strcmp(compiler_filter_string, "balanced") == 0) { 899 compiler_filter = CompilerOptions::kBalanced; 900 } else if (strcmp(compiler_filter_string, "speed") == 0) { 901 compiler_filter = CompilerOptions::kSpeed; 902 } else if (strcmp(compiler_filter_string, "everything") == 0) { 903 compiler_filter = CompilerOptions::kEverything; 904 } else if (strcmp(compiler_filter_string, "time") == 0) { 905 compiler_filter = CompilerOptions::kTime; 906 } else { 907 Usage("Unknown --compiler-filter value %s", compiler_filter_string); 908 } 909 910 // Checks are all explicit until we know the architecture. 911 bool implicit_null_checks = false; 912 bool implicit_so_checks = false; 913 bool implicit_suspend_checks = false; 914 // Set the compilation target's implicit checks options. 915 switch (instruction_set_) { 916 case kArm: 917 case kThumb2: 918 case kArm64: 919 case kX86: 920 case kX86_64: 921 implicit_null_checks = true; 922 implicit_so_checks = true; 923 break; 924 925 default: 926 // Defaults are correct. 927 break; 928 } 929 930 compiler_options_.reset(new CompilerOptions(compiler_filter, 931 huge_method_threshold, 932 large_method_threshold, 933 small_method_threshold, 934 tiny_method_threshold, 935 num_dex_methods_threshold, 936 include_patch_information, 937 top_k_profile_threshold, 938 debuggable, 939 generate_debug_info, 940 implicit_null_checks, 941 implicit_so_checks, 942 implicit_suspend_checks, 943 compile_pic, 944 verbose_methods_.empty() ? 945 nullptr : 946 &verbose_methods_, 947 new PassManagerOptions(pass_manager_options), 948 init_failure_output_.get(), 949 abort_on_hard_verifier_error)); 950 951 // Done with usage checks, enable watchdog if requested 952 if (watch_dog_enabled) { 953 watchdog_.reset(new WatchDog(true)); 954 } 955 956 // Fill some values into the key-value store for the oat header. 957 key_value_store_.reset(new SafeMap<std::string, std::string>()); 958 959 // Insert some compiler things. 960 { 961 std::ostringstream oss; 962 for (int i = 0; i < argc; ++i) { 963 if (i > 0) { 964 oss << ' '; 965 } 966 oss << argv[i]; 967 } 968 key_value_store_->Put(OatHeader::kDex2OatCmdLineKey, oss.str()); 969 oss.str(""); // Reset. 970 oss << kRuntimeISA; 971 key_value_store_->Put(OatHeader::kDex2OatHostKey, oss.str()); 972 key_value_store_->Put(OatHeader::kPicKey, 973 compile_pic ? OatHeader::kTrueValue : OatHeader::kFalseValue); 974 key_value_store_->Put(OatHeader::kDebuggableKey, 975 debuggable ? OatHeader::kTrueValue : OatHeader::kFalseValue); 976 } 977 } 978 979 // Check whether the oat output file is writable, and open it for later. Also open a swap file, 980 // if a name is given. 981 bool OpenFile() { 982 bool create_file = !oat_unstripped_.empty(); // as opposed to using open file descriptor 983 if (create_file) { 984 oat_file_.reset(OS::CreateEmptyFile(oat_unstripped_.c_str())); 985 if (oat_location_.empty()) { 986 oat_location_ = oat_filename_; 987 } 988 } else { 989 oat_file_.reset(new File(oat_fd_, oat_location_, true)); 990 oat_file_->DisableAutoClose(); 991 if (oat_file_->SetLength(0) != 0) { 992 PLOG(WARNING) << "Truncating oat file " << oat_location_ << " failed."; 993 } 994 } 995 if (oat_file_.get() == nullptr) { 996 PLOG(ERROR) << "Failed to create oat file: " << oat_location_; 997 return false; 998 } 999 if (create_file && fchmod(oat_file_->Fd(), 0644) != 0) { 1000 PLOG(ERROR) << "Failed to make oat file world readable: " << oat_location_; 1001 oat_file_->Erase(); 1002 return false; 1003 } 1004 1005 // Swap file handling. 1006 // 1007 // If the swap fd is not -1, we assume this is the file descriptor of an open but unlinked file 1008 // that we can use for swap. 1009 // 1010 // If the swap fd is -1 and we have a swap-file string, open the given file as a swap file. We 1011 // will immediately unlink to satisfy the swap fd assumption. 1012 if (swap_fd_ == -1 && !swap_file_name_.empty()) { 1013 std::unique_ptr<File> swap_file(OS::CreateEmptyFile(swap_file_name_.c_str())); 1014 if (swap_file.get() == nullptr) { 1015 PLOG(ERROR) << "Failed to create swap file: " << swap_file_name_; 1016 return false; 1017 } 1018 swap_fd_ = swap_file->Fd(); 1019 swap_file->MarkUnchecked(); // We don't we to track this, it will be unlinked immediately. 1020 swap_file->DisableAutoClose(); // We'll handle it ourselves, the File object will be 1021 // released immediately. 1022 unlink(swap_file_name_.c_str()); 1023 } 1024 1025 return true; 1026 } 1027 1028 void EraseOatFile() { 1029 DCHECK(oat_file_.get() != nullptr); 1030 oat_file_->Erase(); 1031 oat_file_.reset(); 1032 } 1033 1034 // Set up the environment for compilation. Includes starting the runtime and loading/opening the 1035 // boot class path. 1036 bool Setup() { 1037 TimingLogger::ScopedTiming t("dex2oat Setup", timings_); 1038 RuntimeOptions runtime_options; 1039 art::MemMap::Init(); // For ZipEntry::ExtractToMemMap. 1040 if (boot_image_option_.empty()) { 1041 std::string boot_class_path = "-Xbootclasspath:"; 1042 boot_class_path += Join(dex_filenames_, ':'); 1043 runtime_options.push_back(std::make_pair(boot_class_path, nullptr)); 1044 std::string boot_class_path_locations = "-Xbootclasspath-locations:"; 1045 boot_class_path_locations += Join(dex_locations_, ':'); 1046 runtime_options.push_back(std::make_pair(boot_class_path_locations, nullptr)); 1047 } else { 1048 runtime_options.push_back(std::make_pair(boot_image_option_, nullptr)); 1049 } 1050 for (size_t i = 0; i < runtime_args_.size(); i++) { 1051 runtime_options.push_back(std::make_pair(runtime_args_[i], nullptr)); 1052 } 1053 1054 verification_results_.reset(new VerificationResults(compiler_options_.get())); 1055 callbacks_.reset(new QuickCompilerCallbacks( 1056 verification_results_.get(), 1057 &method_inliner_map_, 1058 image_ ? 1059 CompilerCallbacks::CallbackMode::kCompileBootImage : 1060 CompilerCallbacks::CallbackMode::kCompileApp)); 1061 runtime_options.push_back(std::make_pair("compilercallbacks", callbacks_.get())); 1062 runtime_options.push_back( 1063 std::make_pair("imageinstructionset", GetInstructionSetString(instruction_set_))); 1064 1065 // Only allow no boot image for the runtime if we're compiling one. When we compile an app, 1066 // we don't want fallback mode, it will abort as we do not push a boot classpath (it might 1067 // have been stripped in preopting, anyways). 1068 if (!image_) { 1069 runtime_options.push_back(std::make_pair("-Xno-dex-file-fallback", nullptr)); 1070 } 1071 1072 if (!CreateRuntime(runtime_options)) { 1073 return false; 1074 } 1075 1076 // Runtime::Create acquired the mutator_lock_ that is normally given away when we 1077 // Runtime::Start, give it away now so that we don't starve GC. 1078 Thread* self = Thread::Current(); 1079 self->TransitionFromRunnableToSuspended(kNative); 1080 // If we're doing the image, override the compiler filter to force full compilation. Must be 1081 // done ahead of WellKnownClasses::Init that causes verification. Note: doesn't force 1082 // compilation of class initializers. 1083 // Whilst we're in native take the opportunity to initialize well known classes. 1084 WellKnownClasses::Init(self->GetJniEnv()); 1085 1086 // If --image-classes was specified, calculate the full list of classes to include in the image 1087 if (image_classes_filename_ != nullptr) { 1088 std::string error_msg; 1089 if (image_classes_zip_filename_ != nullptr) { 1090 image_classes_.reset(ReadImageClassesFromZip(image_classes_zip_filename_, 1091 image_classes_filename_, 1092 &error_msg)); 1093 } else { 1094 image_classes_.reset(ReadImageClassesFromFile(image_classes_filename_)); 1095 } 1096 if (image_classes_.get() == nullptr) { 1097 LOG(ERROR) << "Failed to create list of image classes from '" << image_classes_filename_ << 1098 "': " << error_msg; 1099 return false; 1100 } 1101 } else if (image_) { 1102 image_classes_.reset(new std::unordered_set<std::string>); 1103 } 1104 // If --compiled-classes was specified, calculate the full list of classes to compile in the 1105 // image. 1106 if (compiled_classes_filename_ != nullptr) { 1107 std::string error_msg; 1108 if (compiled_classes_zip_filename_ != nullptr) { 1109 compiled_classes_.reset(ReadImageClassesFromZip(compiled_classes_zip_filename_, 1110 compiled_classes_filename_, 1111 &error_msg)); 1112 } else { 1113 compiled_classes_.reset(ReadImageClassesFromFile(compiled_classes_filename_)); 1114 } 1115 if (compiled_classes_.get() == nullptr) { 1116 LOG(ERROR) << "Failed to create list of compiled classes from '" 1117 << compiled_classes_filename_ << "': " << error_msg; 1118 return false; 1119 } 1120 } else { 1121 compiled_classes_.reset(nullptr); // By default compile everything. 1122 } 1123 // If --compiled-methods was specified, read the methods to compile from the given file(s). 1124 if (compiled_methods_filename_ != nullptr) { 1125 std::string error_msg; 1126 if (compiled_methods_zip_filename_ != nullptr) { 1127 compiled_methods_.reset(ReadCommentedInputFromZip(compiled_methods_zip_filename_, 1128 compiled_methods_filename_, 1129 nullptr, // No post-processing. 1130 &error_msg)); 1131 } else { 1132 compiled_methods_.reset(ReadCommentedInputFromFile(compiled_methods_filename_, 1133 nullptr)); // No post-processing. 1134 } 1135 if (compiled_methods_.get() == nullptr) { 1136 LOG(ERROR) << "Failed to create list of compiled methods from '" 1137 << compiled_methods_filename_ << "': " << error_msg; 1138 return false; 1139 } 1140 } else { 1141 compiled_methods_.reset(nullptr); // By default compile everything. 1142 } 1143 1144 if (boot_image_option_.empty()) { 1145 dex_files_ = Runtime::Current()->GetClassLinker()->GetBootClassPath(); 1146 } else { 1147 if (dex_filenames_.empty()) { 1148 ATRACE_BEGIN("Opening zip archive from file descriptor"); 1149 std::string error_msg; 1150 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(zip_fd_, 1151 zip_location_.c_str(), 1152 &error_msg)); 1153 if (zip_archive.get() == nullptr) { 1154 LOG(ERROR) << "Failed to open zip from file descriptor for '" << zip_location_ << "': " 1155 << error_msg; 1156 return false; 1157 } 1158 if (!DexFile::OpenFromZip(*zip_archive.get(), zip_location_, &error_msg, &opened_dex_files_)) { 1159 LOG(ERROR) << "Failed to open dex from file descriptor for zip file '" << zip_location_ 1160 << "': " << error_msg; 1161 return false; 1162 } 1163 for (auto& dex_file : opened_dex_files_) { 1164 dex_files_.push_back(dex_file.get()); 1165 } 1166 ATRACE_END(); 1167 } else { 1168 size_t failure_count = OpenDexFiles(dex_filenames_, dex_locations_, &opened_dex_files_); 1169 if (failure_count > 0) { 1170 LOG(ERROR) << "Failed to open some dex files: " << failure_count; 1171 return false; 1172 } 1173 for (auto& dex_file : opened_dex_files_) { 1174 dex_files_.push_back(dex_file.get()); 1175 } 1176 } 1177 1178 constexpr bool kSaveDexInput = false; 1179 if (kSaveDexInput) { 1180 for (size_t i = 0; i < dex_files_.size(); ++i) { 1181 const DexFile* dex_file = dex_files_[i]; 1182 std::string tmp_file_name(StringPrintf("/data/local/tmp/dex2oat.%d.%zd.dex", 1183 getpid(), i)); 1184 std::unique_ptr<File> tmp_file(OS::CreateEmptyFile(tmp_file_name.c_str())); 1185 if (tmp_file.get() == nullptr) { 1186 PLOG(ERROR) << "Failed to open file " << tmp_file_name 1187 << ". Try: adb shell chmod 777 /data/local/tmp"; 1188 continue; 1189 } 1190 // This is just dumping files for debugging. Ignore errors, and leave remnants. 1191 UNUSED(tmp_file->WriteFully(dex_file->Begin(), dex_file->Size())); 1192 UNUSED(tmp_file->Flush()); 1193 UNUSED(tmp_file->Close()); 1194 LOG(INFO) << "Wrote input to " << tmp_file_name; 1195 } 1196 } 1197 } 1198 // Ensure opened dex files are writable for dex-to-dex transformations. 1199 for (const auto& dex_file : dex_files_) { 1200 if (!dex_file->EnableWrite()) { 1201 PLOG(ERROR) << "Failed to make .dex file writeable '" << dex_file->GetLocation() << "'\n"; 1202 } 1203 } 1204 1205 // If we use a swap file, ensure we are above the threshold to make it necessary. 1206 if (swap_fd_ != -1) { 1207 if (!UseSwap(image_, dex_files_)) { 1208 close(swap_fd_); 1209 swap_fd_ = -1; 1210 VLOG(compiler) << "Decided to run without swap."; 1211 } else { 1212 LOG(INFO) << "Large app, accepted running with swap."; 1213 } 1214 } 1215 // Note that dex2oat won't close the swap_fd_. The compiler driver's swap space will do that. 1216 1217 /* 1218 * If we're not in interpret-only or verify-none mode, go ahead and compile small applications. 1219 * Don't bother to check if we're doing the image. 1220 */ 1221 if (!image_ && 1222 compiler_options_->IsCompilationEnabled() && 1223 compiler_kind_ == Compiler::kQuick) { 1224 size_t num_methods = 0; 1225 for (size_t i = 0; i != dex_files_.size(); ++i) { 1226 const DexFile* dex_file = dex_files_[i]; 1227 CHECK(dex_file != nullptr); 1228 num_methods += dex_file->NumMethodIds(); 1229 } 1230 if (num_methods <= compiler_options_->GetNumDexMethodsThreshold()) { 1231 compiler_options_->SetCompilerFilter(CompilerOptions::kSpeed); 1232 VLOG(compiler) << "Below method threshold, compiling anyways"; 1233 } 1234 } 1235 1236 return true; 1237 } 1238 1239 // Create and invoke the compiler driver. This will compile all the dex files. 1240 void Compile() { 1241 TimingLogger::ScopedTiming t("dex2oat Compile", timings_); 1242 compiler_phases_timings_.reset(new CumulativeLogger("compilation times")); 1243 1244 // Handle and ClassLoader creation needs to come after Runtime::Create 1245 jobject class_loader = nullptr; 1246 Thread* self = Thread::Current(); 1247 if (!boot_image_option_.empty()) { 1248 ClassLinker* class_linker = Runtime::Current()->GetClassLinker(); 1249 OpenClassPathFiles(runtime_->GetClassPathString(), dex_files_, &class_path_files_); 1250 ScopedObjectAccess soa(self); 1251 1252 // Classpath: first the class-path given. 1253 std::vector<const DexFile*> class_path_files; 1254 for (auto& class_path_file : class_path_files_) { 1255 class_path_files.push_back(class_path_file.get()); 1256 } 1257 1258 // Store the classpath we have right now. 1259 key_value_store_->Put(OatHeader::kClassPathKey, 1260 OatFile::EncodeDexFileDependencies(class_path_files)); 1261 1262 // Then the dex files we'll compile. Thus we'll resolve the class-path first. 1263 class_path_files.insert(class_path_files.end(), dex_files_.begin(), dex_files_.end()); 1264 1265 class_loader = class_linker->CreatePathClassLoader(self, class_path_files); 1266 } 1267 1268 driver_.reset(new CompilerDriver(compiler_options_.get(), 1269 verification_results_.get(), 1270 &method_inliner_map_, 1271 compiler_kind_, 1272 instruction_set_, 1273 instruction_set_features_.get(), 1274 image_, 1275 image_classes_.release(), 1276 compiled_classes_.release(), 1277 nullptr, 1278 thread_count_, 1279 dump_stats_, 1280 dump_passes_, 1281 dump_cfg_file_name_, 1282 compiler_phases_timings_.get(), 1283 swap_fd_, 1284 profile_file_)); 1285 1286 driver_->CompileAll(class_loader, dex_files_, timings_); 1287 } 1288 1289 // Notes on the interleaving of creating the image and oat file to 1290 // ensure the references between the two are correct. 1291 // 1292 // Currently we have a memory layout that looks something like this: 1293 // 1294 // +--------------+ 1295 // | image | 1296 // +--------------+ 1297 // | boot oat | 1298 // +--------------+ 1299 // | alloc spaces | 1300 // +--------------+ 1301 // 1302 // There are several constraints on the loading of the image and boot.oat. 1303 // 1304 // 1. The image is expected to be loaded at an absolute address and 1305 // contains Objects with absolute pointers within the image. 1306 // 1307 // 2. There are absolute pointers from Methods in the image to their 1308 // code in the oat. 1309 // 1310 // 3. There are absolute pointers from the code in the oat to Methods 1311 // in the image. 1312 // 1313 // 4. There are absolute pointers from code in the oat to other code 1314 // in the oat. 1315 // 1316 // To get this all correct, we go through several steps. 1317 // 1318 // 1. We prepare offsets for all data in the oat file and calculate 1319 // the oat data size and code size. During this stage, we also set 1320 // oat code offsets in methods for use by the image writer. 1321 // 1322 // 2. We prepare offsets for the objects in the image and calculate 1323 // the image size. 1324 // 1325 // 3. We create the oat file. Originally this was just our own proprietary 1326 // file but now it is contained within an ELF dynamic object (aka an .so 1327 // file). Since we know the image size and oat data size and code size we 1328 // can prepare the ELF headers and we then know the ELF memory segment 1329 // layout and we can now resolve all references. The compiler provides 1330 // LinkerPatch information in each CompiledMethod and we resolve these, 1331 // using the layout information and image object locations provided by 1332 // image writer, as we're writing the method code. 1333 // 1334 // 4. We create the image file. It needs to know where the oat file 1335 // will be loaded after itself. Originally when oat file was simply 1336 // memory mapped so we could predict where its contents were based 1337 // on the file size. Now that it is an ELF file, we need to inspect 1338 // the ELF file to understand the in memory segment layout including 1339 // where the oat header is located within. 1340 // TODO: We could just remember this information from step 3. 1341 // 1342 // 5. We fixup the ELF program headers so that dlopen will try to 1343 // load the .so at the desired location at runtime by offsetting the 1344 // Elf32_Phdr.p_vaddr values by the desired base address. 1345 // TODO: Do this in step 3. We already know the layout there. 1346 // 1347 // Steps 1.-3. are done by the CreateOatFile() above, steps 4.-5. 1348 // are done by the CreateImageFile() below. 1349 1350 1351 // Write out the generated code part. Calls the OatWriter and ElfBuilder. Also prepares the 1352 // ImageWriter, if necessary. 1353 // Note: Flushing (and closing) the file is the caller's responsibility, except for the failure 1354 // case (when the file will be explicitly erased). 1355 bool CreateOatFile() { 1356 CHECK(key_value_store_.get() != nullptr); 1357 1358 TimingLogger::ScopedTiming t("dex2oat Oat", timings_); 1359 1360 std::unique_ptr<OatWriter> oat_writer; 1361 { 1362 TimingLogger::ScopedTiming t2("dex2oat OatWriter", timings_); 1363 std::string image_file_location; 1364 uint32_t image_file_location_oat_checksum = 0; 1365 uintptr_t image_file_location_oat_data_begin = 0; 1366 int32_t image_patch_delta = 0; 1367 if (image_) { 1368 PrepareImageWriter(image_base_); 1369 } else { 1370 TimingLogger::ScopedTiming t3("Loading image checksum", timings_); 1371 gc::space::ImageSpace* image_space = Runtime::Current()->GetHeap()->GetImageSpace(); 1372 image_file_location_oat_checksum = image_space->GetImageHeader().GetOatChecksum(); 1373 image_file_location_oat_data_begin = 1374 reinterpret_cast<uintptr_t>(image_space->GetImageHeader().GetOatDataBegin()); 1375 image_file_location = image_space->GetImageFilename(); 1376 image_patch_delta = image_space->GetImageHeader().GetPatchDelta(); 1377 } 1378 1379 if (!image_file_location.empty()) { 1380 key_value_store_->Put(OatHeader::kImageLocationKey, image_file_location); 1381 } 1382 1383 oat_writer.reset(new OatWriter(dex_files_, image_file_location_oat_checksum, 1384 image_file_location_oat_data_begin, 1385 image_patch_delta, 1386 driver_.get(), 1387 image_writer_.get(), 1388 timings_, 1389 key_value_store_.get())); 1390 } 1391 1392 if (image_) { 1393 // The OatWriter constructor has already updated offsets in methods and we need to 1394 // prepare method offsets in the image address space for direct method patching. 1395 TimingLogger::ScopedTiming t2("dex2oat Prepare image address space", timings_); 1396 if (!image_writer_->PrepareImageAddressSpace()) { 1397 LOG(ERROR) << "Failed to prepare image address space."; 1398 return false; 1399 } 1400 } 1401 1402 { 1403 TimingLogger::ScopedTiming t2("dex2oat Write ELF", timings_); 1404 if (!driver_->WriteElf(android_root_, is_host_, dex_files_, oat_writer.get(), 1405 oat_file_.get())) { 1406 LOG(ERROR) << "Failed to write ELF file " << oat_file_->GetPath(); 1407 return false; 1408 } 1409 } 1410 1411 VLOG(compiler) << "Oat file written successfully (unstripped): " << oat_location_; 1412 return true; 1413 } 1414 1415 // If we are compiling an image, invoke the image creation routine. Else just skip. 1416 bool HandleImage() { 1417 if (image_) { 1418 TimingLogger::ScopedTiming t("dex2oat ImageWriter", timings_); 1419 if (!CreateImageFile()) { 1420 return false; 1421 } 1422 VLOG(compiler) << "Image written successfully: " << image_filename_; 1423 } 1424 return true; 1425 } 1426 1427 // Create a copy from unstripped to stripped. 1428 bool CopyUnstrippedToStripped() { 1429 // If we don't want to strip in place, copy from unstripped location to stripped location. 1430 // We need to strip after image creation because FixupElf needs to use .strtab. 1431 if (oat_unstripped_ != oat_stripped_) { 1432 // If the oat file is still open, flush it. 1433 if (oat_file_.get() != nullptr && oat_file_->IsOpened()) { 1434 if (!FlushCloseOatFile()) { 1435 return false; 1436 } 1437 } 1438 1439 TimingLogger::ScopedTiming t("dex2oat OatFile copy", timings_); 1440 std::unique_ptr<File> in(OS::OpenFileForReading(oat_unstripped_.c_str())); 1441 std::unique_ptr<File> out(OS::CreateEmptyFile(oat_stripped_.c_str())); 1442 size_t buffer_size = 8192; 1443 std::unique_ptr<uint8_t[]> buffer(new uint8_t[buffer_size]); 1444 while (true) { 1445 int bytes_read = TEMP_FAILURE_RETRY(read(in->Fd(), buffer.get(), buffer_size)); 1446 if (bytes_read <= 0) { 1447 break; 1448 } 1449 bool write_ok = out->WriteFully(buffer.get(), bytes_read); 1450 CHECK(write_ok); 1451 } 1452 if (out->FlushCloseOrErase() != 0) { 1453 PLOG(ERROR) << "Failed to flush and close copied oat file: " << oat_stripped_; 1454 return false; 1455 } 1456 VLOG(compiler) << "Oat file copied successfully (stripped): " << oat_stripped_; 1457 } 1458 return true; 1459 } 1460 1461 bool FlushOatFile() { 1462 if (oat_file_.get() != nullptr) { 1463 TimingLogger::ScopedTiming t2("dex2oat Flush ELF", timings_); 1464 if (oat_file_->Flush() != 0) { 1465 PLOG(ERROR) << "Failed to flush oat file: " << oat_location_ << " / " 1466 << oat_filename_; 1467 oat_file_->Erase(); 1468 return false; 1469 } 1470 } 1471 return true; 1472 } 1473 1474 bool FlushCloseOatFile() { 1475 if (oat_file_.get() != nullptr) { 1476 std::unique_ptr<File> tmp(oat_file_.release()); 1477 if (tmp->FlushCloseOrErase() != 0) { 1478 PLOG(ERROR) << "Failed to flush and close oat file: " << oat_location_ << " / " 1479 << oat_filename_; 1480 return false; 1481 } 1482 } 1483 return true; 1484 } 1485 1486 void DumpTiming() { 1487 if (dump_timing_ || (dump_slow_timing_ && timings_->GetTotalNs() > MsToNs(1000))) { 1488 LOG(INFO) << Dumpable<TimingLogger>(*timings_); 1489 } 1490 if (dump_passes_) { 1491 LOG(INFO) << Dumpable<CumulativeLogger>(*driver_->GetTimingsLogger()); 1492 } 1493 } 1494 1495 CompilerOptions* GetCompilerOptions() const { 1496 return compiler_options_.get(); 1497 } 1498 1499 bool IsImage() const { 1500 return image_; 1501 } 1502 1503 bool IsHost() const { 1504 return is_host_; 1505 } 1506 1507 private: 1508 static size_t OpenDexFiles(const std::vector<const char*>& dex_filenames, 1509 const std::vector<const char*>& dex_locations, 1510 std::vector<std::unique_ptr<const DexFile>>* dex_files) { 1511 DCHECK(dex_files != nullptr) << "OpenDexFiles out-param is nullptr"; 1512 size_t failure_count = 0; 1513 for (size_t i = 0; i < dex_filenames.size(); i++) { 1514 const char* dex_filename = dex_filenames[i]; 1515 const char* dex_location = dex_locations[i]; 1516 ATRACE_BEGIN(StringPrintf("Opening dex file '%s'", dex_filenames[i]).c_str()); 1517 std::string error_msg; 1518 if (!OS::FileExists(dex_filename)) { 1519 LOG(WARNING) << "Skipping non-existent dex file '" << dex_filename << "'"; 1520 continue; 1521 } 1522 if (!DexFile::Open(dex_filename, dex_location, &error_msg, dex_files)) { 1523 LOG(WARNING) << "Failed to open .dex from file '" << dex_filename << "': " << error_msg; 1524 ++failure_count; 1525 } 1526 ATRACE_END(); 1527 } 1528 return failure_count; 1529 } 1530 1531 // Returns true if dex_files has a dex with the named location. We compare canonical locations, 1532 // so that relative and absolute paths will match. Not caching for the dex_files isn't very 1533 // efficient, but under normal circumstances the list is neither large nor is this part too 1534 // sensitive. 1535 static bool DexFilesContains(const std::vector<const DexFile*>& dex_files, 1536 const std::string& location) { 1537 std::string canonical_location(DexFile::GetDexCanonicalLocation(location.c_str())); 1538 for (size_t i = 0; i < dex_files.size(); ++i) { 1539 if (DexFile::GetDexCanonicalLocation(dex_files[i]->GetLocation().c_str()) == 1540 canonical_location) { 1541 return true; 1542 } 1543 } 1544 return false; 1545 } 1546 1547 // Appends to opened_dex_files any elements of class_path that dex_files 1548 // doesn't already contain. This will open those dex files as necessary. 1549 static void OpenClassPathFiles(const std::string& class_path, 1550 std::vector<const DexFile*> dex_files, 1551 std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) { 1552 DCHECK(opened_dex_files != nullptr) << "OpenClassPathFiles out-param is nullptr"; 1553 std::vector<std::string> parsed; 1554 Split(class_path, ':', &parsed); 1555 // Take Locks::mutator_lock_ so that lock ordering on the ClassLinker::dex_lock_ is maintained. 1556 ScopedObjectAccess soa(Thread::Current()); 1557 for (size_t i = 0; i < parsed.size(); ++i) { 1558 if (DexFilesContains(dex_files, parsed[i])) { 1559 continue; 1560 } 1561 std::string error_msg; 1562 if (!DexFile::Open(parsed[i].c_str(), parsed[i].c_str(), &error_msg, opened_dex_files)) { 1563 LOG(WARNING) << "Failed to open dex file '" << parsed[i] << "': " << error_msg; 1564 } 1565 } 1566 } 1567 1568 // Create a runtime necessary for compilation. 1569 bool CreateRuntime(const RuntimeOptions& runtime_options) 1570 SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_) { 1571 if (!Runtime::Create(runtime_options, false)) { 1572 LOG(ERROR) << "Failed to create runtime"; 1573 return false; 1574 } 1575 Runtime* runtime = Runtime::Current(); 1576 runtime->SetInstructionSet(instruction_set_); 1577 for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) { 1578 Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i); 1579 if (!runtime->HasCalleeSaveMethod(type)) { 1580 runtime->SetCalleeSaveMethod(runtime->CreateCalleeSaveMethod(), type); 1581 } 1582 } 1583 runtime->GetClassLinker()->FixupDexCaches(runtime->GetResolutionMethod()); 1584 1585 // Initialize maps for unstarted runtime. This needs to be here, as running clinits needs this 1586 // set up. 1587 interpreter::UnstartedRuntime::Initialize(); 1588 1589 runtime->GetClassLinker()->RunRootClinits(); 1590 runtime_ = runtime; 1591 1592 return true; 1593 } 1594 1595 void PrepareImageWriter(uintptr_t image_base) { 1596 image_writer_.reset(new ImageWriter(*driver_, image_base, compiler_options_->GetCompilePic())); 1597 } 1598 1599 // Let the ImageWriter write the image file. If we do not compile PIC, also fix up the oat file. 1600 bool CreateImageFile() 1601 LOCKS_EXCLUDED(Locks::mutator_lock_) { 1602 CHECK(image_writer_ != nullptr); 1603 if (!image_writer_->Write(image_filename_, oat_unstripped_, oat_location_)) { 1604 LOG(ERROR) << "Failed to create image file " << image_filename_; 1605 return false; 1606 } 1607 uintptr_t oat_data_begin = image_writer_->GetOatDataBegin(); 1608 1609 // Destroy ImageWriter before doing FixupElf. 1610 image_writer_.reset(); 1611 1612 // Do not fix up the ELF file if we are --compile-pic 1613 if (!compiler_options_->GetCompilePic()) { 1614 std::unique_ptr<File> oat_file(OS::OpenFileReadWrite(oat_unstripped_.c_str())); 1615 if (oat_file.get() == nullptr) { 1616 PLOG(ERROR) << "Failed to open ELF file: " << oat_unstripped_; 1617 return false; 1618 } 1619 1620 if (!ElfWriter::Fixup(oat_file.get(), oat_data_begin)) { 1621 oat_file->Erase(); 1622 LOG(ERROR) << "Failed to fixup ELF file " << oat_file->GetPath(); 1623 return false; 1624 } 1625 1626 if (oat_file->FlushCloseOrErase()) { 1627 PLOG(ERROR) << "Failed to flush and close fixed ELF file " << oat_file->GetPath(); 1628 return false; 1629 } 1630 } 1631 1632 return true; 1633 } 1634 1635 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;) 1636 static std::unordered_set<std::string>* ReadImageClassesFromFile( 1637 const char* image_classes_filename) { 1638 std::function<std::string(const char*)> process = DotToDescriptor; 1639 return ReadCommentedInputFromFile(image_classes_filename, &process); 1640 } 1641 1642 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;) 1643 static std::unordered_set<std::string>* ReadImageClassesFromZip( 1644 const char* zip_filename, 1645 const char* image_classes_filename, 1646 std::string* error_msg) { 1647 std::function<std::string(const char*)> process = DotToDescriptor; 1648 return ReadCommentedInputFromZip(zip_filename, image_classes_filename, &process, error_msg); 1649 } 1650 1651 // Read lines from the given file, dropping comments and empty lines. Post-process each line with 1652 // the given function. 1653 static std::unordered_set<std::string>* ReadCommentedInputFromFile( 1654 const char* input_filename, std::function<std::string(const char*)>* process) { 1655 std::unique_ptr<std::ifstream> input_file(new std::ifstream(input_filename, std::ifstream::in)); 1656 if (input_file.get() == nullptr) { 1657 LOG(ERROR) << "Failed to open input file " << input_filename; 1658 return nullptr; 1659 } 1660 std::unique_ptr<std::unordered_set<std::string>> result( 1661 ReadCommentedInputStream(*input_file, process)); 1662 input_file->close(); 1663 return result.release(); 1664 } 1665 1666 // Read lines from the given file from the given zip file, dropping comments and empty lines. 1667 // Post-process each line with the given function. 1668 static std::unordered_set<std::string>* ReadCommentedInputFromZip( 1669 const char* zip_filename, 1670 const char* input_filename, 1671 std::function<std::string(const char*)>* process, 1672 std::string* error_msg) { 1673 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::Open(zip_filename, error_msg)); 1674 if (zip_archive.get() == nullptr) { 1675 return nullptr; 1676 } 1677 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(input_filename, error_msg)); 1678 if (zip_entry.get() == nullptr) { 1679 *error_msg = StringPrintf("Failed to find '%s' within '%s': %s", input_filename, 1680 zip_filename, error_msg->c_str()); 1681 return nullptr; 1682 } 1683 std::unique_ptr<MemMap> input_file(zip_entry->ExtractToMemMap(zip_filename, 1684 input_filename, 1685 error_msg)); 1686 if (input_file.get() == nullptr) { 1687 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", input_filename, 1688 zip_filename, error_msg->c_str()); 1689 return nullptr; 1690 } 1691 const std::string input_string(reinterpret_cast<char*>(input_file->Begin()), 1692 input_file->Size()); 1693 std::istringstream input_stream(input_string); 1694 return ReadCommentedInputStream(input_stream, process); 1695 } 1696 1697 // Read lines from the given stream, dropping comments and empty lines. Post-process each line 1698 // with the given function. 1699 static std::unordered_set<std::string>* ReadCommentedInputStream( 1700 std::istream& in_stream, 1701 std::function<std::string(const char*)>* process) { 1702 std::unique_ptr<std::unordered_set<std::string>> image_classes( 1703 new std::unordered_set<std::string>); 1704 while (in_stream.good()) { 1705 std::string dot; 1706 std::getline(in_stream, dot); 1707 if (StartsWith(dot, "#") || dot.empty()) { 1708 continue; 1709 } 1710 if (process != nullptr) { 1711 std::string descriptor((*process)(dot.c_str())); 1712 image_classes->insert(descriptor); 1713 } else { 1714 image_classes->insert(dot); 1715 } 1716 } 1717 return image_classes.release(); 1718 } 1719 1720 void LogCompletionTime() { 1721 // Note: when creation of a runtime fails, e.g., when trying to compile an app but when there 1722 // is no image, there won't be a Runtime::Current(). 1723 // Note: driver creation can fail when loading an invalid dex file. 1724 LOG(INFO) << "dex2oat took " << PrettyDuration(NanoTime() - start_ns_) 1725 << " (threads: " << thread_count_ << ") " 1726 << ((Runtime::Current() != nullptr && driver_.get() != nullptr) ? 1727 driver_->GetMemoryUsageString(kIsDebugBuild || VLOG_IS_ON(compiler)) : 1728 ""); 1729 } 1730 1731 std::unique_ptr<CompilerOptions> compiler_options_; 1732 Compiler::Kind compiler_kind_; 1733 1734 InstructionSet instruction_set_; 1735 std::unique_ptr<const InstructionSetFeatures> instruction_set_features_; 1736 1737 std::unique_ptr<SafeMap<std::string, std::string> > key_value_store_; 1738 1739 std::unique_ptr<VerificationResults> verification_results_; 1740 DexFileToMethodInlinerMap method_inliner_map_; 1741 std::unique_ptr<QuickCompilerCallbacks> callbacks_; 1742 1743 // Ownership for the class path files. 1744 std::vector<std::unique_ptr<const DexFile>> class_path_files_; 1745 1746 // Not a unique_ptr as we want to just exit on non-debug builds, not bringing the runtime down 1747 // in an orderly fashion. The destructor takes care of deleting this. 1748 Runtime* runtime_; 1749 1750 size_t thread_count_; 1751 uint64_t start_ns_; 1752 std::unique_ptr<WatchDog> watchdog_; 1753 std::unique_ptr<File> oat_file_; 1754 std::string oat_stripped_; 1755 std::string oat_unstripped_; 1756 std::string oat_location_; 1757 std::string oat_filename_; 1758 int oat_fd_; 1759 std::vector<const char*> dex_filenames_; 1760 std::vector<const char*> dex_locations_; 1761 int zip_fd_; 1762 std::string zip_location_; 1763 std::string boot_image_option_; 1764 std::vector<const char*> runtime_args_; 1765 std::string image_filename_; 1766 uintptr_t image_base_; 1767 const char* image_classes_zip_filename_; 1768 const char* image_classes_filename_; 1769 const char* compiled_classes_zip_filename_; 1770 const char* compiled_classes_filename_; 1771 const char* compiled_methods_zip_filename_; 1772 const char* compiled_methods_filename_; 1773 std::unique_ptr<std::unordered_set<std::string>> image_classes_; 1774 std::unique_ptr<std::unordered_set<std::string>> compiled_classes_; 1775 std::unique_ptr<std::unordered_set<std::string>> compiled_methods_; 1776 bool image_; 1777 std::unique_ptr<ImageWriter> image_writer_; 1778 bool is_host_; 1779 std::string android_root_; 1780 std::vector<const DexFile*> dex_files_; 1781 std::vector<std::unique_ptr<const DexFile>> opened_dex_files_; 1782 std::unique_ptr<CompilerDriver> driver_; 1783 std::vector<std::string> verbose_methods_; 1784 bool dump_stats_; 1785 bool dump_passes_; 1786 bool dump_timing_; 1787 bool dump_slow_timing_; 1788 std::string dump_cfg_file_name_; 1789 std::string swap_file_name_; 1790 int swap_fd_; 1791 std::string profile_file_; // Profile file to use 1792 TimingLogger* timings_; 1793 std::unique_ptr<CumulativeLogger> compiler_phases_timings_; 1794 std::unique_ptr<std::ostream> init_failure_output_; 1795 1796 DISALLOW_IMPLICIT_CONSTRUCTORS(Dex2Oat); 1797}; 1798 1799static void b13564922() { 1800#if defined(__linux__) && defined(__arm__) 1801 int major, minor; 1802 struct utsname uts; 1803 if (uname(&uts) != -1 && 1804 sscanf(uts.release, "%d.%d", &major, &minor) == 2 && 1805 ((major < 3) || ((major == 3) && (minor < 4)))) { 1806 // Kernels before 3.4 don't handle the ASLR well and we can run out of address 1807 // space (http://b/13564922). Work around the issue by inhibiting further mmap() randomization. 1808 int old_personality = personality(0xffffffff); 1809 if ((old_personality & ADDR_NO_RANDOMIZE) == 0) { 1810 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE); 1811 if (new_personality == -1) { 1812 LOG(WARNING) << "personality(. | ADDR_NO_RANDOMIZE) failed."; 1813 } 1814 } 1815 } 1816#endif 1817} 1818 1819static int CompileImage(Dex2Oat& dex2oat) { 1820 dex2oat.Compile(); 1821 1822 // Create the boot.oat. 1823 if (!dex2oat.CreateOatFile()) { 1824 dex2oat.EraseOatFile(); 1825 return EXIT_FAILURE; 1826 } 1827 1828 // Flush and close the boot.oat. We always expect the output file by name, and it will be 1829 // re-opened from the unstripped name. 1830 if (!dex2oat.FlushCloseOatFile()) { 1831 return EXIT_FAILURE; 1832 } 1833 1834 // Creates the boot.art and patches the boot.oat. 1835 if (!dex2oat.HandleImage()) { 1836 return EXIT_FAILURE; 1837 } 1838 1839 // When given --host, finish early without stripping. 1840 if (dex2oat.IsHost()) { 1841 dex2oat.DumpTiming(); 1842 return EXIT_SUCCESS; 1843 } 1844 1845 // Copy unstripped to stripped location, if necessary. 1846 if (!dex2oat.CopyUnstrippedToStripped()) { 1847 return EXIT_FAILURE; 1848 } 1849 1850 // FlushClose again, as stripping might have re-opened the oat file. 1851 if (!dex2oat.FlushCloseOatFile()) { 1852 return EXIT_FAILURE; 1853 } 1854 1855 dex2oat.DumpTiming(); 1856 return EXIT_SUCCESS; 1857} 1858 1859static int CompileApp(Dex2Oat& dex2oat) { 1860 dex2oat.Compile(); 1861 1862 // Create the app oat. 1863 if (!dex2oat.CreateOatFile()) { 1864 dex2oat.EraseOatFile(); 1865 return EXIT_FAILURE; 1866 } 1867 1868 // Do not close the oat file here. We might haven gotten the output file by file descriptor, 1869 // which we would lose. 1870 if (!dex2oat.FlushOatFile()) { 1871 return EXIT_FAILURE; 1872 } 1873 1874 // When given --host, finish early without stripping. 1875 if (dex2oat.IsHost()) { 1876 if (!dex2oat.FlushCloseOatFile()) { 1877 return EXIT_FAILURE; 1878 } 1879 1880 dex2oat.DumpTiming(); 1881 return EXIT_SUCCESS; 1882 } 1883 1884 // Copy unstripped to stripped location, if necessary. This will implicitly flush & close the 1885 // unstripped version. If this is given, we expect to be able to open writable files by name. 1886 if (!dex2oat.CopyUnstrippedToStripped()) { 1887 return EXIT_FAILURE; 1888 } 1889 1890 // Flush and close the file. 1891 if (!dex2oat.FlushCloseOatFile()) { 1892 return EXIT_FAILURE; 1893 } 1894 1895 dex2oat.DumpTiming(); 1896 return EXIT_SUCCESS; 1897} 1898 1899static int dex2oat(int argc, char** argv) { 1900 b13564922(); 1901 1902 TimingLogger timings("compiler", false, false); 1903 1904 Dex2Oat dex2oat(&timings); 1905 1906 // Parse arguments. Argument mistakes will lead to exit(EXIT_FAILURE) in UsageError. 1907 dex2oat.ParseArgs(argc, argv); 1908 1909 // Check early that the result of compilation can be written 1910 if (!dex2oat.OpenFile()) { 1911 return EXIT_FAILURE; 1912 } 1913 1914 LOG(INFO) << CommandLine(); 1915 1916 if (!dex2oat.Setup()) { 1917 dex2oat.EraseOatFile(); 1918 return EXIT_FAILURE; 1919 } 1920 1921 if (dex2oat.IsImage()) { 1922 return CompileImage(dex2oat); 1923 } else { 1924 return CompileApp(dex2oat); 1925 } 1926} 1927} // namespace art 1928 1929int main(int argc, char** argv) { 1930 int result = art::dex2oat(argc, argv); 1931 // Everything was done, do an explicit exit here to avoid running Runtime destructors that take 1932 // time (bug 10645725) unless we're a debug build or running on valgrind. Note: The Dex2Oat class 1933 // should not destruct the runtime in this case. 1934 if (!art::kIsDebugBuild && (RUNNING_ON_VALGRIND == 0)) { 1935 exit(result); 1936 } 1937 return result; 1938} 1939