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