dex2oat.cc revision 8d26c5967674d2eab21f65eeac9f1adcf88fce38
1/* 2 * Copyright (C) 2011 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17#include <inttypes.h> 18#include <stdio.h> 19#include <stdlib.h> 20#include <sys/stat.h> 21#include "base/memory_tool.h" 22 23#include <fstream> 24#include <iostream> 25#include <sstream> 26#include <string> 27#include <unordered_set> 28#include <vector> 29 30#if defined(__linux__) && defined(__arm__) 31#include <sys/personality.h> 32#include <sys/utsname.h> 33#endif 34 35#include "arch/instruction_set_features.h" 36#include "arch/mips/instruction_set_features_mips.h" 37#include "art_method-inl.h" 38#include "base/dumpable.h" 39#include "base/macros.h" 40#include "base/scoped_flock.h" 41#include "base/stl_util.h" 42#include "base/stringpiece.h" 43#include "base/time_utils.h" 44#include "base/timing_logger.h" 45#include "base/unix_file/fd_file.h" 46#include "class_linker.h" 47#include "compiler.h" 48#include "compiler_callbacks.h" 49#include "debug/elf_debug_writer.h" 50#include "debug/method_debug_info.h" 51#include "dex/quick/dex_file_to_method_inliner_map.h" 52#include "dex/quick_compiler_callbacks.h" 53#include "dex/verification_results.h" 54#include "dex_file-inl.h" 55#include "driver/compiler_driver.h" 56#include "driver/compiler_options.h" 57#include "elf_file.h" 58#include "elf_writer.h" 59#include "elf_writer_quick.h" 60#include "gc/space/image_space.h" 61#include "gc/space/space-inl.h" 62#include "image_writer.h" 63#include "interpreter/unstarted_runtime.h" 64#include "jit/offline_profiling_info.h" 65#include "leb128.h" 66#include "linker/multi_oat_relative_patcher.h" 67#include "mirror/class-inl.h" 68#include "mirror/class_loader.h" 69#include "mirror/object-inl.h" 70#include "mirror/object_array-inl.h" 71#include "oat_file_assistant.h" 72#include "oat_writer.h" 73#include "os.h" 74#include "runtime.h" 75#include "runtime_options.h" 76#include "ScopedLocalRef.h" 77#include "scoped_thread_state_change.h" 78#include "utils.h" 79#include "well_known_classes.h" 80#include "zip_archive.h" 81 82namespace art { 83 84static int original_argc; 85static char** original_argv; 86 87static 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). 98static 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 158static void UsageErrorV(const char* fmt, va_list ap) { 159 std::string error; 160 StringAppendV(&error, fmt, ap); 161 LOG(ERROR) << error; 162} 163 164static void UsageError(const char* fmt, ...) { 165 va_list ap; 166 va_start(ap, fmt); 167 UsageErrorV(fmt, ap); 168 va_end(ap); 169} 170 171NO_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@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@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. 374class 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 476static constexpr size_t kMinDexFilesForSwap = 2; 477static constexpr size_t kMinDexFileCumulativeSizeForSwap = 20 * MB; 478 479static 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 495class 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 // If we use a swap file, ensure we are above the threshold to make it necessary. 1236 if (swap_fd_ != -1) { 1237 if (!UseSwap(IsBootImage(), dex_files_)) { 1238 close(swap_fd_); 1239 swap_fd_ = -1; 1240 VLOG(compiler) << "Decided to run without swap."; 1241 } else { 1242 LOG(INFO) << "Large app, accepted running with swap."; 1243 } 1244 } 1245 // Note that dex2oat won't close the swap_fd_. The compiler driver's swap space will do that. 1246 1247 return true; 1248 } 1249 1250 void EraseOatFiles() { 1251 for (size_t i = 0; i < oat_files_.size(); ++i) { 1252 DCHECK(oat_files_[i].get() != nullptr); 1253 oat_files_[i]->Erase(); 1254 oat_files_[i].reset(); 1255 } 1256 } 1257 1258 void Shutdown() { 1259 ScopedObjectAccess soa(Thread::Current()); 1260 for (jobject dex_cache : dex_caches_) { 1261 soa.Env()->DeleteLocalRef(dex_cache); 1262 } 1263 dex_caches_.clear(); 1264 } 1265 1266 void LoadClassProfileDescriptors() { 1267 if (profile_compilation_info_ != nullptr && app_image_) { 1268 Runtime* runtime = Runtime::Current(); 1269 CHECK(runtime != nullptr); 1270 std::set<DexCacheResolvedClasses> resolved_classes( 1271 profile_compilation_info_->GetResolvedClasses()); 1272 1273 // Filter out class path classes since we don't want to include these in the image. 1274 std::unordered_set<std::string> dex_files_locations; 1275 for (const DexFile* dex_file : dex_files_) { 1276 dex_files_locations.insert(dex_file->GetLocation()); 1277 } 1278 for (auto it = resolved_classes.begin(); it != resolved_classes.end(); ) { 1279 if (dex_files_locations.find(it->GetDexLocation()) == dex_files_locations.end()) { 1280 VLOG(compiler) << "Removed profile samples for non-app dex file " << it->GetDexLocation(); 1281 it = resolved_classes.erase(it); 1282 } else { 1283 ++it; 1284 } 1285 } 1286 1287 image_classes_.reset(new std::unordered_set<std::string>( 1288 runtime->GetClassLinker()->GetClassDescriptorsForProfileKeys(resolved_classes))); 1289 VLOG(compiler) << "Loaded " << image_classes_->size() 1290 << " image class descriptors from profile"; 1291 if (VLOG_IS_ON(compiler)) { 1292 for (const std::string& s : *image_classes_) { 1293 LOG(INFO) << "Image class " << s; 1294 } 1295 } 1296 } 1297 } 1298 1299 // Set up the environment for compilation. Includes starting the runtime and loading/opening the 1300 // boot class path. 1301 bool Setup() { 1302 TimingLogger::ScopedTiming t("dex2oat Setup", timings_); 1303 art::MemMap::Init(); // For ZipEntry::ExtractToMemMap. 1304 1305 if (!PrepareImageClasses() || !PrepareCompiledClasses() || !PrepareCompiledMethods()) { 1306 return false; 1307 } 1308 1309 verification_results_.reset(new VerificationResults(compiler_options_.get())); 1310 callbacks_.reset(new QuickCompilerCallbacks( 1311 verification_results_.get(), 1312 &method_inliner_map_, 1313 IsBootImage() ? 1314 CompilerCallbacks::CallbackMode::kCompileBootImage : 1315 CompilerCallbacks::CallbackMode::kCompileApp)); 1316 1317 RuntimeArgumentMap runtime_options; 1318 if (!PrepareRuntimeOptions(&runtime_options)) { 1319 return false; 1320 } 1321 1322 CreateOatWriters(); 1323 if (!AddDexFileSources()) { 1324 return false; 1325 } 1326 1327 if (IsBootImage() && image_filenames_.size() > 1) { 1328 // If we're compiling the boot image, store the boot classpath into the Key-Value store. 1329 // We need this for the multi-image case. 1330 key_value_store_->Put(OatHeader::kBootClassPathKey, GetMultiImageBootClassPath()); 1331 } 1332 1333 if (!IsBootImage()) { 1334 // When compiling an app, create the runtime early to retrieve 1335 // the image location key needed for the oat header. 1336 if (!CreateRuntime(std::move(runtime_options))) { 1337 return false; 1338 } 1339 1340 if (CompilerFilter::DependsOnImageChecksum(compiler_options_->GetCompilerFilter())) { 1341 TimingLogger::ScopedTiming t3("Loading image checksum", timings_); 1342 std::vector<gc::space::ImageSpace*> image_spaces = 1343 Runtime::Current()->GetHeap()->GetBootImageSpaces(); 1344 image_file_location_oat_checksum_ = OatFileAssistant::CalculateCombinedImageChecksum(); 1345 image_file_location_oat_data_begin_ = 1346 reinterpret_cast<uintptr_t>(image_spaces[0]->GetImageHeader().GetOatDataBegin()); 1347 image_patch_delta_ = image_spaces[0]->GetImageHeader().GetPatchDelta(); 1348 // Store the boot image filename(s). 1349 std::vector<std::string> image_filenames; 1350 for (const gc::space::ImageSpace* image_space : image_spaces) { 1351 image_filenames.push_back(image_space->GetImageFilename()); 1352 } 1353 std::string image_file_location = Join(image_filenames, ':'); 1354 if (!image_file_location.empty()) { 1355 key_value_store_->Put(OatHeader::kImageLocationKey, image_file_location); 1356 } 1357 } else { 1358 image_file_location_oat_checksum_ = 0u; 1359 image_file_location_oat_data_begin_ = 0u; 1360 image_patch_delta_ = 0; 1361 } 1362 1363 // Open dex files for class path. 1364 const std::vector<std::string> class_path_locations = 1365 GetClassPathLocations(runtime_->GetClassPathString()); 1366 OpenClassPathFiles(class_path_locations, 1367 &class_path_files_, 1368 &opened_oat_files_, 1369 runtime_->GetInstructionSet()); 1370 1371 // Store the classpath we have right now. 1372 std::vector<const DexFile*> class_path_files = MakeNonOwningPointerVector(class_path_files_); 1373 std::string encoded_class_path; 1374 if (class_path_locations.size() == 1 && 1375 class_path_locations[0] == OatFile::kSpecialSharedLibrary) { 1376 // When passing the special shared library as the classpath, it is the only path. 1377 encoded_class_path = OatFile::kSpecialSharedLibrary; 1378 } else { 1379 encoded_class_path = OatFile::EncodeDexFileDependencies(class_path_files); 1380 } 1381 key_value_store_->Put(OatHeader::kClassPathKey, encoded_class_path); 1382 } 1383 1384 // Now that we have finalized key_value_store_, start writing the oat file. 1385 { 1386 TimingLogger::ScopedTiming t_dex("Writing and opening dex files", timings_); 1387 rodata_.reserve(oat_writers_.size()); 1388 for (size_t i = 0, size = oat_writers_.size(); i != size; ++i) { 1389 rodata_.push_back(elf_writers_[i]->StartRoData()); 1390 // Unzip or copy dex files straight to the oat file. 1391 std::unique_ptr<MemMap> opened_dex_files_map; 1392 std::vector<std::unique_ptr<const DexFile>> opened_dex_files; 1393 if (!oat_writers_[i]->WriteAndOpenDexFiles(rodata_.back(), 1394 oat_files_[i].get(), 1395 instruction_set_, 1396 instruction_set_features_.get(), 1397 key_value_store_.get(), 1398 /* verify */ true, 1399 &opened_dex_files_map, 1400 &opened_dex_files)) { 1401 return false; 1402 } 1403 dex_files_per_oat_file_.push_back(MakeNonOwningPointerVector(opened_dex_files)); 1404 if (opened_dex_files_map != nullptr) { 1405 opened_dex_files_maps_.push_back(std::move(opened_dex_files_map)); 1406 for (std::unique_ptr<const DexFile>& dex_file : opened_dex_files) { 1407 dex_file_oat_index_map_.emplace(dex_file.get(), i); 1408 opened_dex_files_.push_back(std::move(dex_file)); 1409 } 1410 } else { 1411 DCHECK(opened_dex_files.empty()); 1412 } 1413 } 1414 } 1415 1416 dex_files_ = MakeNonOwningPointerVector(opened_dex_files_); 1417 if (IsBootImage()) { 1418 // For boot image, pass opened dex files to the Runtime::Create(). 1419 // Note: Runtime acquires ownership of these dex files. 1420 runtime_options.Set(RuntimeArgumentMap::BootClassPathDexList, &opened_dex_files_); 1421 if (!CreateRuntime(std::move(runtime_options))) { 1422 return false; 1423 } 1424 } 1425 1426 // If we're doing the image, override the compiler filter to force full compilation. Must be 1427 // done ahead of WellKnownClasses::Init that causes verification. Note: doesn't force 1428 // compilation of class initializers. 1429 // Whilst we're in native take the opportunity to initialize well known classes. 1430 Thread* self = Thread::Current(); 1431 WellKnownClasses::Init(self->GetJniEnv()); 1432 1433 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker(); 1434 if (!IsBootImage()) { 1435 constexpr bool kSaveDexInput = false; 1436 if (kSaveDexInput) { 1437 SaveDexInput(); 1438 } 1439 1440 // Handle and ClassLoader creation needs to come after Runtime::Create. 1441 ScopedObjectAccess soa(self); 1442 1443 // Classpath: first the class-path given. 1444 std::vector<const DexFile*> class_path_files = MakeNonOwningPointerVector(class_path_files_); 1445 1446 // Then the dex files we'll compile. Thus we'll resolve the class-path first. 1447 class_path_files.insert(class_path_files.end(), dex_files_.begin(), dex_files_.end()); 1448 1449 class_loader_ = class_linker->CreatePathClassLoader(self, class_path_files); 1450 } 1451 1452 // Ensure opened dex files are writable for dex-to-dex transformations. 1453 for (const std::unique_ptr<MemMap>& map : opened_dex_files_maps_) { 1454 if (!map->Protect(PROT_READ | PROT_WRITE)) { 1455 PLOG(ERROR) << "Failed to make .dex files writeable."; 1456 return false; 1457 } 1458 } 1459 1460 // Ensure that the dex caches stay live since we don't want class unloading 1461 // to occur during compilation. 1462 for (const auto& dex_file : dex_files_) { 1463 ScopedObjectAccess soa(self); 1464 dex_caches_.push_back(soa.AddLocalReference<jobject>( 1465 class_linker->RegisterDexFile(*dex_file, Runtime::Current()->GetLinearAlloc()))); 1466 } 1467 1468 return true; 1469 } 1470 1471 // If we need to keep the oat file open for the image writer. 1472 bool ShouldKeepOatFileOpen() const { 1473 return IsImage() && oat_fd_ != kInvalidFd; 1474 } 1475 1476 // Create and invoke the compiler driver. This will compile all the dex files. 1477 void Compile() { 1478 TimingLogger::ScopedTiming t("dex2oat Compile", timings_); 1479 compiler_phases_timings_.reset(new CumulativeLogger("compilation times")); 1480 1481 // Find the dex files we should not inline from. 1482 1483 std::vector<std::string> no_inline_filters; 1484 Split(no_inline_from_string_, ',', &no_inline_filters); 1485 1486 // For now, on the host always have core-oj removed. 1487 const std::string core_oj = "core-oj"; 1488 if (!kIsTargetBuild && !ContainsElement(no_inline_filters, core_oj)) { 1489 no_inline_filters.push_back(core_oj); 1490 } 1491 1492 if (!no_inline_filters.empty()) { 1493 ClassLinker* class_linker = Runtime::Current()->GetClassLinker(); 1494 std::vector<const DexFile*> class_path_files = MakeNonOwningPointerVector(class_path_files_); 1495 std::vector<const std::vector<const DexFile*>*> dex_file_vectors = { 1496 &class_linker->GetBootClassPath(), 1497 &class_path_files, 1498 &dex_files_ 1499 }; 1500 for (const std::vector<const DexFile*>* dex_file_vector : dex_file_vectors) { 1501 for (const DexFile* dex_file : *dex_file_vector) { 1502 for (const std::string& filter : no_inline_filters) { 1503 // Use dex_file->GetLocation() rather than dex_file->GetBaseLocation(). This 1504 // allows tests to specify <test-dexfile>:classes2.dex if needed but if the 1505 // base location passes the StartsWith() test, so do all extra locations. 1506 std::string dex_location = dex_file->GetLocation(); 1507 if (filter.find('/') == std::string::npos) { 1508 // The filter does not contain the path. Remove the path from dex_location as well. 1509 size_t last_slash = dex_file->GetLocation().rfind('/'); 1510 if (last_slash != std::string::npos) { 1511 dex_location = dex_location.substr(last_slash + 1); 1512 } 1513 } 1514 1515 if (StartsWith(dex_location, filter.c_str())) { 1516 VLOG(compiler) << "Disabling inlining from " << dex_file->GetLocation(); 1517 no_inline_from_dex_files_.push_back(dex_file); 1518 break; 1519 } 1520 } 1521 } 1522 } 1523 if (!no_inline_from_dex_files_.empty()) { 1524 compiler_options_->no_inline_from_ = &no_inline_from_dex_files_; 1525 } 1526 } 1527 1528 driver_.reset(new CompilerDriver(compiler_options_.get(), 1529 verification_results_.get(), 1530 &method_inliner_map_, 1531 compiler_kind_, 1532 instruction_set_, 1533 instruction_set_features_.get(), 1534 IsBootImage(), 1535 IsAppImage(), 1536 image_classes_.release(), 1537 compiled_classes_.release(), 1538 /* compiled_methods */ nullptr, 1539 thread_count_, 1540 dump_stats_, 1541 dump_passes_, 1542 compiler_phases_timings_.get(), 1543 swap_fd_, 1544 profile_compilation_info_.get())); 1545 driver_->SetDexFilesForOatFile(dex_files_); 1546 driver_->CompileAll(class_loader_, dex_files_, timings_); 1547 } 1548 1549 // Notes on the interleaving of creating the images and oat files to 1550 // ensure the references between the two are correct. 1551 // 1552 // Currently we have a memory layout that looks something like this: 1553 // 1554 // +--------------+ 1555 // | images | 1556 // +--------------+ 1557 // | oat files | 1558 // +--------------+ 1559 // | alloc spaces | 1560 // +--------------+ 1561 // 1562 // There are several constraints on the loading of the images and oat files. 1563 // 1564 // 1. The images are expected to be loaded at an absolute address and 1565 // contain Objects with absolute pointers within the images. 1566 // 1567 // 2. There are absolute pointers from Methods in the images to their 1568 // code in the oat files. 1569 // 1570 // 3. There are absolute pointers from the code in the oat files to Methods 1571 // in the images. 1572 // 1573 // 4. There are absolute pointers from code in the oat files to other code 1574 // in the oat files. 1575 // 1576 // To get this all correct, we go through several steps. 1577 // 1578 // 1. We prepare offsets for all data in the oat files and calculate 1579 // the oat data size and code size. During this stage, we also set 1580 // oat code offsets in methods for use by the image writer. 1581 // 1582 // 2. We prepare offsets for the objects in the images and calculate 1583 // the image sizes. 1584 // 1585 // 3. We create the oat files. Originally this was just our own proprietary 1586 // file but now it is contained within an ELF dynamic object (aka an .so 1587 // file). Since we know the image sizes and oat data sizes and code sizes we 1588 // can prepare the ELF headers and we then know the ELF memory segment 1589 // layout and we can now resolve all references. The compiler provides 1590 // LinkerPatch information in each CompiledMethod and we resolve these, 1591 // using the layout information and image object locations provided by 1592 // image writer, as we're writing the method code. 1593 // 1594 // 4. We create the image files. They need to know where the oat files 1595 // will be loaded after itself. Originally oat files were simply 1596 // memory mapped so we could predict where their contents were based 1597 // on the file size. Now that they are ELF files, we need to inspect 1598 // the ELF files to understand the in memory segment layout including 1599 // where the oat header is located within. 1600 // TODO: We could just remember this information from step 3. 1601 // 1602 // 5. We fixup the ELF program headers so that dlopen will try to 1603 // load the .so at the desired location at runtime by offsetting the 1604 // Elf32_Phdr.p_vaddr values by the desired base address. 1605 // TODO: Do this in step 3. We already know the layout there. 1606 // 1607 // Steps 1.-3. are done by the CreateOatFile() above, steps 4.-5. 1608 // are done by the CreateImageFile() below. 1609 1610 // Write out the generated code part. Calls the OatWriter and ElfBuilder. Also prepares the 1611 // ImageWriter, if necessary. 1612 // Note: Flushing (and closing) the file is the caller's responsibility, except for the failure 1613 // case (when the file will be explicitly erased). 1614 bool WriteOatFiles() { 1615 TimingLogger::ScopedTiming t("dex2oat Oat", timings_); 1616 1617 // Sync the data to the file, in case we did dex2dex transformations. 1618 for (const std::unique_ptr<MemMap>& map : opened_dex_files_maps_) { 1619 if (!map->Sync()) { 1620 PLOG(ERROR) << "Failed to Sync() dex2dex output. Map: " << map->GetName(); 1621 return false; 1622 } 1623 } 1624 1625 if (IsImage()) { 1626 if (app_image_ && image_base_ == 0) { 1627 gc::Heap* const heap = Runtime::Current()->GetHeap(); 1628 for (gc::space::ImageSpace* image_space : heap->GetBootImageSpaces()) { 1629 image_base_ = std::max(image_base_, RoundUp( 1630 reinterpret_cast<uintptr_t>(image_space->GetImageHeader().GetOatFileEnd()), 1631 kPageSize)); 1632 } 1633 // The non moving space is right after the oat file. Put the preferred app image location 1634 // right after the non moving space so that we ideally get a continuous immune region for 1635 // the GC. 1636 // Use the default non moving space capacity since dex2oat does not have a separate non- 1637 // moving space. This means the runtime's non moving space space size will be as large 1638 // as the growth limit for dex2oat, but smaller in the zygote. 1639 const size_t non_moving_space_capacity = gc::Heap::kDefaultNonMovingSpaceCapacity; 1640 image_base_ += non_moving_space_capacity; 1641 VLOG(compiler) << "App image base=" << reinterpret_cast<void*>(image_base_); 1642 } 1643 1644 image_writer_.reset(new ImageWriter(*driver_, 1645 image_base_, 1646 compiler_options_->GetCompilePic(), 1647 IsAppImage(), 1648 image_storage_mode_, 1649 oat_filenames_, 1650 dex_file_oat_index_map_)); 1651 1652 // We need to prepare method offsets in the image address space for direct method patching. 1653 TimingLogger::ScopedTiming t2("dex2oat Prepare image address space", timings_); 1654 if (!image_writer_->PrepareImageAddressSpace()) { 1655 LOG(ERROR) << "Failed to prepare image address space."; 1656 return false; 1657 } 1658 } 1659 1660 linker::MultiOatRelativePatcher patcher(instruction_set_, instruction_set_features_.get()); 1661 { 1662 TimingLogger::ScopedTiming t2("dex2oat Write ELF", timings_); 1663 for (size_t i = 0, size = oat_files_.size(); i != size; ++i) { 1664 std::unique_ptr<ElfWriter>& elf_writer = elf_writers_[i]; 1665 std::unique_ptr<OatWriter>& oat_writer = oat_writers_[i]; 1666 1667 std::vector<const DexFile*>& dex_files = dex_files_per_oat_file_[i]; 1668 oat_writer->PrepareLayout(driver_.get(), image_writer_.get(), dex_files, &patcher); 1669 1670 size_t rodata_size = oat_writer->GetOatHeader().GetExecutableOffset(); 1671 size_t text_size = oat_writer->GetSize() - rodata_size; 1672 elf_writer->SetLoadedSectionSizes(rodata_size, text_size, oat_writer->GetBssSize()); 1673 1674 if (IsImage()) { 1675 // Update oat layout. 1676 DCHECK(image_writer_ != nullptr); 1677 DCHECK_LT(i, oat_filenames_.size()); 1678 image_writer_->UpdateOatFileLayout(i, 1679 elf_writer->GetLoadedSize(), 1680 oat_writer->GetOatDataOffset(), 1681 oat_writer->GetSize()); 1682 } 1683 } 1684 1685 for (size_t i = 0, size = oat_files_.size(); i != size; ++i) { 1686 std::unique_ptr<File>& oat_file = oat_files_[i]; 1687 std::unique_ptr<ElfWriter>& elf_writer = elf_writers_[i]; 1688 std::unique_ptr<OatWriter>& oat_writer = oat_writers_[i]; 1689 1690 oat_writer->AddMethodDebugInfos(debug::MakeTrampolineInfos(oat_writer->GetOatHeader())); 1691 1692 // We need to mirror the layout of the ELF file in the compressed debug-info. 1693 // Therefore PrepareDebugInfo() relies on the SetLoadedSectionSizes() call further above. 1694 elf_writer->PrepareDebugInfo(oat_writer->GetMethodDebugInfo()); 1695 1696 OutputStream*& rodata = rodata_[i]; 1697 DCHECK(rodata != nullptr); 1698 if (!oat_writer->WriteRodata(rodata)) { 1699 LOG(ERROR) << "Failed to write .rodata section to the ELF file " << oat_file->GetPath(); 1700 return false; 1701 } 1702 elf_writer->EndRoData(rodata); 1703 rodata = nullptr; 1704 1705 OutputStream* text = elf_writer->StartText(); 1706 if (!oat_writer->WriteCode(text)) { 1707 LOG(ERROR) << "Failed to write .text section to the ELF file " << oat_file->GetPath(); 1708 return false; 1709 } 1710 elf_writer->EndText(text); 1711 1712 if (!oat_writer->WriteHeader(elf_writer->GetStream(), 1713 image_file_location_oat_checksum_, 1714 image_file_location_oat_data_begin_, 1715 image_patch_delta_)) { 1716 LOG(ERROR) << "Failed to write oat header to the ELF file " << oat_file->GetPath(); 1717 return false; 1718 } 1719 1720 if (IsImage()) { 1721 // Update oat header information. 1722 DCHECK(image_writer_ != nullptr); 1723 DCHECK_LT(i, oat_filenames_.size()); 1724 image_writer_->UpdateOatFileHeader(i, oat_writer->GetOatHeader()); 1725 } 1726 1727 elf_writer->WriteDynamicSection(); 1728 elf_writer->WriteDebugInfo(oat_writer->GetMethodDebugInfo()); 1729 elf_writer->WritePatchLocations(oat_writer->GetAbsolutePatchLocations()); 1730 1731 if (!elf_writer->End()) { 1732 LOG(ERROR) << "Failed to write ELF file " << oat_file->GetPath(); 1733 return false; 1734 } 1735 1736 // Flush the oat file. 1737 if (oat_files_[i] != nullptr) { 1738 if (oat_files_[i]->Flush() != 0) { 1739 PLOG(ERROR) << "Failed to flush oat file: " << oat_filenames_[i]; 1740 return false; 1741 } 1742 } 1743 1744 VLOG(compiler) << "Oat file written successfully: " << oat_filenames_[i]; 1745 1746 oat_writer.reset(); 1747 elf_writer.reset(); 1748 } 1749 } 1750 1751 return true; 1752 } 1753 1754 // If we are compiling an image, invoke the image creation routine. Else just skip. 1755 bool HandleImage() { 1756 if (IsImage()) { 1757 TimingLogger::ScopedTiming t("dex2oat ImageWriter", timings_); 1758 if (!CreateImageFile()) { 1759 return false; 1760 } 1761 VLOG(compiler) << "Images written successfully"; 1762 } 1763 return true; 1764 } 1765 1766 // Create a copy from stripped to unstripped. 1767 bool CopyStrippedToUnstripped() { 1768 for (size_t i = 0; i < oat_unstripped_.size(); ++i) { 1769 // If we don't want to strip in place, copy from stripped location to unstripped location. 1770 // We need to strip after image creation because FixupElf needs to use .strtab. 1771 if (strcmp(oat_unstripped_[i], oat_filenames_[i]) != 0) { 1772 // If the oat file is still open, flush it. 1773 if (oat_files_[i].get() != nullptr && oat_files_[i]->IsOpened()) { 1774 if (!FlushCloseOatFile(i)) { 1775 return false; 1776 } 1777 } 1778 1779 TimingLogger::ScopedTiming t("dex2oat OatFile copy", timings_); 1780 std::unique_ptr<File> in(OS::OpenFileForReading(oat_filenames_[i])); 1781 std::unique_ptr<File> out(OS::CreateEmptyFile(oat_unstripped_[i])); 1782 size_t buffer_size = 8192; 1783 std::unique_ptr<uint8_t[]> buffer(new uint8_t[buffer_size]); 1784 while (true) { 1785 int bytes_read = TEMP_FAILURE_RETRY(read(in->Fd(), buffer.get(), buffer_size)); 1786 if (bytes_read <= 0) { 1787 break; 1788 } 1789 bool write_ok = out->WriteFully(buffer.get(), bytes_read); 1790 CHECK(write_ok); 1791 } 1792 if (out->FlushCloseOrErase() != 0) { 1793 PLOG(ERROR) << "Failed to flush and close copied oat file: " << oat_unstripped_[i]; 1794 return false; 1795 } 1796 VLOG(compiler) << "Oat file copied successfully (unstripped): " << oat_unstripped_[i]; 1797 } 1798 } 1799 return true; 1800 } 1801 1802 bool FlushOatFiles() { 1803 TimingLogger::ScopedTiming t2("dex2oat Flush ELF", timings_); 1804 for (size_t i = 0; i < oat_files_.size(); ++i) { 1805 if (oat_files_[i].get() != nullptr) { 1806 if (oat_files_[i]->Flush() != 0) { 1807 PLOG(ERROR) << "Failed to flush oat file: " << oat_filenames_[i]; 1808 oat_files_[i]->Erase(); 1809 return false; 1810 } 1811 } 1812 } 1813 return true; 1814 } 1815 1816 bool FlushCloseOatFile(size_t i) { 1817 if (oat_files_[i].get() != nullptr) { 1818 std::unique_ptr<File> tmp(oat_files_[i].release()); 1819 if (tmp->FlushCloseOrErase() != 0) { 1820 PLOG(ERROR) << "Failed to flush and close oat file: " << oat_filenames_[i]; 1821 return false; 1822 } 1823 } 1824 return true; 1825 } 1826 1827 bool FlushCloseOatFiles() { 1828 bool result = true; 1829 for (size_t i = 0; i < oat_files_.size(); ++i) { 1830 result &= FlushCloseOatFile(i); 1831 } 1832 return result; 1833 } 1834 1835 void DumpTiming() { 1836 if (dump_timing_ || (dump_slow_timing_ && timings_->GetTotalNs() > MsToNs(1000))) { 1837 LOG(INFO) << Dumpable<TimingLogger>(*timings_); 1838 } 1839 if (dump_passes_) { 1840 LOG(INFO) << Dumpable<CumulativeLogger>(*driver_->GetTimingsLogger()); 1841 } 1842 } 1843 1844 CompilerOptions* GetCompilerOptions() const { 1845 return compiler_options_.get(); 1846 } 1847 1848 bool IsImage() const { 1849 return IsAppImage() || IsBootImage(); 1850 } 1851 1852 bool IsAppImage() const { 1853 return app_image_; 1854 } 1855 1856 bool IsBootImage() const { 1857 return boot_image_; 1858 } 1859 1860 bool IsHost() const { 1861 return is_host_; 1862 } 1863 1864 bool UseProfileGuidedCompilation() const { 1865 return CompilerFilter::DependsOnProfile(compiler_options_->GetCompilerFilter()); 1866 } 1867 1868 bool LoadProfile() { 1869 DCHECK(UseProfileGuidedCompilation()); 1870 1871 profile_compilation_info_.reset(new ProfileCompilationInfo()); 1872 ScopedFlock flock; 1873 bool success = true; 1874 std::string error; 1875 if (profile_file_fd_ != -1) { 1876 // The file doesn't need to be flushed so don't check the usage. 1877 // Pass a bogus path so that we can easily attribute any reported error. 1878 File file(profile_file_fd_, "profile", /*check_usage*/ false, /*read_only_mode*/ true); 1879 if (flock.Init(&file, &error)) { 1880 success = profile_compilation_info_->Load(profile_file_fd_); 1881 } 1882 } else if (profile_file_ != "") { 1883 if (flock.Init(profile_file_.c_str(), O_RDONLY, /* block */ true, &error)) { 1884 success = profile_compilation_info_->Load(flock.GetFile()->Fd()); 1885 } 1886 } 1887 if (!error.empty()) { 1888 LOG(WARNING) << "Cannot lock profiles: " << error; 1889 } 1890 1891 if (!success) { 1892 profile_compilation_info_.reset(nullptr); 1893 } 1894 1895 return success; 1896 } 1897 1898 private: 1899 template <typename T> 1900 static std::vector<T*> MakeNonOwningPointerVector(const std::vector<std::unique_ptr<T>>& src) { 1901 std::vector<T*> result; 1902 result.reserve(src.size()); 1903 for (const std::unique_ptr<T>& t : src) { 1904 result.push_back(t.get()); 1905 } 1906 return result; 1907 } 1908 1909 std::string GetMultiImageBootClassPath() { 1910 DCHECK(IsBootImage()); 1911 DCHECK_GT(oat_filenames_.size(), 1u); 1912 // If the image filename was adapted (e.g., for our tests), we need to change this here, 1913 // too, but need to strip all path components (they will be re-established when loading). 1914 std::ostringstream bootcp_oss; 1915 bool first_bootcp = true; 1916 for (size_t i = 0; i < dex_locations_.size(); ++i) { 1917 if (!first_bootcp) { 1918 bootcp_oss << ":"; 1919 } 1920 1921 std::string dex_loc = dex_locations_[i]; 1922 std::string image_filename = image_filenames_[i]; 1923 1924 // Use the dex_loc path, but the image_filename name (without path elements). 1925 size_t dex_last_slash = dex_loc.rfind('/'); 1926 1927 // npos is max(size_t). That makes this a bit ugly. 1928 size_t image_last_slash = image_filename.rfind('/'); 1929 size_t image_last_at = image_filename.rfind('@'); 1930 size_t image_last_sep = (image_last_slash == std::string::npos) 1931 ? image_last_at 1932 : (image_last_at == std::string::npos) 1933 ? std::string::npos 1934 : std::max(image_last_slash, image_last_at); 1935 // Note: whenever image_last_sep == npos, +1 overflow means using the full string. 1936 1937 if (dex_last_slash == std::string::npos) { 1938 dex_loc = image_filename.substr(image_last_sep + 1); 1939 } else { 1940 dex_loc = dex_loc.substr(0, dex_last_slash + 1) + 1941 image_filename.substr(image_last_sep + 1); 1942 } 1943 1944 // Image filenames already end with .art, no need to replace. 1945 1946 bootcp_oss << dex_loc; 1947 first_bootcp = false; 1948 } 1949 return bootcp_oss.str(); 1950 } 1951 1952 std::vector<std::string> GetClassPathLocations(const std::string& class_path) { 1953 // This function is used only for apps and for an app we have exactly one oat file. 1954 DCHECK(!IsBootImage()); 1955 DCHECK_EQ(oat_writers_.size(), 1u); 1956 std::vector<std::string> dex_files_canonical_locations; 1957 for (const char* location : oat_writers_[0]->GetSourceLocations()) { 1958 dex_files_canonical_locations.push_back(DexFile::GetDexCanonicalLocation(location)); 1959 } 1960 1961 std::vector<std::string> parsed; 1962 Split(class_path, ':', &parsed); 1963 auto kept_it = std::remove_if(parsed.begin(), 1964 parsed.end(), 1965 [dex_files_canonical_locations](const std::string& location) { 1966 return ContainsElement(dex_files_canonical_locations, 1967 DexFile::GetDexCanonicalLocation(location.c_str())); 1968 }); 1969 parsed.erase(kept_it, parsed.end()); 1970 return parsed; 1971 } 1972 1973 // Opens requested class path files and appends them to opened_dex_files. If the dex files have 1974 // been stripped, this opens them from their oat files and appends them to opened_oat_files. 1975 static void OpenClassPathFiles(const std::vector<std::string>& class_path_locations, 1976 std::vector<std::unique_ptr<const DexFile>>* opened_dex_files, 1977 std::vector<std::unique_ptr<OatFile>>* opened_oat_files, 1978 InstructionSet isa) { 1979 DCHECK(opened_dex_files != nullptr) << "OpenClassPathFiles dex out-param is nullptr"; 1980 DCHECK(opened_oat_files != nullptr) << "OpenClassPathFiles oat out-param is nullptr"; 1981 for (const std::string& location : class_path_locations) { 1982 // Stop early if we detect the special shared library, which may be passed as the classpath 1983 // for dex2oat when we want to skip the shared libraries check. 1984 if (location == OatFile::kSpecialSharedLibrary) { 1985 break; 1986 } 1987 std::string error_msg; 1988 if (!DexFile::Open(location.c_str(), location.c_str(), &error_msg, opened_dex_files)) { 1989 // If we fail to open the dex file because it's been stripped, try to open the dex file 1990 // from its corresponding oat file. 1991 OatFileAssistant oat_file_assistant(location.c_str(), isa, false, false); 1992 std::unique_ptr<OatFile> oat_file(oat_file_assistant.GetBestOatFile()); 1993 if (oat_file == nullptr) { 1994 LOG(WARNING) << "Failed to open dex file and associated oat file for '" << location 1995 << "': " << error_msg; 1996 } else { 1997 std::vector<std::unique_ptr<const DexFile>> oat_dex_files = 1998 oat_file_assistant.LoadDexFiles(*oat_file, location.c_str()); 1999 opened_oat_files->push_back(std::move(oat_file)); 2000 opened_dex_files->insert(opened_dex_files->end(), 2001 std::make_move_iterator(oat_dex_files.begin()), 2002 std::make_move_iterator(oat_dex_files.end())); 2003 } 2004 } 2005 } 2006 } 2007 2008 bool PrepareImageClasses() { 2009 // If --image-classes was specified, calculate the full list of classes to include in the image. 2010 if (image_classes_filename_ != nullptr) { 2011 image_classes_ = 2012 ReadClasses(image_classes_zip_filename_, image_classes_filename_, "image"); 2013 if (image_classes_ == nullptr) { 2014 return false; 2015 } 2016 } else if (IsBootImage()) { 2017 image_classes_.reset(new std::unordered_set<std::string>); 2018 } 2019 return true; 2020 } 2021 2022 bool PrepareCompiledClasses() { 2023 // If --compiled-classes was specified, calculate the full list of classes to compile in the 2024 // image. 2025 if (compiled_classes_filename_ != nullptr) { 2026 compiled_classes_ = 2027 ReadClasses(compiled_classes_zip_filename_, compiled_classes_filename_, "compiled"); 2028 if (compiled_classes_ == nullptr) { 2029 return false; 2030 } 2031 } else { 2032 compiled_classes_.reset(nullptr); // By default compile everything. 2033 } 2034 return true; 2035 } 2036 2037 static std::unique_ptr<std::unordered_set<std::string>> ReadClasses(const char* zip_filename, 2038 const char* classes_filename, 2039 const char* tag) { 2040 std::unique_ptr<std::unordered_set<std::string>> classes; 2041 std::string error_msg; 2042 if (zip_filename != nullptr) { 2043 classes.reset(ReadImageClassesFromZip(zip_filename, classes_filename, &error_msg)); 2044 } else { 2045 classes.reset(ReadImageClassesFromFile(classes_filename)); 2046 } 2047 if (classes == nullptr) { 2048 LOG(ERROR) << "Failed to create list of " << tag << " classes from '" 2049 << classes_filename << "': " << error_msg; 2050 } 2051 return classes; 2052 } 2053 2054 bool PrepareCompiledMethods() { 2055 // If --compiled-methods was specified, read the methods to compile from the given file(s). 2056 if (compiled_methods_filename_ != nullptr) { 2057 std::string error_msg; 2058 if (compiled_methods_zip_filename_ != nullptr) { 2059 compiled_methods_.reset(ReadCommentedInputFromZip(compiled_methods_zip_filename_, 2060 compiled_methods_filename_, 2061 nullptr, // No post-processing. 2062 &error_msg)); 2063 } else { 2064 compiled_methods_.reset(ReadCommentedInputFromFile(compiled_methods_filename_, 2065 nullptr)); // No post-processing. 2066 } 2067 if (compiled_methods_.get() == nullptr) { 2068 LOG(ERROR) << "Failed to create list of compiled methods from '" 2069 << compiled_methods_filename_ << "': " << error_msg; 2070 return false; 2071 } 2072 } else { 2073 compiled_methods_.reset(nullptr); // By default compile everything. 2074 } 2075 return true; 2076 } 2077 2078 void PruneNonExistentDexFiles() { 2079 DCHECK_EQ(dex_filenames_.size(), dex_locations_.size()); 2080 size_t kept = 0u; 2081 for (size_t i = 0, size = dex_filenames_.size(); i != size; ++i) { 2082 if (!OS::FileExists(dex_filenames_[i])) { 2083 LOG(WARNING) << "Skipping non-existent dex file '" << dex_filenames_[i] << "'"; 2084 } else { 2085 dex_filenames_[kept] = dex_filenames_[i]; 2086 dex_locations_[kept] = dex_locations_[i]; 2087 ++kept; 2088 } 2089 } 2090 dex_filenames_.resize(kept); 2091 dex_locations_.resize(kept); 2092 } 2093 2094 bool AddDexFileSources() { 2095 TimingLogger::ScopedTiming t2("AddDexFileSources", timings_); 2096 if (zip_fd_ != -1) { 2097 DCHECK_EQ(oat_writers_.size(), 1u); 2098 if (!oat_writers_[0]->AddZippedDexFilesSource(ScopedFd(zip_fd_), zip_location_.c_str())) { 2099 return false; 2100 } 2101 } else if (oat_writers_.size() > 1u) { 2102 // Multi-image. 2103 DCHECK_EQ(oat_writers_.size(), dex_filenames_.size()); 2104 DCHECK_EQ(oat_writers_.size(), dex_locations_.size()); 2105 for (size_t i = 0, size = oat_writers_.size(); i != size; ++i) { 2106 if (!oat_writers_[i]->AddDexFileSource(dex_filenames_[i], dex_locations_[i])) { 2107 return false; 2108 } 2109 } 2110 } else { 2111 DCHECK_EQ(oat_writers_.size(), 1u); 2112 DCHECK_EQ(dex_filenames_.size(), dex_locations_.size()); 2113 DCHECK_NE(dex_filenames_.size(), 0u); 2114 for (size_t i = 0; i != dex_filenames_.size(); ++i) { 2115 if (!oat_writers_[0]->AddDexFileSource(dex_filenames_[i], dex_locations_[i])) { 2116 return false; 2117 } 2118 } 2119 } 2120 return true; 2121 } 2122 2123 void CreateOatWriters() { 2124 TimingLogger::ScopedTiming t2("CreateOatWriters", timings_); 2125 elf_writers_.reserve(oat_files_.size()); 2126 oat_writers_.reserve(oat_files_.size()); 2127 for (const std::unique_ptr<File>& oat_file : oat_files_) { 2128 elf_writers_.emplace_back(CreateElfWriterQuick(instruction_set_, 2129 instruction_set_features_.get(), 2130 compiler_options_.get(), 2131 oat_file.get())); 2132 elf_writers_.back()->Start(); 2133 oat_writers_.emplace_back(new OatWriter(IsBootImage(), timings_)); 2134 } 2135 } 2136 2137 void SaveDexInput() { 2138 for (size_t i = 0; i < dex_files_.size(); ++i) { 2139 const DexFile* dex_file = dex_files_[i]; 2140 std::string tmp_file_name(StringPrintf("/data/local/tmp/dex2oat.%d.%zd.dex", 2141 getpid(), i)); 2142 std::unique_ptr<File> tmp_file(OS::CreateEmptyFile(tmp_file_name.c_str())); 2143 if (tmp_file.get() == nullptr) { 2144 PLOG(ERROR) << "Failed to open file " << tmp_file_name 2145 << ". Try: adb shell chmod 777 /data/local/tmp"; 2146 continue; 2147 } 2148 // This is just dumping files for debugging. Ignore errors, and leave remnants. 2149 UNUSED(tmp_file->WriteFully(dex_file->Begin(), dex_file->Size())); 2150 UNUSED(tmp_file->Flush()); 2151 UNUSED(tmp_file->Close()); 2152 LOG(INFO) << "Wrote input to " << tmp_file_name; 2153 } 2154 } 2155 2156 bool PrepareRuntimeOptions(RuntimeArgumentMap* runtime_options) { 2157 RuntimeOptions raw_options; 2158 if (boot_image_filename_.empty()) { 2159 std::string boot_class_path = "-Xbootclasspath:"; 2160 boot_class_path += Join(dex_filenames_, ':'); 2161 raw_options.push_back(std::make_pair(boot_class_path, nullptr)); 2162 std::string boot_class_path_locations = "-Xbootclasspath-locations:"; 2163 boot_class_path_locations += Join(dex_locations_, ':'); 2164 raw_options.push_back(std::make_pair(boot_class_path_locations, nullptr)); 2165 } else { 2166 std::string boot_image_option = "-Ximage:"; 2167 boot_image_option += boot_image_filename_; 2168 raw_options.push_back(std::make_pair(boot_image_option, nullptr)); 2169 } 2170 for (size_t i = 0; i < runtime_args_.size(); i++) { 2171 raw_options.push_back(std::make_pair(runtime_args_[i], nullptr)); 2172 } 2173 2174 raw_options.push_back(std::make_pair("compilercallbacks", callbacks_.get())); 2175 raw_options.push_back( 2176 std::make_pair("imageinstructionset", GetInstructionSetString(instruction_set_))); 2177 2178 // Only allow no boot image for the runtime if we're compiling one. When we compile an app, 2179 // we don't want fallback mode, it will abort as we do not push a boot classpath (it might 2180 // have been stripped in preopting, anyways). 2181 if (!IsBootImage()) { 2182 raw_options.push_back(std::make_pair("-Xno-dex-file-fallback", nullptr)); 2183 } 2184 // Disable libsigchain. We don't don't need it during compilation and it prevents us 2185 // from getting a statically linked version of dex2oat (because of dlsym and RTLD_NEXT). 2186 raw_options.push_back(std::make_pair("-Xno-sig-chain", nullptr)); 2187 // Disable Hspace compaction to save heap size virtual space. 2188 // Only need disable Hspace for OOM becasue background collector is equal to 2189 // foreground collector by default for dex2oat. 2190 raw_options.push_back(std::make_pair("-XX:DisableHSpaceCompactForOOM", nullptr)); 2191 2192 // If we're asked to be deterministic, ensure non-concurrent GC for determinism. Also 2193 // force the free-list implementation for large objects. 2194 if (compiler_options_->IsForceDeterminism()) { 2195 raw_options.push_back(std::make_pair("-Xgc:nonconcurrent", nullptr)); 2196 raw_options.push_back(std::make_pair("-XX:LargeObjectSpace=freelist", nullptr)); 2197 2198 // We also need to turn off the nonmoving space. For that, we need to disable HSpace 2199 // compaction (done above) and ensure that neither foreground nor background collectors 2200 // are concurrent. 2201 raw_options.push_back(std::make_pair("-XX:BackgroundGC=nonconcurrent", nullptr)); 2202 2203 // To make identity hashcode deterministic, set a known seed. 2204 mirror::Object::SetHashCodeSeed(987654321U); 2205 } 2206 2207 if (!Runtime::ParseOptions(raw_options, false, runtime_options)) { 2208 LOG(ERROR) << "Failed to parse runtime options"; 2209 return false; 2210 } 2211 return true; 2212 } 2213 2214 // Create a runtime necessary for compilation. 2215 bool CreateRuntime(RuntimeArgumentMap&& runtime_options) { 2216 TimingLogger::ScopedTiming t_runtime("Create runtime", timings_); 2217 if (!Runtime::Create(std::move(runtime_options))) { 2218 LOG(ERROR) << "Failed to create runtime"; 2219 return false; 2220 } 2221 runtime_.reset(Runtime::Current()); 2222 runtime_->SetInstructionSet(instruction_set_); 2223 for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) { 2224 Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i); 2225 if (!runtime_->HasCalleeSaveMethod(type)) { 2226 runtime_->SetCalleeSaveMethod(runtime_->CreateCalleeSaveMethod(), type); 2227 } 2228 } 2229 runtime_->GetClassLinker()->FixupDexCaches(runtime_->GetResolutionMethod()); 2230 2231 // Initialize maps for unstarted runtime. This needs to be here, as running clinits needs this 2232 // set up. 2233 interpreter::UnstartedRuntime::Initialize(); 2234 2235 runtime_->GetClassLinker()->RunRootClinits(); 2236 2237 // Runtime::Create acquired the mutator_lock_ that is normally given away when we 2238 // Runtime::Start, give it away now so that we don't starve GC. 2239 Thread* self = Thread::Current(); 2240 self->TransitionFromRunnableToSuspended(kNative); 2241 2242 return true; 2243 } 2244 2245 // Let the ImageWriter write the image files. If we do not compile PIC, also fix up the oat files. 2246 bool CreateImageFile() 2247 REQUIRES(!Locks::mutator_lock_) { 2248 CHECK(image_writer_ != nullptr); 2249 if (!IsBootImage()) { 2250 CHECK(image_filenames_.empty()); 2251 image_filenames_.push_back(app_image_file_name_.c_str()); 2252 } 2253 if (!image_writer_->Write(app_image_fd_, 2254 image_filenames_, 2255 oat_filenames_)) { 2256 LOG(ERROR) << "Failure during image file creation"; 2257 return false; 2258 } 2259 2260 // We need the OatDataBegin entries. 2261 dchecked_vector<uintptr_t> oat_data_begins; 2262 for (size_t i = 0, size = oat_filenames_.size(); i != size; ++i) { 2263 oat_data_begins.push_back(image_writer_->GetOatDataBegin(i)); 2264 } 2265 // Destroy ImageWriter before doing FixupElf. 2266 image_writer_.reset(); 2267 2268 for (size_t i = 0, size = oat_filenames_.size(); i != size; ++i) { 2269 const char* oat_filename = oat_filenames_[i]; 2270 // Do not fix up the ELF file if we are --compile-pic or compiling the app image 2271 if (!compiler_options_->GetCompilePic() && IsBootImage()) { 2272 std::unique_ptr<File> oat_file(OS::OpenFileReadWrite(oat_filename)); 2273 if (oat_file.get() == nullptr) { 2274 PLOG(ERROR) << "Failed to open ELF file: " << oat_filename; 2275 return false; 2276 } 2277 2278 if (!ElfWriter::Fixup(oat_file.get(), oat_data_begins[i])) { 2279 oat_file->Erase(); 2280 LOG(ERROR) << "Failed to fixup ELF file " << oat_file->GetPath(); 2281 return false; 2282 } 2283 2284 if (oat_file->FlushCloseOrErase()) { 2285 PLOG(ERROR) << "Failed to flush and close fixed ELF file " << oat_file->GetPath(); 2286 return false; 2287 } 2288 } 2289 } 2290 2291 return true; 2292 } 2293 2294 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;) 2295 static std::unordered_set<std::string>* ReadImageClassesFromFile( 2296 const char* image_classes_filename) { 2297 std::function<std::string(const char*)> process = DotToDescriptor; 2298 return ReadCommentedInputFromFile(image_classes_filename, &process); 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>* ReadImageClassesFromZip( 2303 const char* zip_filename, 2304 const char* image_classes_filename, 2305 std::string* error_msg) { 2306 std::function<std::string(const char*)> process = DotToDescriptor; 2307 return ReadCommentedInputFromZip(zip_filename, image_classes_filename, &process, error_msg); 2308 } 2309 2310 // Read lines from the given file, dropping comments and empty lines. Post-process each line with 2311 // the given function. 2312 static std::unordered_set<std::string>* ReadCommentedInputFromFile( 2313 const char* input_filename, std::function<std::string(const char*)>* process) { 2314 std::unique_ptr<std::ifstream> input_file(new std::ifstream(input_filename, std::ifstream::in)); 2315 if (input_file.get() == nullptr) { 2316 LOG(ERROR) << "Failed to open input file " << input_filename; 2317 return nullptr; 2318 } 2319 std::unique_ptr<std::unordered_set<std::string>> result( 2320 ReadCommentedInputStream(*input_file, process)); 2321 input_file->close(); 2322 return result.release(); 2323 } 2324 2325 // Read lines from the given file from the given zip file, dropping comments and empty lines. 2326 // Post-process each line with the given function. 2327 static std::unordered_set<std::string>* ReadCommentedInputFromZip( 2328 const char* zip_filename, 2329 const char* input_filename, 2330 std::function<std::string(const char*)>* process, 2331 std::string* error_msg) { 2332 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::Open(zip_filename, error_msg)); 2333 if (zip_archive.get() == nullptr) { 2334 return nullptr; 2335 } 2336 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(input_filename, error_msg)); 2337 if (zip_entry.get() == nullptr) { 2338 *error_msg = StringPrintf("Failed to find '%s' within '%s': %s", input_filename, 2339 zip_filename, error_msg->c_str()); 2340 return nullptr; 2341 } 2342 std::unique_ptr<MemMap> input_file(zip_entry->ExtractToMemMap(zip_filename, 2343 input_filename, 2344 error_msg)); 2345 if (input_file.get() == nullptr) { 2346 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", input_filename, 2347 zip_filename, error_msg->c_str()); 2348 return nullptr; 2349 } 2350 const std::string input_string(reinterpret_cast<char*>(input_file->Begin()), 2351 input_file->Size()); 2352 std::istringstream input_stream(input_string); 2353 return ReadCommentedInputStream(input_stream, process); 2354 } 2355 2356 // Read lines from the given stream, dropping comments and empty lines. Post-process each line 2357 // with the given function. 2358 static std::unordered_set<std::string>* ReadCommentedInputStream( 2359 std::istream& in_stream, 2360 std::function<std::string(const char*)>* process) { 2361 std::unique_ptr<std::unordered_set<std::string>> image_classes( 2362 new std::unordered_set<std::string>); 2363 while (in_stream.good()) { 2364 std::string dot; 2365 std::getline(in_stream, dot); 2366 if (StartsWith(dot, "#") || dot.empty()) { 2367 continue; 2368 } 2369 if (process != nullptr) { 2370 std::string descriptor((*process)(dot.c_str())); 2371 image_classes->insert(descriptor); 2372 } else { 2373 image_classes->insert(dot); 2374 } 2375 } 2376 return image_classes.release(); 2377 } 2378 2379 void LogCompletionTime() { 2380 // Note: when creation of a runtime fails, e.g., when trying to compile an app but when there 2381 // is no image, there won't be a Runtime::Current(). 2382 // Note: driver creation can fail when loading an invalid dex file. 2383 LOG(INFO) << "dex2oat took " << PrettyDuration(NanoTime() - start_ns_) 2384 << " (threads: " << thread_count_ << ") " 2385 << ((Runtime::Current() != nullptr && driver_ != nullptr) ? 2386 driver_->GetMemoryUsageString(kIsDebugBuild || VLOG_IS_ON(compiler)) : 2387 ""); 2388 } 2389 2390 std::string StripIsaFrom(const char* image_filename, InstructionSet isa) { 2391 std::string res(image_filename); 2392 size_t last_slash = res.rfind('/'); 2393 if (last_slash == std::string::npos || last_slash == 0) { 2394 return res; 2395 } 2396 size_t penultimate_slash = res.rfind('/', last_slash - 1); 2397 if (penultimate_slash == std::string::npos) { 2398 return res; 2399 } 2400 // Check that the string in-between is the expected one. 2401 if (res.substr(penultimate_slash + 1, last_slash - penultimate_slash - 1) != 2402 GetInstructionSetString(isa)) { 2403 LOG(WARNING) << "Unexpected string when trying to strip isa: " << res; 2404 return res; 2405 } 2406 return res.substr(0, penultimate_slash) + res.substr(last_slash); 2407 } 2408 2409 std::unique_ptr<CompilerOptions> compiler_options_; 2410 Compiler::Kind compiler_kind_; 2411 2412 InstructionSet instruction_set_; 2413 std::unique_ptr<const InstructionSetFeatures> instruction_set_features_; 2414 2415 uint32_t image_file_location_oat_checksum_; 2416 uintptr_t image_file_location_oat_data_begin_; 2417 int32_t image_patch_delta_; 2418 std::unique_ptr<SafeMap<std::string, std::string> > key_value_store_; 2419 2420 std::unique_ptr<VerificationResults> verification_results_; 2421 2422 DexFileToMethodInlinerMap method_inliner_map_; 2423 std::unique_ptr<QuickCompilerCallbacks> callbacks_; 2424 2425 std::unique_ptr<Runtime> runtime_; 2426 2427 // Ownership for the class path files. 2428 std::vector<std::unique_ptr<const DexFile>> class_path_files_; 2429 2430 size_t thread_count_; 2431 uint64_t start_ns_; 2432 std::unique_ptr<WatchDog> watchdog_; 2433 std::vector<std::unique_ptr<File>> oat_files_; 2434 std::string oat_location_; 2435 std::vector<const char*> oat_filenames_; 2436 std::vector<const char*> oat_unstripped_; 2437 int oat_fd_; 2438 std::vector<const char*> dex_filenames_; 2439 std::vector<const char*> dex_locations_; 2440 int zip_fd_; 2441 std::string zip_location_; 2442 std::string boot_image_filename_; 2443 std::vector<const char*> runtime_args_; 2444 std::vector<const char*> image_filenames_; 2445 uintptr_t image_base_; 2446 const char* image_classes_zip_filename_; 2447 const char* image_classes_filename_; 2448 ImageHeader::StorageMode image_storage_mode_; 2449 const char* compiled_classes_zip_filename_; 2450 const char* compiled_classes_filename_; 2451 const char* compiled_methods_zip_filename_; 2452 const char* compiled_methods_filename_; 2453 std::unique_ptr<std::unordered_set<std::string>> image_classes_; 2454 std::unique_ptr<std::unordered_set<std::string>> compiled_classes_; 2455 std::unique_ptr<std::unordered_set<std::string>> compiled_methods_; 2456 bool app_image_; 2457 bool boot_image_; 2458 bool multi_image_; 2459 bool is_host_; 2460 std::string android_root_; 2461 // Dex files we are compiling, does not include the class path dex files. 2462 std::vector<const DexFile*> dex_files_; 2463 std::string no_inline_from_string_; 2464 std::vector<jobject> dex_caches_; 2465 jobject class_loader_; 2466 2467 std::vector<std::unique_ptr<ElfWriter>> elf_writers_; 2468 std::vector<std::unique_ptr<OatWriter>> oat_writers_; 2469 std::vector<OutputStream*> rodata_; 2470 std::unique_ptr<ImageWriter> image_writer_; 2471 std::unique_ptr<CompilerDriver> driver_; 2472 2473 std::vector<std::unique_ptr<MemMap>> opened_dex_files_maps_; 2474 std::vector<std::unique_ptr<OatFile>> opened_oat_files_; 2475 std::vector<std::unique_ptr<const DexFile>> opened_dex_files_; 2476 2477 std::vector<const DexFile*> no_inline_from_dex_files_; 2478 2479 std::vector<std::string> verbose_methods_; 2480 bool dump_stats_; 2481 bool dump_passes_; 2482 bool dump_timing_; 2483 bool dump_slow_timing_; 2484 std::string swap_file_name_; 2485 int swap_fd_; 2486 std::string app_image_file_name_; 2487 int app_image_fd_; 2488 std::string profile_file_; 2489 int profile_file_fd_; 2490 std::unique_ptr<ProfileCompilationInfo> profile_compilation_info_; 2491 TimingLogger* timings_; 2492 std::unique_ptr<CumulativeLogger> compiler_phases_timings_; 2493 std::vector<std::vector<const DexFile*>> dex_files_per_oat_file_; 2494 std::unordered_map<const DexFile*, size_t> dex_file_oat_index_map_; 2495 2496 // Backing storage. 2497 std::vector<std::string> char_backing_storage_; 2498 2499 // See CompilerOptions.force_determinism_. 2500 bool force_determinism_; 2501 2502 DISALLOW_IMPLICIT_CONSTRUCTORS(Dex2Oat); 2503}; 2504 2505static void b13564922() { 2506#if defined(__linux__) && defined(__arm__) 2507 int major, minor; 2508 struct utsname uts; 2509 if (uname(&uts) != -1 && 2510 sscanf(uts.release, "%d.%d", &major, &minor) == 2 && 2511 ((major < 3) || ((major == 3) && (minor < 4)))) { 2512 // Kernels before 3.4 don't handle the ASLR well and we can run out of address 2513 // space (http://b/13564922). Work around the issue by inhibiting further mmap() randomization. 2514 int old_personality = personality(0xffffffff); 2515 if ((old_personality & ADDR_NO_RANDOMIZE) == 0) { 2516 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE); 2517 if (new_personality == -1) { 2518 LOG(WARNING) << "personality(. | ADDR_NO_RANDOMIZE) failed."; 2519 } 2520 } 2521 } 2522#endif 2523} 2524 2525static int CompileImage(Dex2Oat& dex2oat) { 2526 dex2oat.LoadClassProfileDescriptors(); 2527 dex2oat.Compile(); 2528 2529 if (!dex2oat.WriteOatFiles()) { 2530 dex2oat.EraseOatFiles(); 2531 return EXIT_FAILURE; 2532 } 2533 2534 // Flush boot.oat. We always expect the output file by name, and it will be re-opened from the 2535 // unstripped name. Do not close the file if we are compiling the image with an oat fd since the 2536 // image writer will require this fd to generate the image. 2537 if (dex2oat.ShouldKeepOatFileOpen()) { 2538 if (!dex2oat.FlushOatFiles()) { 2539 return EXIT_FAILURE; 2540 } 2541 } else if (!dex2oat.FlushCloseOatFiles()) { 2542 return EXIT_FAILURE; 2543 } 2544 2545 // Creates the boot.art and patches the oat files. 2546 if (!dex2oat.HandleImage()) { 2547 return EXIT_FAILURE; 2548 } 2549 2550 // When given --host, finish early without stripping. 2551 if (dex2oat.IsHost()) { 2552 dex2oat.DumpTiming(); 2553 return EXIT_SUCCESS; 2554 } 2555 2556 // Copy stripped to unstripped location, if necessary. 2557 if (!dex2oat.CopyStrippedToUnstripped()) { 2558 return EXIT_FAILURE; 2559 } 2560 2561 // FlushClose again, as stripping might have re-opened the oat files. 2562 if (!dex2oat.FlushCloseOatFiles()) { 2563 return EXIT_FAILURE; 2564 } 2565 2566 dex2oat.DumpTiming(); 2567 return EXIT_SUCCESS; 2568} 2569 2570static int CompileApp(Dex2Oat& dex2oat) { 2571 dex2oat.Compile(); 2572 2573 if (!dex2oat.WriteOatFiles()) { 2574 dex2oat.EraseOatFiles(); 2575 return EXIT_FAILURE; 2576 } 2577 2578 // Do not close the oat files here. We might have gotten the output file by file descriptor, 2579 // which we would lose. 2580 2581 // When given --host, finish early without stripping. 2582 if (dex2oat.IsHost()) { 2583 if (!dex2oat.FlushCloseOatFiles()) { 2584 return EXIT_FAILURE; 2585 } 2586 2587 dex2oat.DumpTiming(); 2588 return EXIT_SUCCESS; 2589 } 2590 2591 // Copy stripped to unstripped location, if necessary. This will implicitly flush & close the 2592 // stripped versions. If this is given, we expect to be able to open writable files by name. 2593 if (!dex2oat.CopyStrippedToUnstripped()) { 2594 return EXIT_FAILURE; 2595 } 2596 2597 // Flush and close the files. 2598 if (!dex2oat.FlushCloseOatFiles()) { 2599 return EXIT_FAILURE; 2600 } 2601 2602 dex2oat.DumpTiming(); 2603 return EXIT_SUCCESS; 2604} 2605 2606static int dex2oat(int argc, char** argv) { 2607 b13564922(); 2608 2609 TimingLogger timings("compiler", false, false); 2610 2611 // Allocate `dex2oat` on the heap instead of on the stack, as Clang 2612 // might produce a stack frame too large for this function or for 2613 // functions inlining it (such as main), that would not fit the 2614 // requirements of the `-Wframe-larger-than` option. 2615 std::unique_ptr<Dex2Oat> dex2oat = MakeUnique<Dex2Oat>(&timings); 2616 2617 // Parse arguments. Argument mistakes will lead to exit(EXIT_FAILURE) in UsageError. 2618 dex2oat->ParseArgs(argc, argv); 2619 2620 // If needed, process profile information for profile guided compilation. 2621 // This operation involves I/O. 2622 if (dex2oat->UseProfileGuidedCompilation()) { 2623 if (!dex2oat->LoadProfile()) { 2624 LOG(ERROR) << "Failed to process profile file"; 2625 return EXIT_FAILURE; 2626 } 2627 } 2628 2629 // Check early that the result of compilation can be written 2630 if (!dex2oat->OpenFile()) { 2631 return EXIT_FAILURE; 2632 } 2633 2634 // Print the complete line when any of the following is true: 2635 // 1) Debug build 2636 // 2) Compiling an image 2637 // 3) Compiling with --host 2638 // 4) Compiling on the host (not a target build) 2639 // Otherwise, print a stripped command line. 2640 if (kIsDebugBuild || dex2oat->IsBootImage() || dex2oat->IsHost() || !kIsTargetBuild) { 2641 LOG(INFO) << CommandLine(); 2642 } else { 2643 LOG(INFO) << StrippedCommandLine(); 2644 } 2645 2646 if (!dex2oat->Setup()) { 2647 dex2oat->EraseOatFiles(); 2648 return EXIT_FAILURE; 2649 } 2650 2651 bool result; 2652 if (dex2oat->IsImage()) { 2653 result = CompileImage(*dex2oat); 2654 } else { 2655 result = CompileApp(*dex2oat); 2656 } 2657 2658 dex2oat->Shutdown(); 2659 return result; 2660} 2661} // namespace art 2662 2663int main(int argc, char** argv) { 2664 int result = art::dex2oat(argc, argv); 2665 // Everything was done, do an explicit exit here to avoid running Runtime destructors that take 2666 // time (bug 10645725) unless we're a debug build or running on valgrind. Note: The Dex2Oat class 2667 // should not destruct the runtime in this case. 2668 if (!art::kIsDebugBuild && (RUNNING_ON_MEMORY_TOOL == 0)) { 2669 exit(result); 2670 } 2671 return result; 2672} 2673