dex2oat.cc revision 25a9abe3cd9594a60d353c0277b4f9e49a71a40a
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 "base/memory_tool.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#include "arch/instruction_set_features.h" 36#include "arch/mips/instruction_set_features_mips.h" 37#include "art_method-inl.h" 38#include "base/dumpable.h" 39#include "base/macros.h" 40#include "base/scoped_flock.h" 41#include "base/stl_util.h" 42#include "base/stringpiece.h" 43#include "base/time_utils.h" 44#include "base/timing_logger.h" 45#include "base/unix_file/fd_file.h" 46#include "class_linker.h" 47#include "compiler.h" 48#include "compiler_callbacks.h" 49#include "debug/elf_debug_writer.h" 50#include "debug/method_debug_info.h" 51#include "dex/quick/dex_file_to_method_inliner_map.h" 52#include "dex/quick_compiler_callbacks.h" 53#include "dex/verification_results.h" 54#include "dex_file-inl.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 "elf_writer_quick.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 "jit/offline_profiling_info.h" 65#include "leb128.h" 66#include "linker/multi_oat_relative_patcher.h" 67#include "mirror/class-inl.h" 68#include "mirror/class_loader.h" 69#include "mirror/object-inl.h" 70#include "mirror/object_array-inl.h" 71#include "oat_file_assistant.h" 72#include "oat_writer.h" 73#include "os.h" 74#include "runtime.h" 75#include "runtime_options.h" 76#include "ScopedLocalRef.h" 77#include "scoped_thread_state_change.h" 78#include "utils.h" 79#include "well_known_classes.h" 80#include "zip_archive.h" 81 82namespace art { 83 84static constexpr size_t kDefaultMinDexFilesForSwap = 2; 85static constexpr size_t kDefaultMinDexFileCumulativeSizeForSwap = 20 * MB; 86 87static int original_argc; 88static char** original_argv; 89 90static std::string CommandLine() { 91 std::vector<std::string> command; 92 for (int i = 0; i < original_argc; ++i) { 93 command.push_back(original_argv[i]); 94 } 95 return Join(command, ' '); 96} 97 98// A stripped version. Remove some less essential parameters. If we see a "--zip-fd=" parameter, be 99// even more aggressive. There won't be much reasonable data here for us in that case anyways (the 100// locations are all staged). 101static std::string StrippedCommandLine() { 102 std::vector<std::string> command; 103 104 // Do a pre-pass to look for zip-fd. 105 bool saw_zip_fd = false; 106 for (int i = 0; i < original_argc; ++i) { 107 if (StartsWith(original_argv[i], "--zip-fd=")) { 108 saw_zip_fd = true; 109 break; 110 } 111 } 112 113 // Now filter out things. 114 for (int i = 0; i < original_argc; ++i) { 115 // All runtime-arg parameters are dropped. 116 if (strcmp(original_argv[i], "--runtime-arg") == 0) { 117 i++; // Drop the next part, too. 118 continue; 119 } 120 121 // Any instruction-setXXX is dropped. 122 if (StartsWith(original_argv[i], "--instruction-set")) { 123 continue; 124 } 125 126 // The boot image is dropped. 127 if (StartsWith(original_argv[i], "--boot-image=")) { 128 continue; 129 } 130 131 // The image format is dropped. 132 if (StartsWith(original_argv[i], "--image-format=")) { 133 continue; 134 } 135 136 // This should leave any dex-file and oat-file options, describing what we compiled. 137 138 // However, we prefer to drop this when we saw --zip-fd. 139 if (saw_zip_fd) { 140 // Drop anything --zip-X, --dex-X, --oat-X, --swap-X, or --app-image-X 141 if (StartsWith(original_argv[i], "--zip-") || 142 StartsWith(original_argv[i], "--dex-") || 143 StartsWith(original_argv[i], "--oat-") || 144 StartsWith(original_argv[i], "--swap-") || 145 StartsWith(original_argv[i], "--app-image-")) { 146 continue; 147 } 148 } 149 150 command.push_back(original_argv[i]); 151 } 152 153 // Construct the final output. 154 if (command.size() <= 1U) { 155 // It seems only "/system/bin/dex2oat" is left, or not even that. Use a pretty line. 156 return "Starting dex2oat."; 157 } 158 return Join(command, ' '); 159} 160 161static void UsageErrorV(const char* fmt, va_list ap) { 162 std::string error; 163 StringAppendV(&error, fmt, ap); 164 LOG(ERROR) << error; 165} 166 167static void UsageError(const char* fmt, ...) { 168 va_list ap; 169 va_start(ap, fmt); 170 UsageErrorV(fmt, ap); 171 va_end(ap); 172} 173 174NO_RETURN static void Usage(const char* fmt, ...) { 175 va_list ap; 176 va_start(ap, fmt); 177 UsageErrorV(fmt, ap); 178 va_end(ap); 179 180 UsageError("Command: %s", CommandLine().c_str()); 181 182 UsageError("Usage: dex2oat [options]..."); 183 UsageError(""); 184 UsageError(" -j<number>: specifies the number of threads used for compilation."); 185 UsageError(" Default is the number of detected hardware threads available on the"); 186 UsageError(" host system."); 187 UsageError(" Example: -j12"); 188 UsageError(""); 189 UsageError(" --dex-file=<dex-file>: specifies a .dex, .jar, or .apk file to compile."); 190 UsageError(" Example: --dex-file=/system/framework/core.jar"); 191 UsageError(""); 192 UsageError(" --dex-location=<dex-location>: specifies an alternative dex location to"); 193 UsageError(" encode in the oat file for the corresponding --dex-file argument."); 194 UsageError(" Example: --dex-file=/home/build/out/system/framework/core.jar"); 195 UsageError(" --dex-location=/system/framework/core.jar"); 196 UsageError(""); 197 UsageError(" --zip-fd=<file-descriptor>: specifies a file descriptor of a zip file"); 198 UsageError(" containing a classes.dex file to compile."); 199 UsageError(" Example: --zip-fd=5"); 200 UsageError(""); 201 UsageError(" --zip-location=<zip-location>: specifies a symbolic name for the file"); 202 UsageError(" corresponding to the file descriptor specified by --zip-fd."); 203 UsageError(" Example: --zip-location=/system/app/Calculator.apk"); 204 UsageError(""); 205 UsageError(" --oat-file=<file.oat>: specifies an oat output destination via a filename."); 206 UsageError(" Example: --oat-file=/system/framework/boot.oat"); 207 UsageError(""); 208 UsageError(" --oat-fd=<number>: specifies the oat output destination via a file descriptor."); 209 UsageError(" Example: --oat-fd=6"); 210 UsageError(""); 211 UsageError(" --oat-location=<oat-name>: specifies a symbolic name for the file corresponding"); 212 UsageError(" to the file descriptor specified by --oat-fd."); 213 UsageError(" Example: --oat-location=/data/dalvik-cache/system@app@Calculator.apk.oat"); 214 UsageError(""); 215 UsageError(" --oat-symbols=<file.oat>: specifies an oat output destination with full symbols."); 216 UsageError(" Example: --oat-symbols=/symbols/system/framework/boot.oat"); 217 UsageError(""); 218 UsageError(" --image=<file.art>: specifies an output image filename."); 219 UsageError(" Example: --image=/system/framework/boot.art"); 220 UsageError(""); 221 UsageError(" --image-format=(uncompressed|lz4|lz4hc):"); 222 UsageError(" Which format to store the image."); 223 UsageError(" Example: --image-format=lz4"); 224 UsageError(" Default: uncompressed"); 225 UsageError(""); 226 UsageError(" --image-classes=<classname-file>: specifies classes to include in an image."); 227 UsageError(" Example: --image=frameworks/base/preloaded-classes"); 228 UsageError(""); 229 UsageError(" --base=<hex-address>: specifies the base address when creating a boot image."); 230 UsageError(" Example: --base=0x50000000"); 231 UsageError(""); 232 UsageError(" --boot-image=<file.art>: provide the image file for the boot class path."); 233 UsageError(" Do not include the arch as part of the name, it is added automatically."); 234 UsageError(" Example: --boot-image=/system/framework/boot.art"); 235 UsageError(" (specifies /system/framework/<arch>/boot.art as the image file)"); 236 UsageError(" Default: $ANDROID_ROOT/system/framework/boot.art"); 237 UsageError(""); 238 UsageError(" --android-root=<path>: used to locate libraries for portable linking."); 239 UsageError(" Example: --android-root=out/host/linux-x86"); 240 UsageError(" Default: $ANDROID_ROOT"); 241 UsageError(""); 242 UsageError(" --instruction-set=(arm|arm64|mips|mips64|x86|x86_64): compile for a particular"); 243 UsageError(" instruction set."); 244 UsageError(" Example: --instruction-set=x86"); 245 UsageError(" Default: arm"); 246 UsageError(""); 247 UsageError(" --instruction-set-features=...,: Specify instruction set features"); 248 UsageError(" Example: --instruction-set-features=div"); 249 UsageError(" Default: default"); 250 UsageError(""); 251 UsageError(" --compile-pic: Force indirect use of code, methods, and classes"); 252 UsageError(" Default: disabled"); 253 UsageError(""); 254 UsageError(" --compiler-backend=(Quick|Optimizing): select compiler backend"); 255 UsageError(" set."); 256 UsageError(" Example: --compiler-backend=Optimizing"); 257 UsageError(" Default: Optimizing"); 258 UsageError(""); 259 UsageError(" --compiler-filter=" 260 "(verify-none" 261 "|verify-at-runtime" 262 "|verify-profile" 263 "|interpret-only" 264 "|time" 265 "|space-profile" 266 "|space" 267 "|balanced" 268 "|speed-profile" 269 "|speed" 270 "|everything-profile" 271 "|everything):"); 272 UsageError(" select compiler filter."); 273 UsageError(" verify-profile requires a --profile(-fd) to also be passed in."); 274 UsageError(" Example: --compiler-filter=everything"); 275 UsageError(" Default: speed"); 276 UsageError(""); 277 UsageError(" --huge-method-max=<method-instruction-count>: threshold size for a huge"); 278 UsageError(" method for compiler filter tuning."); 279 UsageError(" Example: --huge-method-max=%d", CompilerOptions::kDefaultHugeMethodThreshold); 280 UsageError(" Default: %d", CompilerOptions::kDefaultHugeMethodThreshold); 281 UsageError(""); 282 UsageError(" --large-method-max=<method-instruction-count>: threshold size for a large"); 283 UsageError(" method for compiler filter tuning."); 284 UsageError(" Example: --large-method-max=%d", CompilerOptions::kDefaultLargeMethodThreshold); 285 UsageError(" Default: %d", CompilerOptions::kDefaultLargeMethodThreshold); 286 UsageError(""); 287 UsageError(" --small-method-max=<method-instruction-count>: threshold size for a small"); 288 UsageError(" method for compiler filter tuning."); 289 UsageError(" Example: --small-method-max=%d", CompilerOptions::kDefaultSmallMethodThreshold); 290 UsageError(" Default: %d", CompilerOptions::kDefaultSmallMethodThreshold); 291 UsageError(""); 292 UsageError(" --tiny-method-max=<method-instruction-count>: threshold size for a tiny"); 293 UsageError(" method for compiler filter tuning."); 294 UsageError(" Example: --tiny-method-max=%d", CompilerOptions::kDefaultTinyMethodThreshold); 295 UsageError(" Default: %d", CompilerOptions::kDefaultTinyMethodThreshold); 296 UsageError(""); 297 UsageError(" --num-dex-methods=<method-count>: threshold size for a small dex file for"); 298 UsageError(" compiler filter tuning. If the input has fewer than this many methods"); 299 UsageError(" and the filter is not interpret-only or verify-none or verify-at-runtime, "); 300 UsageError(" overrides the filter to use speed"); 301 UsageError(" Example: --num-dex-method=%d", CompilerOptions::kDefaultNumDexMethodsThreshold); 302 UsageError(" Default: %d", CompilerOptions::kDefaultNumDexMethodsThreshold); 303 UsageError(""); 304 UsageError(" --inline-depth-limit=<depth-limit>: the depth limit of inlining for fine tuning"); 305 UsageError(" the compiler. A zero value will disable inlining. Honored only by Optimizing."); 306 UsageError(" Has priority over the --compiler-filter option. Intended for "); 307 UsageError(" development/experimental use."); 308 UsageError(" Example: --inline-depth-limit=%d", CompilerOptions::kDefaultInlineDepthLimit); 309 UsageError(" Default: %d", CompilerOptions::kDefaultInlineDepthLimit); 310 UsageError(""); 311 UsageError(" --inline-max-code-units=<code-units-count>: the maximum code units that a method"); 312 UsageError(" can have to be considered for inlining. A zero value will disable inlining."); 313 UsageError(" Honored only by Optimizing. Has priority over the --compiler-filter option."); 314 UsageError(" Intended for development/experimental use."); 315 UsageError(" Example: --inline-max-code-units=%d", 316 CompilerOptions::kDefaultInlineMaxCodeUnits); 317 UsageError(" Default: %d", CompilerOptions::kDefaultInlineMaxCodeUnits); 318 UsageError(""); 319 UsageError(" --dump-timing: display a breakdown of where time was spent"); 320 UsageError(""); 321 UsageError(" --include-patch-information: Include patching information so the generated code"); 322 UsageError(" can have its base address moved without full recompilation."); 323 UsageError(""); 324 UsageError(" --no-include-patch-information: Do not include patching information."); 325 UsageError(""); 326 UsageError(" -g"); 327 UsageError(" --generate-debug-info: Generate debug information for native debugging,"); 328 UsageError(" such as stack unwinding information, ELF symbols and DWARF sections."); 329 UsageError(" If used without --debuggable, it will be best-effort only."); 330 UsageError(" This option does not affect the generated code. (disabled by default)"); 331 UsageError(""); 332 UsageError(" --no-generate-debug-info: Do not generate debug information for native debugging."); 333 UsageError(""); 334 UsageError(" --generate-mini-debug-info: Generate minimal amount of LZMA-compressed"); 335 UsageError(" debug information necessary to print backtraces. (disabled by default)"); 336 UsageError(""); 337 UsageError(" --no-generate-mini-debug-info: Do not generate backtrace info."); 338 UsageError(""); 339 UsageError(" --debuggable: Produce code debuggable with Java debugger."); 340 UsageError(""); 341 UsageError(" --runtime-arg <argument>: used to specify various arguments for the runtime,"); 342 UsageError(" such as initial heap size, maximum heap size, and verbose output."); 343 UsageError(" Use a separate --runtime-arg switch for each argument."); 344 UsageError(" Example: --runtime-arg -Xms256m"); 345 UsageError(""); 346 UsageError(" --profile-file=<filename>: specify profiler output file to use for compilation."); 347 UsageError(""); 348 UsageError(" --profile-file-fd=<number>: same as --profile-file but accepts a file descriptor."); 349 UsageError(" Cannot be used together with --profile-file."); 350 UsageError(""); 351 UsageError(" --swap-file=<file-name>: specifies a file to use for swap."); 352 UsageError(" Example: --swap-file=/data/tmp/swap.001"); 353 UsageError(""); 354 UsageError(" --swap-fd=<file-descriptor>: specifies a file to use for swap (by descriptor)."); 355 UsageError(" Example: --swap-fd=10"); 356 UsageError(""); 357 UsageError(" --swap-dex-size-threshold=<size>: specifies the minimum total dex file size in"); 358 UsageError(" bytes to allow the use of swap."); 359 UsageError(" Example: --swap-dex-size-threshold=1000000"); 360 UsageError(" Default: %zu", kDefaultMinDexFileCumulativeSizeForSwap); 361 UsageError(""); 362 UsageError(" --swap-dex-count-threshold=<count>: specifies the minimum number of dex files to"); 363 UsageError(" allow the use of swap."); 364 UsageError(" Example: --swap-dex-count-threshold=10"); 365 UsageError(" Default: %zu", kDefaultMinDexFilesForSwap); 366 UsageError(""); 367 UsageError(" --app-image-fd=<file-descriptor>: specify output file descriptor for app image."); 368 UsageError(" Example: --app-image-fd=10"); 369 UsageError(""); 370 UsageError(" --app-image-file=<file-name>: specify a file name for app image."); 371 UsageError(" Example: --app-image-file=/data/dalvik-cache/system@app@Calculator.apk.art"); 372 UsageError(""); 373 UsageError(" --multi-image: specify that separate oat and image files be generated for each " 374 "input dex file."); 375 UsageError(""); 376 UsageError(" --force-determinism: force the compiler to emit a deterministic output."); 377 UsageError(" This option is incompatible with read barriers (e.g., if dex2oat has been"); 378 UsageError(" built with the environment variable `ART_USE_READ_BARRIER` set to `true`)."); 379 UsageError(""); 380 std::cerr << "See log for usage error information\n"; 381 exit(EXIT_FAILURE); 382} 383 384// The primary goal of the watchdog is to prevent stuck build servers 385// during development when fatal aborts lead to a cascade of failures 386// that result in a deadlock. 387class WatchDog { 388// WatchDog defines its own CHECK_PTHREAD_CALL to avoid using LOG which uses locks 389#undef CHECK_PTHREAD_CALL 390#define CHECK_WATCH_DOG_PTHREAD_CALL(call, args, what) \ 391 do { \ 392 int rc = call args; \ 393 if (rc != 0) { \ 394 errno = rc; \ 395 std::string message(# call); \ 396 message += " failed for "; \ 397 message += reason; \ 398 Fatal(message); \ 399 } \ 400 } while (false) 401 402 public: 403 explicit WatchDog(bool is_watch_dog_enabled) { 404 is_watch_dog_enabled_ = is_watch_dog_enabled; 405 if (!is_watch_dog_enabled_) { 406 return; 407 } 408 shutting_down_ = false; 409 const char* reason = "dex2oat watch dog thread startup"; 410 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_init, (&mutex_, nullptr), reason); 411 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_init, (&cond_, nullptr), reason); 412 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_init, (&attr_), reason); 413 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_create, (&pthread_, &attr_, &CallBack, this), reason); 414 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_destroy, (&attr_), reason); 415 } 416 ~WatchDog() { 417 if (!is_watch_dog_enabled_) { 418 return; 419 } 420 const char* reason = "dex2oat watch dog thread shutdown"; 421 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason); 422 shutting_down_ = true; 423 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_signal, (&cond_), reason); 424 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason); 425 426 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_join, (pthread_, nullptr), reason); 427 428 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_destroy, (&cond_), reason); 429 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_destroy, (&mutex_), reason); 430 } 431 432 private: 433 static void* CallBack(void* arg) { 434 WatchDog* self = reinterpret_cast<WatchDog*>(arg); 435 ::art::SetThreadName("dex2oat watch dog"); 436 self->Wait(); 437 return nullptr; 438 } 439 440 NO_RETURN static void Fatal(const std::string& message) { 441 // TODO: When we can guarantee it won't prevent shutdown in error cases, move to LOG. However, 442 // it's rather easy to hang in unwinding. 443 // LogLine also avoids ART logging lock issues, as it's really only a wrapper around 444 // logcat logging or stderr output. 445 LogMessage::LogLine(__FILE__, __LINE__, LogSeverity::FATAL, message.c_str()); 446 exit(1); 447 } 448 449 void Wait() { 450 // TODO: tune the multiplier for GC verification, the following is just to make the timeout 451 // large. 452 constexpr int64_t multiplier = kVerifyObjectSupport > kVerifyObjectModeFast ? 100 : 1; 453 timespec timeout_ts; 454 InitTimeSpec(true, CLOCK_REALTIME, multiplier * kWatchDogTimeoutSeconds * 1000, 0, &timeout_ts); 455 const char* reason = "dex2oat watch dog thread waiting"; 456 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason); 457 while (!shutting_down_) { 458 int rc = TEMP_FAILURE_RETRY(pthread_cond_timedwait(&cond_, &mutex_, &timeout_ts)); 459 if (rc == ETIMEDOUT) { 460 Fatal(StringPrintf("dex2oat did not finish after %" PRId64 " seconds", 461 kWatchDogTimeoutSeconds)); 462 } else if (rc != 0) { 463 std::string message(StringPrintf("pthread_cond_timedwait failed: %s", 464 strerror(errno))); 465 Fatal(message.c_str()); 466 } 467 } 468 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason); 469 } 470 471 // When setting timeouts, keep in mind that the build server may not be as fast as your desktop. 472 // Debug builds are slower so they have larger timeouts. 473 static constexpr int64_t kSlowdownFactor = kIsDebugBuild ? 5U : 1U; 474 475 // 9.5 minutes scaled by kSlowdownFactor. This is slightly smaller than the Package Manager 476 // watchdog (PackageManagerService.WATCHDOG_TIMEOUT, 10 minutes), so that dex2oat will abort 477 // itself before that watchdog would take down the system server. 478 static constexpr int64_t kWatchDogTimeoutSeconds = kSlowdownFactor * (9 * 60 + 30); 479 480 bool is_watch_dog_enabled_; 481 bool shutting_down_; 482 // TODO: Switch to Mutex when we can guarantee it won't prevent shutdown in error cases. 483 pthread_mutex_t mutex_; 484 pthread_cond_t cond_; 485 pthread_attr_t attr_; 486 pthread_t pthread_; 487}; 488 489class Dex2Oat FINAL { 490 public: 491 explicit Dex2Oat(TimingLogger* timings) : 492 compiler_kind_(Compiler::kOptimizing), 493 instruction_set_(kRuntimeISA), 494 // Take the default set of instruction features from the build. 495 image_file_location_oat_checksum_(0), 496 image_file_location_oat_data_begin_(0), 497 image_patch_delta_(0), 498 key_value_store_(nullptr), 499 verification_results_(nullptr), 500 method_inliner_map_(), 501 runtime_(nullptr), 502 thread_count_(sysconf(_SC_NPROCESSORS_CONF)), 503 start_ns_(NanoTime()), 504 oat_fd_(-1), 505 zip_fd_(-1), 506 image_base_(0U), 507 image_classes_zip_filename_(nullptr), 508 image_classes_filename_(nullptr), 509 image_storage_mode_(ImageHeader::kStorageModeUncompressed), 510 compiled_classes_zip_filename_(nullptr), 511 compiled_classes_filename_(nullptr), 512 compiled_methods_zip_filename_(nullptr), 513 compiled_methods_filename_(nullptr), 514 app_image_(false), 515 boot_image_(false), 516 multi_image_(false), 517 is_host_(false), 518 class_loader_(nullptr), 519 elf_writers_(), 520 oat_writers_(), 521 rodata_(), 522 image_writer_(nullptr), 523 driver_(nullptr), 524 opened_dex_files_maps_(), 525 opened_dex_files_(), 526 no_inline_from_dex_files_(), 527 dump_stats_(false), 528 dump_passes_(false), 529 dump_timing_(false), 530 dump_slow_timing_(kIsDebugBuild), 531 swap_fd_(kInvalidFd), 532 app_image_fd_(kInvalidFd), 533 profile_file_fd_(kInvalidFd), 534 timings_(timings), 535 force_determinism_(false) 536 {} 537 538 ~Dex2Oat() { 539 // Log completion time before deleting the runtime_, because this accesses 540 // the runtime. 541 LogCompletionTime(); 542 543 if (!kIsDebugBuild && !(RUNNING_ON_MEMORY_TOOL && kMemoryToolDetectsLeaks)) { 544 // We want to just exit on non-debug builds, not bringing the runtime down 545 // in an orderly fashion. So release the following fields. 546 driver_.release(); 547 image_writer_.release(); 548 for (std::unique_ptr<const DexFile>& dex_file : opened_dex_files_) { 549 dex_file.release(); 550 } 551 for (std::unique_ptr<MemMap>& map : opened_dex_files_maps_) { 552 map.release(); 553 } 554 for (std::unique_ptr<File>& oat_file : oat_files_) { 555 oat_file.release(); 556 } 557 runtime_.release(); 558 verification_results_.release(); 559 key_value_store_.release(); 560 } 561 } 562 563 struct ParserOptions { 564 std::vector<const char*> oat_symbols; 565 std::string boot_image_filename; 566 bool watch_dog_enabled = true; 567 bool requested_specific_compiler = false; 568 std::string error_msg; 569 }; 570 571 void ParseZipFd(const StringPiece& option) { 572 ParseUintOption(option, "--zip-fd", &zip_fd_, Usage); 573 } 574 575 void ParseOatFd(const StringPiece& option) { 576 ParseUintOption(option, "--oat-fd", &oat_fd_, Usage); 577 } 578 579 void ParseFdForCollection(const StringPiece& option, 580 const char* arg_name, 581 std::vector<uint32_t>* fds) { 582 uint32_t fd; 583 ParseUintOption(option, arg_name, &fd, Usage); 584 fds->push_back(fd); 585 } 586 587 void ParseJ(const StringPiece& option) { 588 ParseUintOption(option, "-j", &thread_count_, Usage, /* is_long_option */ false); 589 } 590 591 void ParseBase(const StringPiece& option) { 592 DCHECK(option.starts_with("--base=")); 593 const char* image_base_str = option.substr(strlen("--base=")).data(); 594 char* end; 595 image_base_ = strtoul(image_base_str, &end, 16); 596 if (end == image_base_str || *end != '\0') { 597 Usage("Failed to parse hexadecimal value for option %s", option.data()); 598 } 599 } 600 601 void ParseInstructionSet(const StringPiece& option) { 602 DCHECK(option.starts_with("--instruction-set=")); 603 StringPiece instruction_set_str = option.substr(strlen("--instruction-set=")).data(); 604 // StringPiece is not necessarily zero-terminated, so need to make a copy and ensure it. 605 std::unique_ptr<char[]> buf(new char[instruction_set_str.length() + 1]); 606 strncpy(buf.get(), instruction_set_str.data(), instruction_set_str.length()); 607 buf.get()[instruction_set_str.length()] = 0; 608 instruction_set_ = GetInstructionSetFromString(buf.get()); 609 // arm actually means thumb2. 610 if (instruction_set_ == InstructionSet::kArm) { 611 instruction_set_ = InstructionSet::kThumb2; 612 } 613 } 614 615 void ParseInstructionSetVariant(const StringPiece& option, ParserOptions* parser_options) { 616 DCHECK(option.starts_with("--instruction-set-variant=")); 617 StringPiece str = option.substr(strlen("--instruction-set-variant=")).data(); 618 instruction_set_features_.reset( 619 InstructionSetFeatures::FromVariant( 620 instruction_set_, str.as_string(), &parser_options->error_msg)); 621 if (instruction_set_features_.get() == nullptr) { 622 Usage("%s", parser_options->error_msg.c_str()); 623 } 624 } 625 626 void ParseInstructionSetFeatures(const StringPiece& option, ParserOptions* parser_options) { 627 DCHECK(option.starts_with("--instruction-set-features=")); 628 StringPiece str = option.substr(strlen("--instruction-set-features=")).data(); 629 if (instruction_set_features_.get() == nullptr) { 630 instruction_set_features_.reset( 631 InstructionSetFeatures::FromVariant( 632 instruction_set_, "default", &parser_options->error_msg)); 633 if (instruction_set_features_.get() == nullptr) { 634 Usage("Problem initializing default instruction set features variant: %s", 635 parser_options->error_msg.c_str()); 636 } 637 } 638 instruction_set_features_.reset( 639 instruction_set_features_->AddFeaturesFromString(str.as_string(), 640 &parser_options->error_msg)); 641 if (instruction_set_features_.get() == nullptr) { 642 Usage("Error parsing '%s': %s", option.data(), parser_options->error_msg.c_str()); 643 } 644 } 645 646 void ParseCompilerBackend(const StringPiece& option, ParserOptions* parser_options) { 647 DCHECK(option.starts_with("--compiler-backend=")); 648 parser_options->requested_specific_compiler = true; 649 StringPiece backend_str = option.substr(strlen("--compiler-backend=")).data(); 650 if (backend_str == "Quick") { 651 compiler_kind_ = Compiler::kQuick; 652 } else if (backend_str == "Optimizing") { 653 compiler_kind_ = Compiler::kOptimizing; 654 } else { 655 Usage("Unknown compiler backend: %s", backend_str.data()); 656 } 657 } 658 659 void ParseImageFormat(const StringPiece& option) { 660 const StringPiece substr("--image-format="); 661 DCHECK(option.starts_with(substr)); 662 const StringPiece format_str = option.substr(substr.length()); 663 if (format_str == "lz4") { 664 image_storage_mode_ = ImageHeader::kStorageModeLZ4; 665 } else if (format_str == "lz4hc") { 666 image_storage_mode_ = ImageHeader::kStorageModeLZ4HC; 667 } else if (format_str == "uncompressed") { 668 image_storage_mode_ = ImageHeader::kStorageModeUncompressed; 669 } else { 670 Usage("Unknown image format: %s", format_str.data()); 671 } 672 } 673 674 void ProcessOptions(ParserOptions* parser_options) { 675 boot_image_ = !image_filenames_.empty(); 676 app_image_ = app_image_fd_ != -1 || !app_image_file_name_.empty(); 677 678 if (IsAppImage() && IsBootImage()) { 679 Usage("Can't have both --image and (--app-image-fd or --app-image-file)"); 680 } 681 682 if (IsBootImage()) { 683 // We need the boot image to always be debuggable. 684 // TODO: Remove this once we better deal with full frame deoptimization. 685 compiler_options_->debuggable_ = true; 686 } 687 688 if (oat_filenames_.empty() && oat_fd_ == -1) { 689 Usage("Output must be supplied with either --oat-file or --oat-fd"); 690 } 691 692 if (!oat_filenames_.empty() && oat_fd_ != -1) { 693 Usage("--oat-file should not be used with --oat-fd"); 694 } 695 696 if (!parser_options->oat_symbols.empty() && oat_fd_ != -1) { 697 Usage("--oat-symbols should not be used with --oat-fd"); 698 } 699 700 if (!parser_options->oat_symbols.empty() && is_host_) { 701 Usage("--oat-symbols should not be used with --host"); 702 } 703 704 if (oat_fd_ != -1 && !image_filenames_.empty()) { 705 Usage("--oat-fd should not be used with --image"); 706 } 707 708 if (!parser_options->oat_symbols.empty() && 709 parser_options->oat_symbols.size() != oat_filenames_.size()) { 710 Usage("--oat-file arguments do not match --oat-symbols arguments"); 711 } 712 713 if (!image_filenames_.empty() && image_filenames_.size() != oat_filenames_.size()) { 714 Usage("--oat-file arguments do not match --image arguments"); 715 } 716 717 if (android_root_.empty()) { 718 const char* android_root_env_var = getenv("ANDROID_ROOT"); 719 if (android_root_env_var == nullptr) { 720 Usage("--android-root unspecified and ANDROID_ROOT not set"); 721 } 722 android_root_ += android_root_env_var; 723 } 724 725 if (!boot_image_ && parser_options->boot_image_filename.empty()) { 726 parser_options->boot_image_filename += android_root_; 727 parser_options->boot_image_filename += "/framework/boot.art"; 728 } 729 if (!parser_options->boot_image_filename.empty()) { 730 boot_image_filename_ = parser_options->boot_image_filename; 731 } 732 733 if (image_classes_filename_ != nullptr && !IsBootImage()) { 734 Usage("--image-classes should only be used with --image"); 735 } 736 737 if (image_classes_filename_ != nullptr && !boot_image_filename_.empty()) { 738 Usage("--image-classes should not be used with --boot-image"); 739 } 740 741 if (image_classes_zip_filename_ != nullptr && image_classes_filename_ == nullptr) { 742 Usage("--image-classes-zip should be used with --image-classes"); 743 } 744 745 if (compiled_classes_filename_ != nullptr && !IsBootImage()) { 746 Usage("--compiled-classes should only be used with --image"); 747 } 748 749 if (compiled_classes_filename_ != nullptr && !boot_image_filename_.empty()) { 750 Usage("--compiled-classes should not be used with --boot-image"); 751 } 752 753 if (compiled_classes_zip_filename_ != nullptr && compiled_classes_filename_ == nullptr) { 754 Usage("--compiled-classes-zip should be used with --compiled-classes"); 755 } 756 757 if (dex_filenames_.empty() && zip_fd_ == -1) { 758 Usage("Input must be supplied with either --dex-file or --zip-fd"); 759 } 760 761 if (!dex_filenames_.empty() && zip_fd_ != -1) { 762 Usage("--dex-file should not be used with --zip-fd"); 763 } 764 765 if (!dex_filenames_.empty() && !zip_location_.empty()) { 766 Usage("--dex-file should not be used with --zip-location"); 767 } 768 769 if (dex_locations_.empty()) { 770 for (const char* dex_file_name : dex_filenames_) { 771 dex_locations_.push_back(dex_file_name); 772 } 773 } else if (dex_locations_.size() != dex_filenames_.size()) { 774 Usage("--dex-location arguments do not match --dex-file arguments"); 775 } 776 777 if (!dex_filenames_.empty() && !oat_filenames_.empty()) { 778 if (oat_filenames_.size() != 1 && oat_filenames_.size() != dex_filenames_.size()) { 779 Usage("--oat-file arguments must be singular or match --dex-file arguments"); 780 } 781 } 782 783 if (zip_fd_ != -1 && zip_location_.empty()) { 784 Usage("--zip-location should be supplied with --zip-fd"); 785 } 786 787 if (boot_image_filename_.empty()) { 788 if (image_base_ == 0) { 789 Usage("Non-zero --base not specified"); 790 } 791 } 792 793 const bool have_profile_file = !profile_file_.empty(); 794 const bool have_profile_fd = profile_file_fd_ != kInvalidFd; 795 if (have_profile_file && have_profile_fd) { 796 Usage("Profile file should not be specified with both --profile-file-fd and --profile-file"); 797 } 798 799 if (!parser_options->oat_symbols.empty()) { 800 oat_unstripped_ = std::move(parser_options->oat_symbols); 801 } 802 803 // If no instruction set feature was given, use the default one for the target 804 // instruction set. 805 if (instruction_set_features_.get() == nullptr) { 806 instruction_set_features_.reset( 807 InstructionSetFeatures::FromVariant( 808 instruction_set_, "default", &parser_options->error_msg)); 809 if (instruction_set_features_.get() == nullptr) { 810 Usage("Problem initializing default instruction set features variant: %s", 811 parser_options->error_msg.c_str()); 812 } 813 } 814 815 if (instruction_set_ == kRuntimeISA) { 816 std::unique_ptr<const InstructionSetFeatures> runtime_features( 817 InstructionSetFeatures::FromCppDefines()); 818 if (!instruction_set_features_->Equals(runtime_features.get())) { 819 LOG(WARNING) << "Mismatch between dex2oat instruction set features (" 820 << *instruction_set_features_ << ") and those of dex2oat executable (" 821 << *runtime_features <<") for the command line:\n" 822 << CommandLine(); 823 } 824 } 825 826 // It they are not set, use default values for inlining settings. 827 // TODO: We should rethink the compiler filter. We mostly save 828 // time here, which is orthogonal to space. 829 if (compiler_options_->inline_depth_limit_ == CompilerOptions::kUnsetInlineDepthLimit) { 830 compiler_options_->inline_depth_limit_ = 831 (compiler_options_->compiler_filter_ == CompilerFilter::kSpace) 832 // Implementation of the space filter: limit inlining depth. 833 ? CompilerOptions::kSpaceFilterInlineDepthLimit 834 : CompilerOptions::kDefaultInlineDepthLimit; 835 } 836 if (compiler_options_->inline_max_code_units_ == CompilerOptions::kUnsetInlineMaxCodeUnits) { 837 compiler_options_->inline_max_code_units_ = 838 (compiler_options_->compiler_filter_ == CompilerFilter::kSpace) 839 // Implementation of the space filter: limit inlining max code units. 840 ? CompilerOptions::kSpaceFilterInlineMaxCodeUnits 841 : CompilerOptions::kDefaultInlineMaxCodeUnits; 842 } 843 844 // Checks are all explicit until we know the architecture. 845 // Set the compilation target's implicit checks options. 846 switch (instruction_set_) { 847 case kArm: 848 case kThumb2: 849 case kArm64: 850 case kX86: 851 case kX86_64: 852 case kMips: 853 case kMips64: 854 compiler_options_->implicit_null_checks_ = true; 855 compiler_options_->implicit_so_checks_ = true; 856 break; 857 858 default: 859 // Defaults are correct. 860 break; 861 } 862 863 compiler_options_->verbose_methods_ = verbose_methods_.empty() ? nullptr : &verbose_methods_; 864 865 if (!IsBootImage() && multi_image_) { 866 Usage("--multi-image can only be used when creating boot images"); 867 } 868 if (IsBootImage() && multi_image_ && image_filenames_.size() > 1) { 869 Usage("--multi-image cannot be used with multiple image names"); 870 } 871 872 // For now, if we're on the host and compile the boot image, *always* use multiple image files. 873 if (!kIsTargetBuild && IsBootImage()) { 874 if (image_filenames_.size() == 1) { 875 multi_image_ = true; 876 } 877 } 878 879 // Done with usage checks, enable watchdog if requested 880 if (parser_options->watch_dog_enabled) { 881 watchdog_.reset(new WatchDog(true)); 882 } 883 884 // Fill some values into the key-value store for the oat header. 885 key_value_store_.reset(new SafeMap<std::string, std::string>()); 886 887 // Automatically force determinism for the boot image in a host build if the default GC is CMS 888 // or MS and read barriers are not enabled, as the former switches the GC to a non-concurrent 889 // one by passing the option `-Xgc:nonconcurrent` (see below). 890 if (!kIsTargetBuild && IsBootImage()) { 891 if (SupportsDeterministicCompilation()) { 892 force_determinism_ = true; 893 } else { 894 LOG(WARNING) << "Deterministic compilation is disabled."; 895 } 896 } 897 compiler_options_->force_determinism_ = force_determinism_; 898 } 899 900 static bool SupportsDeterministicCompilation() { 901 return (gc::kCollectorTypeDefault == gc::kCollectorTypeCMS || 902 gc::kCollectorTypeDefault == gc::kCollectorTypeMS) && 903 !kEmitCompilerReadBarrier; 904 } 905 906 void ExpandOatAndImageFilenames() { 907 std::string base_oat = oat_filenames_[0]; 908 size_t last_oat_slash = base_oat.rfind('/'); 909 if (last_oat_slash == std::string::npos) { 910 Usage("--multi-image used with unusable oat filename %s", base_oat.c_str()); 911 } 912 // We also need to honor path components that were encoded through '@'. Otherwise the loading 913 // code won't be able to find the images. 914 if (base_oat.find('@', last_oat_slash) != std::string::npos) { 915 last_oat_slash = base_oat.rfind('@'); 916 } 917 base_oat = base_oat.substr(0, last_oat_slash + 1); 918 919 std::string base_img = image_filenames_[0]; 920 size_t last_img_slash = base_img.rfind('/'); 921 if (last_img_slash == std::string::npos) { 922 Usage("--multi-image used with unusable image filename %s", base_img.c_str()); 923 } 924 // We also need to honor path components that were encoded through '@'. Otherwise the loading 925 // code won't be able to find the images. 926 if (base_img.find('@', last_img_slash) != std::string::npos) { 927 last_img_slash = base_img.rfind('@'); 928 } 929 930 // Get the prefix, which is the primary image name (without path components). Strip the 931 // extension. 932 std::string prefix = base_img.substr(last_img_slash + 1); 933 if (prefix.rfind('.') != std::string::npos) { 934 prefix = prefix.substr(0, prefix.rfind('.')); 935 } 936 if (!prefix.empty()) { 937 prefix = prefix + "-"; 938 } 939 940 base_img = base_img.substr(0, last_img_slash + 1); 941 942 // Note: we have some special case here for our testing. We have to inject the differentiating 943 // parts for the different core images. 944 std::string infix; // Empty infix by default. 945 { 946 // Check the first name. 947 std::string dex_file = oat_filenames_[0]; 948 size_t last_dex_slash = dex_file.rfind('/'); 949 if (last_dex_slash != std::string::npos) { 950 dex_file = dex_file.substr(last_dex_slash + 1); 951 } 952 size_t last_dex_dot = dex_file.rfind('.'); 953 if (last_dex_dot != std::string::npos) { 954 dex_file = dex_file.substr(0, last_dex_dot); 955 } 956 if (StartsWith(dex_file, "core-")) { 957 infix = dex_file.substr(strlen("core")); 958 } 959 } 960 961 // Now create the other names. Use a counted loop to skip the first one. 962 for (size_t i = 1; i < dex_locations_.size(); ++i) { 963 // TODO: Make everything properly std::string. 964 std::string image_name = CreateMultiImageName(dex_locations_[i], prefix, infix, ".art"); 965 char_backing_storage_.push_back(base_img + image_name); 966 image_filenames_.push_back((char_backing_storage_.end() - 1)->c_str()); 967 968 std::string oat_name = CreateMultiImageName(dex_locations_[i], prefix, infix, ".oat"); 969 char_backing_storage_.push_back(base_oat + oat_name); 970 oat_filenames_.push_back((char_backing_storage_.end() - 1)->c_str()); 971 } 972 } 973 974 // Modify the input string in the following way: 975 // 0) Assume input is /a/b/c.d 976 // 1) Strip the path -> c.d 977 // 2) Inject prefix p -> pc.d 978 // 3) Inject infix i -> pci.d 979 // 4) Replace suffix with s if it's "jar" -> d == "jar" -> pci.s 980 static std::string CreateMultiImageName(std::string in, 981 const std::string& prefix, 982 const std::string& infix, 983 const char* replace_suffix) { 984 size_t last_dex_slash = in.rfind('/'); 985 if (last_dex_slash != std::string::npos) { 986 in = in.substr(last_dex_slash + 1); 987 } 988 if (!prefix.empty()) { 989 in = prefix + in; 990 } 991 if (!infix.empty()) { 992 // Inject infix. 993 size_t last_dot = in.rfind('.'); 994 if (last_dot != std::string::npos) { 995 in.insert(last_dot, infix); 996 } 997 } 998 if (EndsWith(in, ".jar")) { 999 in = in.substr(0, in.length() - strlen(".jar")) + 1000 (replace_suffix != nullptr ? replace_suffix : ""); 1001 } 1002 return in; 1003 } 1004 1005 void InsertCompileOptions(int argc, char** argv) { 1006 std::ostringstream oss; 1007 for (int i = 0; i < argc; ++i) { 1008 if (i > 0) { 1009 oss << ' '; 1010 } 1011 oss << argv[i]; 1012 } 1013 key_value_store_->Put(OatHeader::kDex2OatCmdLineKey, oss.str()); 1014 oss.str(""); // Reset. 1015 oss << kRuntimeISA; 1016 key_value_store_->Put(OatHeader::kDex2OatHostKey, oss.str()); 1017 key_value_store_->Put( 1018 OatHeader::kPicKey, 1019 compiler_options_->compile_pic_ ? OatHeader::kTrueValue : OatHeader::kFalseValue); 1020 key_value_store_->Put( 1021 OatHeader::kDebuggableKey, 1022 compiler_options_->debuggable_ ? OatHeader::kTrueValue : OatHeader::kFalseValue); 1023 key_value_store_->Put( 1024 OatHeader::kNativeDebuggableKey, 1025 compiler_options_->GetNativeDebuggable() ? OatHeader::kTrueValue : OatHeader::kFalseValue); 1026 key_value_store_->Put(OatHeader::kCompilerFilter, 1027 CompilerFilter::NameOfFilter(compiler_options_->GetCompilerFilter())); 1028 key_value_store_->Put(OatHeader::kHasPatchInfoKey, 1029 compiler_options_->GetIncludePatchInformation() ? OatHeader::kTrueValue 1030 : OatHeader::kFalseValue); 1031 } 1032 1033 // Parse the arguments from the command line. In case of an unrecognized option or impossible 1034 // values/combinations, a usage error will be displayed and exit() is called. Thus, if the method 1035 // returns, arguments have been successfully parsed. 1036 void ParseArgs(int argc, char** argv) { 1037 original_argc = argc; 1038 original_argv = argv; 1039 1040 InitLogging(argv); 1041 1042 // Skip over argv[0]. 1043 argv++; 1044 argc--; 1045 1046 if (argc == 0) { 1047 Usage("No arguments specified"); 1048 } 1049 1050 std::unique_ptr<ParserOptions> parser_options(new ParserOptions()); 1051 compiler_options_.reset(new CompilerOptions()); 1052 1053 for (int i = 0; i < argc; i++) { 1054 const StringPiece option(argv[i]); 1055 const bool log_options = false; 1056 if (log_options) { 1057 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i]; 1058 } 1059 if (option.starts_with("--dex-file=")) { 1060 dex_filenames_.push_back(option.substr(strlen("--dex-file=")).data()); 1061 } else if (option.starts_with("--dex-location=")) { 1062 dex_locations_.push_back(option.substr(strlen("--dex-location=")).data()); 1063 } else if (option.starts_with("--zip-fd=")) { 1064 ParseZipFd(option); 1065 } else if (option.starts_with("--zip-location=")) { 1066 zip_location_ = option.substr(strlen("--zip-location=")).data(); 1067 } else if (option.starts_with("--oat-file=")) { 1068 oat_filenames_.push_back(option.substr(strlen("--oat-file=")).data()); 1069 } else if (option.starts_with("--oat-symbols=")) { 1070 parser_options->oat_symbols.push_back(option.substr(strlen("--oat-symbols=")).data()); 1071 } else if (option.starts_with("--oat-fd=")) { 1072 ParseOatFd(option); 1073 } else if (option == "--watch-dog") { 1074 parser_options->watch_dog_enabled = true; 1075 } else if (option == "--no-watch-dog") { 1076 parser_options->watch_dog_enabled = false; 1077 } else if (option.starts_with("-j")) { 1078 ParseJ(option); 1079 } else if (option.starts_with("--oat-location=")) { 1080 oat_location_ = option.substr(strlen("--oat-location=")).data(); 1081 } else if (option.starts_with("--image=")) { 1082 image_filenames_.push_back(option.substr(strlen("--image=")).data()); 1083 } else if (option.starts_with("--image-classes=")) { 1084 image_classes_filename_ = option.substr(strlen("--image-classes=")).data(); 1085 } else if (option.starts_with("--image-classes-zip=")) { 1086 image_classes_zip_filename_ = option.substr(strlen("--image-classes-zip=")).data(); 1087 } else if (option.starts_with("--image-format=")) { 1088 ParseImageFormat(option); 1089 } else if (option.starts_with("--compiled-classes=")) { 1090 compiled_classes_filename_ = option.substr(strlen("--compiled-classes=")).data(); 1091 } else if (option.starts_with("--compiled-classes-zip=")) { 1092 compiled_classes_zip_filename_ = option.substr(strlen("--compiled-classes-zip=")).data(); 1093 } else if (option.starts_with("--compiled-methods=")) { 1094 compiled_methods_filename_ = option.substr(strlen("--compiled-methods=")).data(); 1095 } else if (option.starts_with("--compiled-methods-zip=")) { 1096 compiled_methods_zip_filename_ = option.substr(strlen("--compiled-methods-zip=")).data(); 1097 } else if (option.starts_with("--base=")) { 1098 ParseBase(option); 1099 } else if (option.starts_with("--boot-image=")) { 1100 parser_options->boot_image_filename = option.substr(strlen("--boot-image=")).data(); 1101 } else if (option.starts_with("--android-root=")) { 1102 android_root_ = option.substr(strlen("--android-root=")).data(); 1103 } else if (option.starts_with("--instruction-set=")) { 1104 ParseInstructionSet(option); 1105 } else if (option.starts_with("--instruction-set-variant=")) { 1106 ParseInstructionSetVariant(option, parser_options.get()); 1107 } else if (option.starts_with("--instruction-set-features=")) { 1108 ParseInstructionSetFeatures(option, parser_options.get()); 1109 } else if (option.starts_with("--compiler-backend=")) { 1110 ParseCompilerBackend(option, parser_options.get()); 1111 } else if (option.starts_with("--profile-file=")) { 1112 profile_file_ = option.substr(strlen("--profile-file=")).ToString(); 1113 } else if (option.starts_with("--profile-file-fd=")) { 1114 ParseUintOption(option, "--profile-file-fd", &profile_file_fd_, Usage); 1115 } else if (option == "--host") { 1116 is_host_ = true; 1117 } else if (option == "--runtime-arg") { 1118 if (++i >= argc) { 1119 Usage("Missing required argument for --runtime-arg"); 1120 } 1121 if (log_options) { 1122 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i]; 1123 } 1124 runtime_args_.push_back(argv[i]); 1125 } else if (option == "--dump-timing") { 1126 dump_timing_ = true; 1127 } else if (option == "--dump-passes") { 1128 dump_passes_ = true; 1129 } else if (option == "--dump-stats") { 1130 dump_stats_ = true; 1131 } else if (option.starts_with("--swap-file=")) { 1132 swap_file_name_ = option.substr(strlen("--swap-file=")).data(); 1133 } else if (option.starts_with("--swap-fd=")) { 1134 ParseUintOption(option, "--swap-fd", &swap_fd_, Usage); 1135 } else if (option.starts_with("--swap-dex-size-threshold=")) { 1136 ParseUintOption(option, 1137 "--swap-dex-size-threshold", 1138 &min_dex_file_cumulative_size_for_swap_, 1139 Usage); 1140 } else if (option.starts_with("--swap-dex-count-threshold=")) { 1141 ParseUintOption(option, 1142 "--swap-dex-count-threshold", 1143 &min_dex_files_for_swap_, 1144 Usage); 1145 } else if (option.starts_with("--app-image-file=")) { 1146 app_image_file_name_ = option.substr(strlen("--app-image-file=")).data(); 1147 } else if (option.starts_with("--app-image-fd=")) { 1148 ParseUintOption(option, "--app-image-fd", &app_image_fd_, Usage); 1149 } else if (option.starts_with("--verbose-methods=")) { 1150 // TODO: rather than switch off compiler logging, make all VLOG(compiler) messages 1151 // conditional on having verbost methods. 1152 gLogVerbosity.compiler = false; 1153 Split(option.substr(strlen("--verbose-methods=")).ToString(), ',', &verbose_methods_); 1154 } else if (option == "--multi-image") { 1155 multi_image_ = true; 1156 } else if (option.starts_with("--no-inline-from=")) { 1157 no_inline_from_string_ = option.substr(strlen("--no-inline-from=")).data(); 1158 } else if (option == "--force-determinism") { 1159 if (!SupportsDeterministicCompilation()) { 1160 Usage("Cannot use --force-determinism with read barriers or non-CMS garbage collector"); 1161 } 1162 force_determinism_ = true; 1163 } else if (!compiler_options_->ParseCompilerOption(option, Usage)) { 1164 Usage("Unknown argument %s", option.data()); 1165 } 1166 } 1167 1168 ProcessOptions(parser_options.get()); 1169 1170 // Insert some compiler things. 1171 InsertCompileOptions(argc, argv); 1172 } 1173 1174 // Check whether the oat output files are writable, and open them for later. Also open a swap 1175 // file, if a name is given. 1176 bool OpenFile() { 1177 // Prune non-existent dex files now so that we don't create empty oat files for multi-image. 1178 PruneNonExistentDexFiles(); 1179 1180 // Expand oat and image filenames for multi image. 1181 if (IsBootImage() && multi_image_) { 1182 ExpandOatAndImageFilenames(); 1183 } 1184 1185 bool create_file = oat_fd_ == -1; // as opposed to using open file descriptor 1186 if (create_file) { 1187 for (const char* oat_filename : oat_filenames_) { 1188 std::unique_ptr<File> oat_file(OS::CreateEmptyFile(oat_filename)); 1189 if (oat_file.get() == nullptr) { 1190 PLOG(ERROR) << "Failed to create oat file: " << oat_filename; 1191 return false; 1192 } 1193 if (create_file && fchmod(oat_file->Fd(), 0644) != 0) { 1194 PLOG(ERROR) << "Failed to make oat file world readable: " << oat_filename; 1195 oat_file->Erase(); 1196 return false; 1197 } 1198 oat_files_.push_back(std::move(oat_file)); 1199 } 1200 } else { 1201 std::unique_ptr<File> oat_file(new File(oat_fd_, oat_location_, true)); 1202 oat_file->DisableAutoClose(); 1203 if (oat_file->SetLength(0) != 0) { 1204 PLOG(WARNING) << "Truncating oat file " << oat_location_ << " failed."; 1205 } 1206 if (oat_file.get() == nullptr) { 1207 PLOG(ERROR) << "Failed to create oat file: " << oat_location_; 1208 return false; 1209 } 1210 if (create_file && fchmod(oat_file->Fd(), 0644) != 0) { 1211 PLOG(ERROR) << "Failed to make oat file world readable: " << oat_location_; 1212 oat_file->Erase(); 1213 return false; 1214 } 1215 oat_filenames_.push_back(oat_location_.c_str()); 1216 oat_files_.push_back(std::move(oat_file)); 1217 } 1218 1219 // Swap file handling. 1220 // 1221 // If the swap fd is not -1, we assume this is the file descriptor of an open but unlinked file 1222 // that we can use for swap. 1223 // 1224 // If the swap fd is -1 and we have a swap-file string, open the given file as a swap file. We 1225 // will immediately unlink to satisfy the swap fd assumption. 1226 if (swap_fd_ == -1 && !swap_file_name_.empty()) { 1227 std::unique_ptr<File> swap_file(OS::CreateEmptyFile(swap_file_name_.c_str())); 1228 if (swap_file.get() == nullptr) { 1229 PLOG(ERROR) << "Failed to create swap file: " << swap_file_name_; 1230 return false; 1231 } 1232 swap_fd_ = swap_file->Fd(); 1233 swap_file->MarkUnchecked(); // We don't we to track this, it will be unlinked immediately. 1234 swap_file->DisableAutoClose(); // We'll handle it ourselves, the File object will be 1235 // released immediately. 1236 unlink(swap_file_name_.c_str()); 1237 } 1238 1239 return true; 1240 } 1241 1242 void EraseOatFiles() { 1243 for (size_t i = 0; i < oat_files_.size(); ++i) { 1244 DCHECK(oat_files_[i].get() != nullptr); 1245 oat_files_[i]->Erase(); 1246 oat_files_[i].reset(); 1247 } 1248 } 1249 1250 void Shutdown() { 1251 ScopedObjectAccess soa(Thread::Current()); 1252 for (jobject dex_cache : dex_caches_) { 1253 soa.Env()->DeleteLocalRef(dex_cache); 1254 } 1255 dex_caches_.clear(); 1256 } 1257 1258 void LoadClassProfileDescriptors() { 1259 if (profile_compilation_info_ != nullptr && app_image_) { 1260 Runtime* runtime = Runtime::Current(); 1261 CHECK(runtime != nullptr); 1262 std::set<DexCacheResolvedClasses> resolved_classes( 1263 profile_compilation_info_->GetResolvedClasses()); 1264 1265 // Filter out class path classes since we don't want to include these in the image. 1266 std::unordered_set<std::string> dex_files_locations; 1267 for (const DexFile* dex_file : dex_files_) { 1268 dex_files_locations.insert(dex_file->GetLocation()); 1269 } 1270 for (auto it = resolved_classes.begin(); it != resolved_classes.end(); ) { 1271 if (dex_files_locations.find(it->GetDexLocation()) == dex_files_locations.end()) { 1272 VLOG(compiler) << "Removed profile samples for non-app dex file " << it->GetDexLocation(); 1273 it = resolved_classes.erase(it); 1274 } else { 1275 ++it; 1276 } 1277 } 1278 1279 image_classes_.reset(new std::unordered_set<std::string>( 1280 runtime->GetClassLinker()->GetClassDescriptorsForProfileKeys(resolved_classes))); 1281 VLOG(compiler) << "Loaded " << image_classes_->size() 1282 << " image class descriptors from profile"; 1283 if (VLOG_IS_ON(compiler)) { 1284 for (const std::string& s : *image_classes_) { 1285 LOG(INFO) << "Image class " << s; 1286 } 1287 } 1288 } 1289 } 1290 1291 // Set up the environment for compilation. Includes starting the runtime and loading/opening the 1292 // boot class path. 1293 bool Setup() { 1294 TimingLogger::ScopedTiming t("dex2oat Setup", timings_); 1295 art::MemMap::Init(); // For ZipEntry::ExtractToMemMap. 1296 1297 if (!PrepareImageClasses() || !PrepareCompiledClasses() || !PrepareCompiledMethods()) { 1298 return false; 1299 } 1300 1301 verification_results_.reset(new VerificationResults(compiler_options_.get())); 1302 callbacks_.reset(new QuickCompilerCallbacks( 1303 verification_results_.get(), 1304 &method_inliner_map_, 1305 IsBootImage() ? 1306 CompilerCallbacks::CallbackMode::kCompileBootImage : 1307 CompilerCallbacks::CallbackMode::kCompileApp)); 1308 1309 RuntimeArgumentMap runtime_options; 1310 if (!PrepareRuntimeOptions(&runtime_options)) { 1311 return false; 1312 } 1313 1314 CreateOatWriters(); 1315 if (!AddDexFileSources()) { 1316 return false; 1317 } 1318 1319 if (IsBootImage() && image_filenames_.size() > 1) { 1320 // If we're compiling the boot image, store the boot classpath into the Key-Value store. 1321 // We need this for the multi-image case. 1322 key_value_store_->Put(OatHeader::kBootClassPathKey, GetMultiImageBootClassPath()); 1323 } 1324 1325 if (!IsBootImage()) { 1326 // When compiling an app, create the runtime early to retrieve 1327 // the image location key needed for the oat header. 1328 if (!CreateRuntime(std::move(runtime_options))) { 1329 return false; 1330 } 1331 1332 if (CompilerFilter::DependsOnImageChecksum(compiler_options_->GetCompilerFilter())) { 1333 TimingLogger::ScopedTiming t3("Loading image checksum", timings_); 1334 std::vector<gc::space::ImageSpace*> image_spaces = 1335 Runtime::Current()->GetHeap()->GetBootImageSpaces(); 1336 image_file_location_oat_checksum_ = OatFileAssistant::CalculateCombinedImageChecksum(); 1337 image_file_location_oat_data_begin_ = 1338 reinterpret_cast<uintptr_t>(image_spaces[0]->GetImageHeader().GetOatDataBegin()); 1339 image_patch_delta_ = image_spaces[0]->GetImageHeader().GetPatchDelta(); 1340 // Store the boot image filename(s). 1341 std::vector<std::string> image_filenames; 1342 for (const gc::space::ImageSpace* image_space : image_spaces) { 1343 image_filenames.push_back(image_space->GetImageFilename()); 1344 } 1345 std::string image_file_location = Join(image_filenames, ':'); 1346 if (!image_file_location.empty()) { 1347 key_value_store_->Put(OatHeader::kImageLocationKey, image_file_location); 1348 } 1349 } else { 1350 image_file_location_oat_checksum_ = 0u; 1351 image_file_location_oat_data_begin_ = 0u; 1352 image_patch_delta_ = 0; 1353 } 1354 1355 // Open dex files for class path. 1356 const std::vector<std::string> class_path_locations = 1357 GetClassPathLocations(runtime_->GetClassPathString()); 1358 OpenClassPathFiles(class_path_locations, 1359 &class_path_files_, 1360 &opened_oat_files_, 1361 runtime_->GetInstructionSet()); 1362 1363 // Store the classpath we have right now. 1364 std::vector<const DexFile*> class_path_files = MakeNonOwningPointerVector(class_path_files_); 1365 std::string encoded_class_path; 1366 if (class_path_locations.size() == 1 && 1367 class_path_locations[0] == OatFile::kSpecialSharedLibrary) { 1368 // When passing the special shared library as the classpath, it is the only path. 1369 encoded_class_path = OatFile::kSpecialSharedLibrary; 1370 } else { 1371 encoded_class_path = OatFile::EncodeDexFileDependencies(class_path_files); 1372 } 1373 key_value_store_->Put(OatHeader::kClassPathKey, encoded_class_path); 1374 } 1375 1376 // Now that we have finalized key_value_store_, start writing the oat file. 1377 { 1378 TimingLogger::ScopedTiming t_dex("Writing and opening dex files", timings_); 1379 rodata_.reserve(oat_writers_.size()); 1380 for (size_t i = 0, size = oat_writers_.size(); i != size; ++i) { 1381 rodata_.push_back(elf_writers_[i]->StartRoData()); 1382 // Unzip or copy dex files straight to the oat file. 1383 std::unique_ptr<MemMap> opened_dex_files_map; 1384 std::vector<std::unique_ptr<const DexFile>> opened_dex_files; 1385 if (!oat_writers_[i]->WriteAndOpenDexFiles(rodata_.back(), 1386 oat_files_[i].get(), 1387 instruction_set_, 1388 instruction_set_features_.get(), 1389 key_value_store_.get(), 1390 /* verify */ true, 1391 &opened_dex_files_map, 1392 &opened_dex_files)) { 1393 return false; 1394 } 1395 dex_files_per_oat_file_.push_back(MakeNonOwningPointerVector(opened_dex_files)); 1396 if (opened_dex_files_map != nullptr) { 1397 opened_dex_files_maps_.push_back(std::move(opened_dex_files_map)); 1398 for (std::unique_ptr<const DexFile>& dex_file : opened_dex_files) { 1399 dex_file_oat_index_map_.emplace(dex_file.get(), i); 1400 opened_dex_files_.push_back(std::move(dex_file)); 1401 } 1402 } else { 1403 DCHECK(opened_dex_files.empty()); 1404 } 1405 } 1406 } 1407 1408 dex_files_ = MakeNonOwningPointerVector(opened_dex_files_); 1409 1410 // We had to postpone the swap decision till now, as this is the point when we actually 1411 // know about the dex files we're going to use. 1412 1413 // Make sure that we didn't create the driver, yet. 1414 CHECK(driver_ == nullptr); 1415 // If we use a swap file, ensure we are above the threshold to make it necessary. 1416 if (swap_fd_ != -1) { 1417 if (!UseSwap(IsBootImage(), dex_files_)) { 1418 close(swap_fd_); 1419 swap_fd_ = -1; 1420 VLOG(compiler) << "Decided to run without swap."; 1421 } else { 1422 LOG(INFO) << "Large app, accepted running with swap."; 1423 } 1424 } 1425 // Note that dex2oat won't close the swap_fd_. The compiler driver's swap space will do that. 1426 1427 if (IsBootImage()) { 1428 // For boot image, pass opened dex files to the Runtime::Create(). 1429 // Note: Runtime acquires ownership of these dex files. 1430 runtime_options.Set(RuntimeArgumentMap::BootClassPathDexList, &opened_dex_files_); 1431 if (!CreateRuntime(std::move(runtime_options))) { 1432 return false; 1433 } 1434 } 1435 1436 // If we're doing the image, override the compiler filter to force full compilation. Must be 1437 // done ahead of WellKnownClasses::Init that causes verification. Note: doesn't force 1438 // compilation of class initializers. 1439 // Whilst we're in native take the opportunity to initialize well known classes. 1440 Thread* self = Thread::Current(); 1441 WellKnownClasses::Init(self->GetJniEnv()); 1442 1443 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker(); 1444 if (!IsBootImage()) { 1445 constexpr bool kSaveDexInput = false; 1446 if (kSaveDexInput) { 1447 SaveDexInput(); 1448 } 1449 1450 // Handle and ClassLoader creation needs to come after Runtime::Create. 1451 ScopedObjectAccess soa(self); 1452 1453 // Classpath: first the class-path given. 1454 std::vector<const DexFile*> class_path_files = MakeNonOwningPointerVector(class_path_files_); 1455 1456 // Then the dex files we'll compile. Thus we'll resolve the class-path first. 1457 class_path_files.insert(class_path_files.end(), dex_files_.begin(), dex_files_.end()); 1458 1459 class_loader_ = class_linker->CreatePathClassLoader(self, class_path_files); 1460 } 1461 1462 // Ensure opened dex files are writable for dex-to-dex transformations. 1463 for (const std::unique_ptr<MemMap>& map : opened_dex_files_maps_) { 1464 if (!map->Protect(PROT_READ | PROT_WRITE)) { 1465 PLOG(ERROR) << "Failed to make .dex files writeable."; 1466 return false; 1467 } 1468 } 1469 1470 // Ensure that the dex caches stay live since we don't want class unloading 1471 // to occur during compilation. 1472 for (const auto& dex_file : dex_files_) { 1473 ScopedObjectAccess soa(self); 1474 dex_caches_.push_back(soa.AddLocalReference<jobject>( 1475 class_linker->RegisterDexFile(*dex_file, 1476 soa.Decode<mirror::ClassLoader*>(class_loader_)))); 1477 } 1478 1479 return true; 1480 } 1481 1482 // If we need to keep the oat file open for the image writer. 1483 bool ShouldKeepOatFileOpen() const { 1484 return IsImage() && oat_fd_ != kInvalidFd; 1485 } 1486 1487 // Create and invoke the compiler driver. This will compile all the dex files. 1488 void Compile() { 1489 TimingLogger::ScopedTiming t("dex2oat Compile", timings_); 1490 compiler_phases_timings_.reset(new CumulativeLogger("compilation times")); 1491 1492 // Find the dex files we should not inline from. 1493 1494 std::vector<std::string> no_inline_filters; 1495 Split(no_inline_from_string_, ',', &no_inline_filters); 1496 1497 // For now, on the host always have core-oj removed. 1498 const std::string core_oj = "core-oj"; 1499 if (!kIsTargetBuild && !ContainsElement(no_inline_filters, core_oj)) { 1500 no_inline_filters.push_back(core_oj); 1501 } 1502 1503 if (!no_inline_filters.empty()) { 1504 ClassLinker* class_linker = Runtime::Current()->GetClassLinker(); 1505 std::vector<const DexFile*> class_path_files = MakeNonOwningPointerVector(class_path_files_); 1506 std::vector<const std::vector<const DexFile*>*> dex_file_vectors = { 1507 &class_linker->GetBootClassPath(), 1508 &class_path_files, 1509 &dex_files_ 1510 }; 1511 for (const std::vector<const DexFile*>* dex_file_vector : dex_file_vectors) { 1512 for (const DexFile* dex_file : *dex_file_vector) { 1513 for (const std::string& filter : no_inline_filters) { 1514 // Use dex_file->GetLocation() rather than dex_file->GetBaseLocation(). This 1515 // allows tests to specify <test-dexfile>:classes2.dex if needed but if the 1516 // base location passes the StartsWith() test, so do all extra locations. 1517 std::string dex_location = dex_file->GetLocation(); 1518 if (filter.find('/') == std::string::npos) { 1519 // The filter does not contain the path. Remove the path from dex_location as well. 1520 size_t last_slash = dex_file->GetLocation().rfind('/'); 1521 if (last_slash != std::string::npos) { 1522 dex_location = dex_location.substr(last_slash + 1); 1523 } 1524 } 1525 1526 if (StartsWith(dex_location, filter.c_str())) { 1527 VLOG(compiler) << "Disabling inlining from " << dex_file->GetLocation(); 1528 no_inline_from_dex_files_.push_back(dex_file); 1529 break; 1530 } 1531 } 1532 } 1533 } 1534 if (!no_inline_from_dex_files_.empty()) { 1535 compiler_options_->no_inline_from_ = &no_inline_from_dex_files_; 1536 } 1537 } 1538 1539 driver_.reset(new CompilerDriver(compiler_options_.get(), 1540 verification_results_.get(), 1541 &method_inliner_map_, 1542 compiler_kind_, 1543 instruction_set_, 1544 instruction_set_features_.get(), 1545 IsBootImage(), 1546 IsAppImage(), 1547 image_classes_.release(), 1548 compiled_classes_.release(), 1549 /* compiled_methods */ nullptr, 1550 thread_count_, 1551 dump_stats_, 1552 dump_passes_, 1553 compiler_phases_timings_.get(), 1554 swap_fd_, 1555 profile_compilation_info_.get())); 1556 driver_->SetDexFilesForOatFile(dex_files_); 1557 driver_->CompileAll(class_loader_, dex_files_, timings_); 1558 } 1559 1560 // Notes on the interleaving of creating the images and oat files to 1561 // ensure the references between the two are correct. 1562 // 1563 // Currently we have a memory layout that looks something like this: 1564 // 1565 // +--------------+ 1566 // | images | 1567 // +--------------+ 1568 // | oat files | 1569 // +--------------+ 1570 // | alloc spaces | 1571 // +--------------+ 1572 // 1573 // There are several constraints on the loading of the images and oat files. 1574 // 1575 // 1. The images are expected to be loaded at an absolute address and 1576 // contain Objects with absolute pointers within the images. 1577 // 1578 // 2. There are absolute pointers from Methods in the images to their 1579 // code in the oat files. 1580 // 1581 // 3. There are absolute pointers from the code in the oat files to Methods 1582 // in the images. 1583 // 1584 // 4. There are absolute pointers from code in the oat files to other code 1585 // in the oat files. 1586 // 1587 // To get this all correct, we go through several steps. 1588 // 1589 // 1. We prepare offsets for all data in the oat files and calculate 1590 // the oat data size and code size. During this stage, we also set 1591 // oat code offsets in methods for use by the image writer. 1592 // 1593 // 2. We prepare offsets for the objects in the images and calculate 1594 // the image sizes. 1595 // 1596 // 3. We create the oat files. Originally this was just our own proprietary 1597 // file but now it is contained within an ELF dynamic object (aka an .so 1598 // file). Since we know the image sizes and oat data sizes and code sizes we 1599 // can prepare the ELF headers and we then know the ELF memory segment 1600 // layout and we can now resolve all references. The compiler provides 1601 // LinkerPatch information in each CompiledMethod and we resolve these, 1602 // using the layout information and image object locations provided by 1603 // image writer, as we're writing the method code. 1604 // 1605 // 4. We create the image files. They need to know where the oat files 1606 // will be loaded after itself. Originally oat files were simply 1607 // memory mapped so we could predict where their contents were based 1608 // on the file size. Now that they are ELF files, we need to inspect 1609 // the ELF files to understand the in memory segment layout including 1610 // where the oat header is located within. 1611 // TODO: We could just remember this information from step 3. 1612 // 1613 // 5. We fixup the ELF program headers so that dlopen will try to 1614 // load the .so at the desired location at runtime by offsetting the 1615 // Elf32_Phdr.p_vaddr values by the desired base address. 1616 // TODO: Do this in step 3. We already know the layout there. 1617 // 1618 // Steps 1.-3. are done by the CreateOatFile() above, steps 4.-5. 1619 // are done by the CreateImageFile() below. 1620 1621 // Write out the generated code part. Calls the OatWriter and ElfBuilder. Also prepares the 1622 // ImageWriter, if necessary. 1623 // Note: Flushing (and closing) the file is the caller's responsibility, except for the failure 1624 // case (when the file will be explicitly erased). 1625 bool WriteOatFiles() { 1626 TimingLogger::ScopedTiming t("dex2oat Oat", timings_); 1627 1628 // Sync the data to the file, in case we did dex2dex transformations. 1629 for (const std::unique_ptr<MemMap>& map : opened_dex_files_maps_) { 1630 if (!map->Sync()) { 1631 PLOG(ERROR) << "Failed to Sync() dex2dex output. Map: " << map->GetName(); 1632 return false; 1633 } 1634 } 1635 1636 if (IsImage()) { 1637 if (app_image_ && image_base_ == 0) { 1638 gc::Heap* const heap = Runtime::Current()->GetHeap(); 1639 for (gc::space::ImageSpace* image_space : heap->GetBootImageSpaces()) { 1640 image_base_ = std::max(image_base_, RoundUp( 1641 reinterpret_cast<uintptr_t>(image_space->GetImageHeader().GetOatFileEnd()), 1642 kPageSize)); 1643 } 1644 // The non moving space is right after the oat file. Put the preferred app image location 1645 // right after the non moving space so that we ideally get a continuous immune region for 1646 // the GC. 1647 // Use the default non moving space capacity since dex2oat does not have a separate non- 1648 // moving space. This means the runtime's non moving space space size will be as large 1649 // as the growth limit for dex2oat, but smaller in the zygote. 1650 const size_t non_moving_space_capacity = gc::Heap::kDefaultNonMovingSpaceCapacity; 1651 image_base_ += non_moving_space_capacity; 1652 VLOG(compiler) << "App image base=" << reinterpret_cast<void*>(image_base_); 1653 } 1654 1655 image_writer_.reset(new ImageWriter(*driver_, 1656 image_base_, 1657 compiler_options_->GetCompilePic(), 1658 IsAppImage(), 1659 image_storage_mode_, 1660 oat_filenames_, 1661 dex_file_oat_index_map_)); 1662 1663 // We need to prepare method offsets in the image address space for direct method patching. 1664 TimingLogger::ScopedTiming t2("dex2oat Prepare image address space", timings_); 1665 if (!image_writer_->PrepareImageAddressSpace()) { 1666 LOG(ERROR) << "Failed to prepare image address space."; 1667 return false; 1668 } 1669 } 1670 1671 linker::MultiOatRelativePatcher patcher(instruction_set_, instruction_set_features_.get()); 1672 { 1673 TimingLogger::ScopedTiming t2("dex2oat Write ELF", timings_); 1674 for (size_t i = 0, size = oat_files_.size(); i != size; ++i) { 1675 std::unique_ptr<ElfWriter>& elf_writer = elf_writers_[i]; 1676 std::unique_ptr<OatWriter>& oat_writer = oat_writers_[i]; 1677 1678 std::vector<const DexFile*>& dex_files = dex_files_per_oat_file_[i]; 1679 oat_writer->PrepareLayout(driver_.get(), image_writer_.get(), dex_files, &patcher); 1680 1681 size_t rodata_size = oat_writer->GetOatHeader().GetExecutableOffset(); 1682 size_t text_size = oat_writer->GetSize() - rodata_size; 1683 elf_writer->SetLoadedSectionSizes(rodata_size, text_size, oat_writer->GetBssSize()); 1684 1685 if (IsImage()) { 1686 // Update oat layout. 1687 DCHECK(image_writer_ != nullptr); 1688 DCHECK_LT(i, oat_filenames_.size()); 1689 image_writer_->UpdateOatFileLayout(i, 1690 elf_writer->GetLoadedSize(), 1691 oat_writer->GetOatDataOffset(), 1692 oat_writer->GetSize()); 1693 } 1694 } 1695 1696 for (size_t i = 0, size = oat_files_.size(); i != size; ++i) { 1697 std::unique_ptr<File>& oat_file = oat_files_[i]; 1698 std::unique_ptr<ElfWriter>& elf_writer = elf_writers_[i]; 1699 std::unique_ptr<OatWriter>& oat_writer = oat_writers_[i]; 1700 1701 oat_writer->AddMethodDebugInfos(debug::MakeTrampolineInfos(oat_writer->GetOatHeader())); 1702 1703 // We need to mirror the layout of the ELF file in the compressed debug-info. 1704 // Therefore PrepareDebugInfo() relies on the SetLoadedSectionSizes() call further above. 1705 elf_writer->PrepareDebugInfo(oat_writer->GetMethodDebugInfo()); 1706 1707 OutputStream*& rodata = rodata_[i]; 1708 DCHECK(rodata != nullptr); 1709 if (!oat_writer->WriteRodata(rodata)) { 1710 LOG(ERROR) << "Failed to write .rodata section to the ELF file " << oat_file->GetPath(); 1711 return false; 1712 } 1713 elf_writer->EndRoData(rodata); 1714 rodata = nullptr; 1715 1716 OutputStream* text = elf_writer->StartText(); 1717 if (!oat_writer->WriteCode(text)) { 1718 LOG(ERROR) << "Failed to write .text section to the ELF file " << oat_file->GetPath(); 1719 return false; 1720 } 1721 elf_writer->EndText(text); 1722 1723 if (!oat_writer->WriteHeader(elf_writer->GetStream(), 1724 image_file_location_oat_checksum_, 1725 image_file_location_oat_data_begin_, 1726 image_patch_delta_)) { 1727 LOG(ERROR) << "Failed to write oat header to the ELF file " << oat_file->GetPath(); 1728 return false; 1729 } 1730 1731 if (IsImage()) { 1732 // Update oat header information. 1733 DCHECK(image_writer_ != nullptr); 1734 DCHECK_LT(i, oat_filenames_.size()); 1735 image_writer_->UpdateOatFileHeader(i, oat_writer->GetOatHeader()); 1736 } 1737 1738 elf_writer->WriteDynamicSection(); 1739 elf_writer->WriteDebugInfo(oat_writer->GetMethodDebugInfo()); 1740 elf_writer->WritePatchLocations(oat_writer->GetAbsolutePatchLocations()); 1741 1742 if (!elf_writer->End()) { 1743 LOG(ERROR) << "Failed to write ELF file " << oat_file->GetPath(); 1744 return false; 1745 } 1746 1747 // Flush the oat file. 1748 if (oat_files_[i] != nullptr) { 1749 if (oat_files_[i]->Flush() != 0) { 1750 PLOG(ERROR) << "Failed to flush oat file: " << oat_filenames_[i]; 1751 return false; 1752 } 1753 } 1754 1755 VLOG(compiler) << "Oat file written successfully: " << oat_filenames_[i]; 1756 1757 oat_writer.reset(); 1758 elf_writer.reset(); 1759 } 1760 } 1761 1762 return true; 1763 } 1764 1765 // If we are compiling an image, invoke the image creation routine. Else just skip. 1766 bool HandleImage() { 1767 if (IsImage()) { 1768 TimingLogger::ScopedTiming t("dex2oat ImageWriter", timings_); 1769 if (!CreateImageFile()) { 1770 return false; 1771 } 1772 VLOG(compiler) << "Images written successfully"; 1773 } 1774 return true; 1775 } 1776 1777 // Create a copy from stripped to unstripped. 1778 bool CopyStrippedToUnstripped() { 1779 for (size_t i = 0; i < oat_unstripped_.size(); ++i) { 1780 // If we don't want to strip in place, copy from stripped location to unstripped location. 1781 // We need to strip after image creation because FixupElf needs to use .strtab. 1782 if (strcmp(oat_unstripped_[i], oat_filenames_[i]) != 0) { 1783 // If the oat file is still open, flush it. 1784 if (oat_files_[i].get() != nullptr && oat_files_[i]->IsOpened()) { 1785 if (!FlushCloseOatFile(i)) { 1786 return false; 1787 } 1788 } 1789 1790 TimingLogger::ScopedTiming t("dex2oat OatFile copy", timings_); 1791 std::unique_ptr<File> in(OS::OpenFileForReading(oat_filenames_[i])); 1792 std::unique_ptr<File> out(OS::CreateEmptyFile(oat_unstripped_[i])); 1793 size_t buffer_size = 8192; 1794 std::unique_ptr<uint8_t[]> buffer(new uint8_t[buffer_size]); 1795 while (true) { 1796 int bytes_read = TEMP_FAILURE_RETRY(read(in->Fd(), buffer.get(), buffer_size)); 1797 if (bytes_read <= 0) { 1798 break; 1799 } 1800 bool write_ok = out->WriteFully(buffer.get(), bytes_read); 1801 CHECK(write_ok); 1802 } 1803 if (out->FlushCloseOrErase() != 0) { 1804 PLOG(ERROR) << "Failed to flush and close copied oat file: " << oat_unstripped_[i]; 1805 return false; 1806 } 1807 VLOG(compiler) << "Oat file copied successfully (unstripped): " << oat_unstripped_[i]; 1808 } 1809 } 1810 return true; 1811 } 1812 1813 bool FlushOatFiles() { 1814 TimingLogger::ScopedTiming t2("dex2oat Flush ELF", timings_); 1815 for (size_t i = 0; i < oat_files_.size(); ++i) { 1816 if (oat_files_[i].get() != nullptr) { 1817 if (oat_files_[i]->Flush() != 0) { 1818 PLOG(ERROR) << "Failed to flush oat file: " << oat_filenames_[i]; 1819 oat_files_[i]->Erase(); 1820 return false; 1821 } 1822 } 1823 } 1824 return true; 1825 } 1826 1827 bool FlushCloseOatFile(size_t i) { 1828 if (oat_files_[i].get() != nullptr) { 1829 std::unique_ptr<File> tmp(oat_files_[i].release()); 1830 if (tmp->FlushCloseOrErase() != 0) { 1831 PLOG(ERROR) << "Failed to flush and close oat file: " << oat_filenames_[i]; 1832 return false; 1833 } 1834 } 1835 return true; 1836 } 1837 1838 bool FlushCloseOatFiles() { 1839 bool result = true; 1840 for (size_t i = 0; i < oat_files_.size(); ++i) { 1841 result &= FlushCloseOatFile(i); 1842 } 1843 return result; 1844 } 1845 1846 void DumpTiming() { 1847 if (dump_timing_ || (dump_slow_timing_ && timings_->GetTotalNs() > MsToNs(1000))) { 1848 LOG(INFO) << Dumpable<TimingLogger>(*timings_); 1849 } 1850 if (dump_passes_) { 1851 LOG(INFO) << Dumpable<CumulativeLogger>(*driver_->GetTimingsLogger()); 1852 } 1853 } 1854 1855 bool IsImage() const { 1856 return IsAppImage() || IsBootImage(); 1857 } 1858 1859 bool IsAppImage() const { 1860 return app_image_; 1861 } 1862 1863 bool IsBootImage() const { 1864 return boot_image_; 1865 } 1866 1867 bool IsHost() const { 1868 return is_host_; 1869 } 1870 1871 bool UseProfileGuidedCompilation() const { 1872 return CompilerFilter::DependsOnProfile(compiler_options_->GetCompilerFilter()); 1873 } 1874 1875 bool LoadProfile() { 1876 DCHECK(UseProfileGuidedCompilation()); 1877 1878 profile_compilation_info_.reset(new ProfileCompilationInfo()); 1879 ScopedFlock flock; 1880 bool success = true; 1881 std::string error; 1882 if (profile_file_fd_ != -1) { 1883 // The file doesn't need to be flushed so don't check the usage. 1884 // Pass a bogus path so that we can easily attribute any reported error. 1885 File file(profile_file_fd_, "profile", /*check_usage*/ false, /*read_only_mode*/ true); 1886 if (flock.Init(&file, &error)) { 1887 success = profile_compilation_info_->Load(profile_file_fd_); 1888 } 1889 } else if (profile_file_ != "") { 1890 if (flock.Init(profile_file_.c_str(), O_RDONLY, /* block */ true, &error)) { 1891 success = profile_compilation_info_->Load(flock.GetFile()->Fd()); 1892 } 1893 } 1894 if (!error.empty()) { 1895 LOG(WARNING) << "Cannot lock profiles: " << error; 1896 } 1897 1898 if (!success) { 1899 profile_compilation_info_.reset(nullptr); 1900 } 1901 1902 return success; 1903 } 1904 1905 private: 1906 bool UseSwap(bool is_image, const std::vector<const DexFile*>& dex_files) { 1907 if (is_image) { 1908 // Don't use swap, we know generation should succeed, and we don't want to slow it down. 1909 return false; 1910 } 1911 if (dex_files.size() < min_dex_files_for_swap_) { 1912 // If there are less dex files than the threshold, assume it's gonna be fine. 1913 return false; 1914 } 1915 size_t dex_files_size = 0; 1916 for (const auto* dex_file : dex_files) { 1917 dex_files_size += dex_file->GetHeader().file_size_; 1918 } 1919 return dex_files_size >= min_dex_file_cumulative_size_for_swap_; 1920 } 1921 1922 template <typename T> 1923 static std::vector<T*> MakeNonOwningPointerVector(const std::vector<std::unique_ptr<T>>& src) { 1924 std::vector<T*> result; 1925 result.reserve(src.size()); 1926 for (const std::unique_ptr<T>& t : src) { 1927 result.push_back(t.get()); 1928 } 1929 return result; 1930 } 1931 1932 std::string GetMultiImageBootClassPath() { 1933 DCHECK(IsBootImage()); 1934 DCHECK_GT(oat_filenames_.size(), 1u); 1935 // If the image filename was adapted (e.g., for our tests), we need to change this here, 1936 // too, but need to strip all path components (they will be re-established when loading). 1937 std::ostringstream bootcp_oss; 1938 bool first_bootcp = true; 1939 for (size_t i = 0; i < dex_locations_.size(); ++i) { 1940 if (!first_bootcp) { 1941 bootcp_oss << ":"; 1942 } 1943 1944 std::string dex_loc = dex_locations_[i]; 1945 std::string image_filename = image_filenames_[i]; 1946 1947 // Use the dex_loc path, but the image_filename name (without path elements). 1948 size_t dex_last_slash = dex_loc.rfind('/'); 1949 1950 // npos is max(size_t). That makes this a bit ugly. 1951 size_t image_last_slash = image_filename.rfind('/'); 1952 size_t image_last_at = image_filename.rfind('@'); 1953 size_t image_last_sep = (image_last_slash == std::string::npos) 1954 ? image_last_at 1955 : (image_last_at == std::string::npos) 1956 ? std::string::npos 1957 : std::max(image_last_slash, image_last_at); 1958 // Note: whenever image_last_sep == npos, +1 overflow means using the full string. 1959 1960 if (dex_last_slash == std::string::npos) { 1961 dex_loc = image_filename.substr(image_last_sep + 1); 1962 } else { 1963 dex_loc = dex_loc.substr(0, dex_last_slash + 1) + 1964 image_filename.substr(image_last_sep + 1); 1965 } 1966 1967 // Image filenames already end with .art, no need to replace. 1968 1969 bootcp_oss << dex_loc; 1970 first_bootcp = false; 1971 } 1972 return bootcp_oss.str(); 1973 } 1974 1975 std::vector<std::string> GetClassPathLocations(const std::string& class_path) { 1976 // This function is used only for apps and for an app we have exactly one oat file. 1977 DCHECK(!IsBootImage()); 1978 DCHECK_EQ(oat_writers_.size(), 1u); 1979 std::vector<std::string> dex_files_canonical_locations; 1980 for (const char* location : oat_writers_[0]->GetSourceLocations()) { 1981 dex_files_canonical_locations.push_back(DexFile::GetDexCanonicalLocation(location)); 1982 } 1983 1984 std::vector<std::string> parsed; 1985 Split(class_path, ':', &parsed); 1986 auto kept_it = std::remove_if(parsed.begin(), 1987 parsed.end(), 1988 [dex_files_canonical_locations](const std::string& location) { 1989 return ContainsElement(dex_files_canonical_locations, 1990 DexFile::GetDexCanonicalLocation(location.c_str())); 1991 }); 1992 parsed.erase(kept_it, parsed.end()); 1993 return parsed; 1994 } 1995 1996 // Opens requested class path files and appends them to opened_dex_files. If the dex files have 1997 // been stripped, this opens them from their oat files and appends them to opened_oat_files. 1998 static void OpenClassPathFiles(const std::vector<std::string>& class_path_locations, 1999 std::vector<std::unique_ptr<const DexFile>>* opened_dex_files, 2000 std::vector<std::unique_ptr<OatFile>>* opened_oat_files, 2001 InstructionSet isa) { 2002 DCHECK(opened_dex_files != nullptr) << "OpenClassPathFiles dex out-param is nullptr"; 2003 DCHECK(opened_oat_files != nullptr) << "OpenClassPathFiles oat out-param is nullptr"; 2004 for (const std::string& location : class_path_locations) { 2005 // Stop early if we detect the special shared library, which may be passed as the classpath 2006 // for dex2oat when we want to skip the shared libraries check. 2007 if (location == OatFile::kSpecialSharedLibrary) { 2008 break; 2009 } 2010 std::string error_msg; 2011 if (!DexFile::Open(location.c_str(), location.c_str(), &error_msg, opened_dex_files)) { 2012 // If we fail to open the dex file because it's been stripped, try to open the dex file 2013 // from its corresponding oat file. 2014 OatFileAssistant oat_file_assistant(location.c_str(), isa, false, false); 2015 std::unique_ptr<OatFile> oat_file(oat_file_assistant.GetBestOatFile()); 2016 if (oat_file == nullptr) { 2017 LOG(WARNING) << "Failed to open dex file and associated oat file for '" << location 2018 << "': " << error_msg; 2019 } else { 2020 std::vector<std::unique_ptr<const DexFile>> oat_dex_files = 2021 oat_file_assistant.LoadDexFiles(*oat_file, location.c_str()); 2022 opened_oat_files->push_back(std::move(oat_file)); 2023 opened_dex_files->insert(opened_dex_files->end(), 2024 std::make_move_iterator(oat_dex_files.begin()), 2025 std::make_move_iterator(oat_dex_files.end())); 2026 } 2027 } 2028 } 2029 } 2030 2031 bool PrepareImageClasses() { 2032 // If --image-classes was specified, calculate the full list of classes to include in the image. 2033 if (image_classes_filename_ != nullptr) { 2034 image_classes_ = 2035 ReadClasses(image_classes_zip_filename_, image_classes_filename_, "image"); 2036 if (image_classes_ == nullptr) { 2037 return false; 2038 } 2039 } else if (IsBootImage()) { 2040 image_classes_.reset(new std::unordered_set<std::string>); 2041 } 2042 return true; 2043 } 2044 2045 bool PrepareCompiledClasses() { 2046 // If --compiled-classes was specified, calculate the full list of classes to compile in the 2047 // image. 2048 if (compiled_classes_filename_ != nullptr) { 2049 compiled_classes_ = 2050 ReadClasses(compiled_classes_zip_filename_, compiled_classes_filename_, "compiled"); 2051 if (compiled_classes_ == nullptr) { 2052 return false; 2053 } 2054 } else { 2055 compiled_classes_.reset(nullptr); // By default compile everything. 2056 } 2057 return true; 2058 } 2059 2060 static std::unique_ptr<std::unordered_set<std::string>> ReadClasses(const char* zip_filename, 2061 const char* classes_filename, 2062 const char* tag) { 2063 std::unique_ptr<std::unordered_set<std::string>> classes; 2064 std::string error_msg; 2065 if (zip_filename != nullptr) { 2066 classes.reset(ReadImageClassesFromZip(zip_filename, classes_filename, &error_msg)); 2067 } else { 2068 classes.reset(ReadImageClassesFromFile(classes_filename)); 2069 } 2070 if (classes == nullptr) { 2071 LOG(ERROR) << "Failed to create list of " << tag << " classes from '" 2072 << classes_filename << "': " << error_msg; 2073 } 2074 return classes; 2075 } 2076 2077 bool PrepareCompiledMethods() { 2078 // If --compiled-methods was specified, read the methods to compile from the given file(s). 2079 if (compiled_methods_filename_ != nullptr) { 2080 std::string error_msg; 2081 if (compiled_methods_zip_filename_ != nullptr) { 2082 compiled_methods_.reset(ReadCommentedInputFromZip(compiled_methods_zip_filename_, 2083 compiled_methods_filename_, 2084 nullptr, // No post-processing. 2085 &error_msg)); 2086 } else { 2087 compiled_methods_.reset(ReadCommentedInputFromFile(compiled_methods_filename_, 2088 nullptr)); // No post-processing. 2089 } 2090 if (compiled_methods_.get() == nullptr) { 2091 LOG(ERROR) << "Failed to create list of compiled methods from '" 2092 << compiled_methods_filename_ << "': " << error_msg; 2093 return false; 2094 } 2095 } else { 2096 compiled_methods_.reset(nullptr); // By default compile everything. 2097 } 2098 return true; 2099 } 2100 2101 void PruneNonExistentDexFiles() { 2102 DCHECK_EQ(dex_filenames_.size(), dex_locations_.size()); 2103 size_t kept = 0u; 2104 for (size_t i = 0, size = dex_filenames_.size(); i != size; ++i) { 2105 if (!OS::FileExists(dex_filenames_[i])) { 2106 LOG(WARNING) << "Skipping non-existent dex file '" << dex_filenames_[i] << "'"; 2107 } else { 2108 dex_filenames_[kept] = dex_filenames_[i]; 2109 dex_locations_[kept] = dex_locations_[i]; 2110 ++kept; 2111 } 2112 } 2113 dex_filenames_.resize(kept); 2114 dex_locations_.resize(kept); 2115 } 2116 2117 bool AddDexFileSources() { 2118 TimingLogger::ScopedTiming t2("AddDexFileSources", timings_); 2119 if (zip_fd_ != -1) { 2120 DCHECK_EQ(oat_writers_.size(), 1u); 2121 if (!oat_writers_[0]->AddZippedDexFilesSource(ScopedFd(zip_fd_), zip_location_.c_str())) { 2122 return false; 2123 } 2124 } else if (oat_writers_.size() > 1u) { 2125 // Multi-image. 2126 DCHECK_EQ(oat_writers_.size(), dex_filenames_.size()); 2127 DCHECK_EQ(oat_writers_.size(), dex_locations_.size()); 2128 for (size_t i = 0, size = oat_writers_.size(); i != size; ++i) { 2129 if (!oat_writers_[i]->AddDexFileSource(dex_filenames_[i], dex_locations_[i])) { 2130 return false; 2131 } 2132 } 2133 } else { 2134 DCHECK_EQ(oat_writers_.size(), 1u); 2135 DCHECK_EQ(dex_filenames_.size(), dex_locations_.size()); 2136 DCHECK_NE(dex_filenames_.size(), 0u); 2137 for (size_t i = 0; i != dex_filenames_.size(); ++i) { 2138 if (!oat_writers_[0]->AddDexFileSource(dex_filenames_[i], dex_locations_[i])) { 2139 return false; 2140 } 2141 } 2142 } 2143 return true; 2144 } 2145 2146 void CreateOatWriters() { 2147 TimingLogger::ScopedTiming t2("CreateOatWriters", timings_); 2148 elf_writers_.reserve(oat_files_.size()); 2149 oat_writers_.reserve(oat_files_.size()); 2150 for (const std::unique_ptr<File>& oat_file : oat_files_) { 2151 elf_writers_.emplace_back(CreateElfWriterQuick(instruction_set_, 2152 instruction_set_features_.get(), 2153 compiler_options_.get(), 2154 oat_file.get())); 2155 elf_writers_.back()->Start(); 2156 oat_writers_.emplace_back(new OatWriter(IsBootImage(), timings_)); 2157 } 2158 } 2159 2160 void SaveDexInput() { 2161 for (size_t i = 0; i < dex_files_.size(); ++i) { 2162 const DexFile* dex_file = dex_files_[i]; 2163 std::string tmp_file_name(StringPrintf("/data/local/tmp/dex2oat.%d.%zd.dex", 2164 getpid(), i)); 2165 std::unique_ptr<File> tmp_file(OS::CreateEmptyFile(tmp_file_name.c_str())); 2166 if (tmp_file.get() == nullptr) { 2167 PLOG(ERROR) << "Failed to open file " << tmp_file_name 2168 << ". Try: adb shell chmod 777 /data/local/tmp"; 2169 continue; 2170 } 2171 // This is just dumping files for debugging. Ignore errors, and leave remnants. 2172 UNUSED(tmp_file->WriteFully(dex_file->Begin(), dex_file->Size())); 2173 UNUSED(tmp_file->Flush()); 2174 UNUSED(tmp_file->Close()); 2175 LOG(INFO) << "Wrote input to " << tmp_file_name; 2176 } 2177 } 2178 2179 bool PrepareRuntimeOptions(RuntimeArgumentMap* runtime_options) { 2180 RuntimeOptions raw_options; 2181 if (boot_image_filename_.empty()) { 2182 std::string boot_class_path = "-Xbootclasspath:"; 2183 boot_class_path += Join(dex_filenames_, ':'); 2184 raw_options.push_back(std::make_pair(boot_class_path, nullptr)); 2185 std::string boot_class_path_locations = "-Xbootclasspath-locations:"; 2186 boot_class_path_locations += Join(dex_locations_, ':'); 2187 raw_options.push_back(std::make_pair(boot_class_path_locations, nullptr)); 2188 } else { 2189 std::string boot_image_option = "-Ximage:"; 2190 boot_image_option += boot_image_filename_; 2191 raw_options.push_back(std::make_pair(boot_image_option, nullptr)); 2192 } 2193 for (size_t i = 0; i < runtime_args_.size(); i++) { 2194 raw_options.push_back(std::make_pair(runtime_args_[i], nullptr)); 2195 } 2196 2197 raw_options.push_back(std::make_pair("compilercallbacks", callbacks_.get())); 2198 raw_options.push_back( 2199 std::make_pair("imageinstructionset", GetInstructionSetString(instruction_set_))); 2200 2201 // Only allow no boot image for the runtime if we're compiling one. When we compile an app, 2202 // we don't want fallback mode, it will abort as we do not push a boot classpath (it might 2203 // have been stripped in preopting, anyways). 2204 if (!IsBootImage()) { 2205 raw_options.push_back(std::make_pair("-Xno-dex-file-fallback", nullptr)); 2206 } 2207 // Disable libsigchain. We don't don't need it during compilation and it prevents us 2208 // from getting a statically linked version of dex2oat (because of dlsym and RTLD_NEXT). 2209 raw_options.push_back(std::make_pair("-Xno-sig-chain", nullptr)); 2210 // Disable Hspace compaction to save heap size virtual space. 2211 // Only need disable Hspace for OOM becasue background collector is equal to 2212 // foreground collector by default for dex2oat. 2213 raw_options.push_back(std::make_pair("-XX:DisableHSpaceCompactForOOM", nullptr)); 2214 2215 // If we're asked to be deterministic, ensure non-concurrent GC for determinism. Also 2216 // force the free-list implementation for large objects. 2217 if (compiler_options_->IsForceDeterminism()) { 2218 raw_options.push_back(std::make_pair("-Xgc:nonconcurrent", nullptr)); 2219 raw_options.push_back(std::make_pair("-XX:LargeObjectSpace=freelist", nullptr)); 2220 2221 // We also need to turn off the nonmoving space. For that, we need to disable HSpace 2222 // compaction (done above) and ensure that neither foreground nor background collectors 2223 // are concurrent. 2224 raw_options.push_back(std::make_pair("-XX:BackgroundGC=nonconcurrent", nullptr)); 2225 2226 // To make identity hashcode deterministic, set a known seed. 2227 mirror::Object::SetHashCodeSeed(987654321U); 2228 } 2229 2230 if (!Runtime::ParseOptions(raw_options, false, runtime_options)) { 2231 LOG(ERROR) << "Failed to parse runtime options"; 2232 return false; 2233 } 2234 return true; 2235 } 2236 2237 // Create a runtime necessary for compilation. 2238 bool CreateRuntime(RuntimeArgumentMap&& runtime_options) { 2239 TimingLogger::ScopedTiming t_runtime("Create runtime", timings_); 2240 if (!Runtime::Create(std::move(runtime_options))) { 2241 LOG(ERROR) << "Failed to create runtime"; 2242 return false; 2243 } 2244 runtime_.reset(Runtime::Current()); 2245 runtime_->SetInstructionSet(instruction_set_); 2246 for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) { 2247 Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i); 2248 if (!runtime_->HasCalleeSaveMethod(type)) { 2249 runtime_->SetCalleeSaveMethod(runtime_->CreateCalleeSaveMethod(), type); 2250 } 2251 } 2252 runtime_->GetClassLinker()->FixupDexCaches(runtime_->GetResolutionMethod()); 2253 2254 // Initialize maps for unstarted runtime. This needs to be here, as running clinits needs this 2255 // set up. 2256 interpreter::UnstartedRuntime::Initialize(); 2257 2258 runtime_->GetClassLinker()->RunRootClinits(); 2259 2260 // Runtime::Create acquired the mutator_lock_ that is normally given away when we 2261 // Runtime::Start, give it away now so that we don't starve GC. 2262 Thread* self = Thread::Current(); 2263 self->TransitionFromRunnableToSuspended(kNative); 2264 2265 return true; 2266 } 2267 2268 // Let the ImageWriter write the image files. If we do not compile PIC, also fix up the oat files. 2269 bool CreateImageFile() 2270 REQUIRES(!Locks::mutator_lock_) { 2271 CHECK(image_writer_ != nullptr); 2272 if (!IsBootImage()) { 2273 CHECK(image_filenames_.empty()); 2274 image_filenames_.push_back(app_image_file_name_.c_str()); 2275 } 2276 if (!image_writer_->Write(app_image_fd_, 2277 image_filenames_, 2278 oat_filenames_)) { 2279 LOG(ERROR) << "Failure during image file creation"; 2280 return false; 2281 } 2282 2283 // We need the OatDataBegin entries. 2284 dchecked_vector<uintptr_t> oat_data_begins; 2285 for (size_t i = 0, size = oat_filenames_.size(); i != size; ++i) { 2286 oat_data_begins.push_back(image_writer_->GetOatDataBegin(i)); 2287 } 2288 // Destroy ImageWriter before doing FixupElf. 2289 image_writer_.reset(); 2290 2291 for (size_t i = 0, size = oat_filenames_.size(); i != size; ++i) { 2292 const char* oat_filename = oat_filenames_[i]; 2293 // Do not fix up the ELF file if we are --compile-pic or compiling the app image 2294 if (!compiler_options_->GetCompilePic() && IsBootImage()) { 2295 std::unique_ptr<File> oat_file(OS::OpenFileReadWrite(oat_filename)); 2296 if (oat_file.get() == nullptr) { 2297 PLOG(ERROR) << "Failed to open ELF file: " << oat_filename; 2298 return false; 2299 } 2300 2301 if (!ElfWriter::Fixup(oat_file.get(), oat_data_begins[i])) { 2302 oat_file->Erase(); 2303 LOG(ERROR) << "Failed to fixup ELF file " << oat_file->GetPath(); 2304 return false; 2305 } 2306 2307 if (oat_file->FlushCloseOrErase()) { 2308 PLOG(ERROR) << "Failed to flush and close fixed ELF file " << oat_file->GetPath(); 2309 return false; 2310 } 2311 } 2312 } 2313 2314 return true; 2315 } 2316 2317 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;) 2318 static std::unordered_set<std::string>* ReadImageClassesFromFile( 2319 const char* image_classes_filename) { 2320 std::function<std::string(const char*)> process = DotToDescriptor; 2321 return ReadCommentedInputFromFile(image_classes_filename, &process); 2322 } 2323 2324 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;) 2325 static std::unordered_set<std::string>* ReadImageClassesFromZip( 2326 const char* zip_filename, 2327 const char* image_classes_filename, 2328 std::string* error_msg) { 2329 std::function<std::string(const char*)> process = DotToDescriptor; 2330 return ReadCommentedInputFromZip(zip_filename, image_classes_filename, &process, error_msg); 2331 } 2332 2333 // Read lines from the given file, dropping comments and empty lines. Post-process each line with 2334 // the given function. 2335 static std::unordered_set<std::string>* ReadCommentedInputFromFile( 2336 const char* input_filename, std::function<std::string(const char*)>* process) { 2337 std::unique_ptr<std::ifstream> input_file(new std::ifstream(input_filename, std::ifstream::in)); 2338 if (input_file.get() == nullptr) { 2339 LOG(ERROR) << "Failed to open input file " << input_filename; 2340 return nullptr; 2341 } 2342 std::unique_ptr<std::unordered_set<std::string>> result( 2343 ReadCommentedInputStream(*input_file, process)); 2344 input_file->close(); 2345 return result.release(); 2346 } 2347 2348 // Read lines from the given file from the given zip file, dropping comments and empty lines. 2349 // Post-process each line with the given function. 2350 static std::unordered_set<std::string>* ReadCommentedInputFromZip( 2351 const char* zip_filename, 2352 const char* input_filename, 2353 std::function<std::string(const char*)>* process, 2354 std::string* error_msg) { 2355 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::Open(zip_filename, error_msg)); 2356 if (zip_archive.get() == nullptr) { 2357 return nullptr; 2358 } 2359 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(input_filename, error_msg)); 2360 if (zip_entry.get() == nullptr) { 2361 *error_msg = StringPrintf("Failed to find '%s' within '%s': %s", input_filename, 2362 zip_filename, error_msg->c_str()); 2363 return nullptr; 2364 } 2365 std::unique_ptr<MemMap> input_file(zip_entry->ExtractToMemMap(zip_filename, 2366 input_filename, 2367 error_msg)); 2368 if (input_file.get() == nullptr) { 2369 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", input_filename, 2370 zip_filename, error_msg->c_str()); 2371 return nullptr; 2372 } 2373 const std::string input_string(reinterpret_cast<char*>(input_file->Begin()), 2374 input_file->Size()); 2375 std::istringstream input_stream(input_string); 2376 return ReadCommentedInputStream(input_stream, process); 2377 } 2378 2379 // Read lines from the given stream, dropping comments and empty lines. Post-process each line 2380 // with the given function. 2381 static std::unordered_set<std::string>* ReadCommentedInputStream( 2382 std::istream& in_stream, 2383 std::function<std::string(const char*)>* process) { 2384 std::unique_ptr<std::unordered_set<std::string>> image_classes( 2385 new std::unordered_set<std::string>); 2386 while (in_stream.good()) { 2387 std::string dot; 2388 std::getline(in_stream, dot); 2389 if (StartsWith(dot, "#") || dot.empty()) { 2390 continue; 2391 } 2392 if (process != nullptr) { 2393 std::string descriptor((*process)(dot.c_str())); 2394 image_classes->insert(descriptor); 2395 } else { 2396 image_classes->insert(dot); 2397 } 2398 } 2399 return image_classes.release(); 2400 } 2401 2402 void LogCompletionTime() { 2403 // Note: when creation of a runtime fails, e.g., when trying to compile an app but when there 2404 // is no image, there won't be a Runtime::Current(). 2405 // Note: driver creation can fail when loading an invalid dex file. 2406 LOG(INFO) << "dex2oat took " << PrettyDuration(NanoTime() - start_ns_) 2407 << " (threads: " << thread_count_ << ") " 2408 << ((Runtime::Current() != nullptr && driver_ != nullptr) ? 2409 driver_->GetMemoryUsageString(kIsDebugBuild || VLOG_IS_ON(compiler)) : 2410 ""); 2411 } 2412 2413 std::string StripIsaFrom(const char* image_filename, InstructionSet isa) { 2414 std::string res(image_filename); 2415 size_t last_slash = res.rfind('/'); 2416 if (last_slash == std::string::npos || last_slash == 0) { 2417 return res; 2418 } 2419 size_t penultimate_slash = res.rfind('/', last_slash - 1); 2420 if (penultimate_slash == std::string::npos) { 2421 return res; 2422 } 2423 // Check that the string in-between is the expected one. 2424 if (res.substr(penultimate_slash + 1, last_slash - penultimate_slash - 1) != 2425 GetInstructionSetString(isa)) { 2426 LOG(WARNING) << "Unexpected string when trying to strip isa: " << res; 2427 return res; 2428 } 2429 return res.substr(0, penultimate_slash) + res.substr(last_slash); 2430 } 2431 2432 std::unique_ptr<CompilerOptions> compiler_options_; 2433 Compiler::Kind compiler_kind_; 2434 2435 InstructionSet instruction_set_; 2436 std::unique_ptr<const InstructionSetFeatures> instruction_set_features_; 2437 2438 uint32_t image_file_location_oat_checksum_; 2439 uintptr_t image_file_location_oat_data_begin_; 2440 int32_t image_patch_delta_; 2441 std::unique_ptr<SafeMap<std::string, std::string> > key_value_store_; 2442 2443 std::unique_ptr<VerificationResults> verification_results_; 2444 2445 DexFileToMethodInlinerMap method_inliner_map_; 2446 std::unique_ptr<QuickCompilerCallbacks> callbacks_; 2447 2448 std::unique_ptr<Runtime> runtime_; 2449 2450 // Ownership for the class path files. 2451 std::vector<std::unique_ptr<const DexFile>> class_path_files_; 2452 2453 size_t thread_count_; 2454 uint64_t start_ns_; 2455 std::unique_ptr<WatchDog> watchdog_; 2456 std::vector<std::unique_ptr<File>> oat_files_; 2457 std::string oat_location_; 2458 std::vector<const char*> oat_filenames_; 2459 std::vector<const char*> oat_unstripped_; 2460 int oat_fd_; 2461 std::vector<const char*> dex_filenames_; 2462 std::vector<const char*> dex_locations_; 2463 int zip_fd_; 2464 std::string zip_location_; 2465 std::string boot_image_filename_; 2466 std::vector<const char*> runtime_args_; 2467 std::vector<const char*> image_filenames_; 2468 uintptr_t image_base_; 2469 const char* image_classes_zip_filename_; 2470 const char* image_classes_filename_; 2471 ImageHeader::StorageMode image_storage_mode_; 2472 const char* compiled_classes_zip_filename_; 2473 const char* compiled_classes_filename_; 2474 const char* compiled_methods_zip_filename_; 2475 const char* compiled_methods_filename_; 2476 std::unique_ptr<std::unordered_set<std::string>> image_classes_; 2477 std::unique_ptr<std::unordered_set<std::string>> compiled_classes_; 2478 std::unique_ptr<std::unordered_set<std::string>> compiled_methods_; 2479 bool app_image_; 2480 bool boot_image_; 2481 bool multi_image_; 2482 bool is_host_; 2483 std::string android_root_; 2484 // Dex files we are compiling, does not include the class path dex files. 2485 std::vector<const DexFile*> dex_files_; 2486 std::string no_inline_from_string_; 2487 std::vector<jobject> dex_caches_; 2488 jobject class_loader_; 2489 2490 std::vector<std::unique_ptr<ElfWriter>> elf_writers_; 2491 std::vector<std::unique_ptr<OatWriter>> oat_writers_; 2492 std::vector<OutputStream*> rodata_; 2493 std::unique_ptr<ImageWriter> image_writer_; 2494 std::unique_ptr<CompilerDriver> driver_; 2495 2496 std::vector<std::unique_ptr<MemMap>> opened_dex_files_maps_; 2497 std::vector<std::unique_ptr<OatFile>> opened_oat_files_; 2498 std::vector<std::unique_ptr<const DexFile>> opened_dex_files_; 2499 2500 std::vector<const DexFile*> no_inline_from_dex_files_; 2501 2502 std::vector<std::string> verbose_methods_; 2503 bool dump_stats_; 2504 bool dump_passes_; 2505 bool dump_timing_; 2506 bool dump_slow_timing_; 2507 std::string swap_file_name_; 2508 int swap_fd_; 2509 size_t min_dex_files_for_swap_ = kDefaultMinDexFilesForSwap; 2510 size_t min_dex_file_cumulative_size_for_swap_ = kDefaultMinDexFileCumulativeSizeForSwap; 2511 std::string app_image_file_name_; 2512 int app_image_fd_; 2513 std::string profile_file_; 2514 int profile_file_fd_; 2515 std::unique_ptr<ProfileCompilationInfo> profile_compilation_info_; 2516 TimingLogger* timings_; 2517 std::unique_ptr<CumulativeLogger> compiler_phases_timings_; 2518 std::vector<std::vector<const DexFile*>> dex_files_per_oat_file_; 2519 std::unordered_map<const DexFile*, size_t> dex_file_oat_index_map_; 2520 2521 // Backing storage. 2522 std::vector<std::string> char_backing_storage_; 2523 2524 // See CompilerOptions.force_determinism_. 2525 bool force_determinism_; 2526 2527 DISALLOW_IMPLICIT_CONSTRUCTORS(Dex2Oat); 2528}; 2529 2530static void b13564922() { 2531#if defined(__linux__) && defined(__arm__) 2532 int major, minor; 2533 struct utsname uts; 2534 if (uname(&uts) != -1 && 2535 sscanf(uts.release, "%d.%d", &major, &minor) == 2 && 2536 ((major < 3) || ((major == 3) && (minor < 4)))) { 2537 // Kernels before 3.4 don't handle the ASLR well and we can run out of address 2538 // space (http://b/13564922). Work around the issue by inhibiting further mmap() randomization. 2539 int old_personality = personality(0xffffffff); 2540 if ((old_personality & ADDR_NO_RANDOMIZE) == 0) { 2541 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE); 2542 if (new_personality == -1) { 2543 LOG(WARNING) << "personality(. | ADDR_NO_RANDOMIZE) failed."; 2544 } 2545 } 2546 } 2547#endif 2548} 2549 2550static int CompileImage(Dex2Oat& dex2oat) { 2551 dex2oat.LoadClassProfileDescriptors(); 2552 dex2oat.Compile(); 2553 2554 if (!dex2oat.WriteOatFiles()) { 2555 dex2oat.EraseOatFiles(); 2556 return EXIT_FAILURE; 2557 } 2558 2559 // Flush boot.oat. We always expect the output file by name, and it will be re-opened from the 2560 // unstripped name. Do not close the file if we are compiling the image with an oat fd since the 2561 // image writer will require this fd to generate the image. 2562 if (dex2oat.ShouldKeepOatFileOpen()) { 2563 if (!dex2oat.FlushOatFiles()) { 2564 return EXIT_FAILURE; 2565 } 2566 } else if (!dex2oat.FlushCloseOatFiles()) { 2567 return EXIT_FAILURE; 2568 } 2569 2570 // Creates the boot.art and patches the oat files. 2571 if (!dex2oat.HandleImage()) { 2572 return EXIT_FAILURE; 2573 } 2574 2575 // When given --host, finish early without stripping. 2576 if (dex2oat.IsHost()) { 2577 dex2oat.DumpTiming(); 2578 return EXIT_SUCCESS; 2579 } 2580 2581 // Copy stripped to unstripped location, if necessary. 2582 if (!dex2oat.CopyStrippedToUnstripped()) { 2583 return EXIT_FAILURE; 2584 } 2585 2586 // FlushClose again, as stripping might have re-opened the oat files. 2587 if (!dex2oat.FlushCloseOatFiles()) { 2588 return EXIT_FAILURE; 2589 } 2590 2591 dex2oat.DumpTiming(); 2592 return EXIT_SUCCESS; 2593} 2594 2595static int CompileApp(Dex2Oat& dex2oat) { 2596 dex2oat.Compile(); 2597 2598 if (!dex2oat.WriteOatFiles()) { 2599 dex2oat.EraseOatFiles(); 2600 return EXIT_FAILURE; 2601 } 2602 2603 // Do not close the oat files here. We might have gotten the output file by file descriptor, 2604 // which we would lose. 2605 2606 // When given --host, finish early without stripping. 2607 if (dex2oat.IsHost()) { 2608 if (!dex2oat.FlushCloseOatFiles()) { 2609 return EXIT_FAILURE; 2610 } 2611 2612 dex2oat.DumpTiming(); 2613 return EXIT_SUCCESS; 2614 } 2615 2616 // Copy stripped to unstripped location, if necessary. This will implicitly flush & close the 2617 // stripped versions. If this is given, we expect to be able to open writable files by name. 2618 if (!dex2oat.CopyStrippedToUnstripped()) { 2619 return EXIT_FAILURE; 2620 } 2621 2622 // Flush and close the files. 2623 if (!dex2oat.FlushCloseOatFiles()) { 2624 return EXIT_FAILURE; 2625 } 2626 2627 dex2oat.DumpTiming(); 2628 return EXIT_SUCCESS; 2629} 2630 2631static int dex2oat(int argc, char** argv) { 2632 b13564922(); 2633 2634 TimingLogger timings("compiler", false, false); 2635 2636 // Allocate `dex2oat` on the heap instead of on the stack, as Clang 2637 // might produce a stack frame too large for this function or for 2638 // functions inlining it (such as main), that would not fit the 2639 // requirements of the `-Wframe-larger-than` option. 2640 std::unique_ptr<Dex2Oat> dex2oat = MakeUnique<Dex2Oat>(&timings); 2641 2642 // Parse arguments. Argument mistakes will lead to exit(EXIT_FAILURE) in UsageError. 2643 dex2oat->ParseArgs(argc, argv); 2644 2645 // If needed, process profile information for profile guided compilation. 2646 // This operation involves I/O. 2647 if (dex2oat->UseProfileGuidedCompilation()) { 2648 if (!dex2oat->LoadProfile()) { 2649 LOG(ERROR) << "Failed to process profile file"; 2650 return EXIT_FAILURE; 2651 } 2652 } 2653 2654 // Check early that the result of compilation can be written 2655 if (!dex2oat->OpenFile()) { 2656 return EXIT_FAILURE; 2657 } 2658 2659 // Print the complete line when any of the following is true: 2660 // 1) Debug build 2661 // 2) Compiling an image 2662 // 3) Compiling with --host 2663 // 4) Compiling on the host (not a target build) 2664 // Otherwise, print a stripped command line. 2665 if (kIsDebugBuild || dex2oat->IsBootImage() || dex2oat->IsHost() || !kIsTargetBuild) { 2666 LOG(INFO) << CommandLine(); 2667 } else { 2668 LOG(INFO) << StrippedCommandLine(); 2669 } 2670 2671 if (!dex2oat->Setup()) { 2672 dex2oat->EraseOatFiles(); 2673 return EXIT_FAILURE; 2674 } 2675 2676 bool result; 2677 if (dex2oat->IsImage()) { 2678 result = CompileImage(*dex2oat); 2679 } else { 2680 result = CompileApp(*dex2oat); 2681 } 2682 2683 dex2oat->Shutdown(); 2684 return result; 2685} 2686} // namespace art 2687 2688int main(int argc, char** argv) { 2689 int result = art::dex2oat(argc, argv); 2690 // Everything was done, do an explicit exit here to avoid running Runtime destructors that take 2691 // time (bug 10645725) unless we're a debug build or running on valgrind. Note: The Dex2Oat class 2692 // should not destruct the runtime in this case. 2693 if (!art::kIsDebugBuild && (RUNNING_ON_MEMORY_TOOL == 0)) { 2694 exit(result); 2695 } 2696 return result; 2697} 2698