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