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