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