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