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