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