dex2oat.cc revision c033474cfbfe1e963c07fa5c38aed02e35ed6f91
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 "elf_file.h" 59#include "elf_writer.h" 60#include "gc/space/image_space.h" 61#include "gc/space/space-inl.h" 62#include "image_writer.h" 63#include "interpreter/unstarted_runtime.h" 64#include "leb128.h" 65#include "mirror/class-inl.h" 66#include "mirror/class_loader.h" 67#include "mirror/object-inl.h" 68#include "mirror/object_array-inl.h" 69#include "oat_writer.h" 70#include "os.h" 71#include "runtime.h" 72#include "ScopedLocalRef.h" 73#include "scoped_thread_state_change.h" 74#include "utils.h" 75#include "vector_output_stream.h" 76#include "well_known_classes.h" 77#include "zip_archive.h" 78 79namespace art { 80 81static int original_argc; 82static char** original_argv; 83 84static std::string CommandLine() { 85 std::vector<std::string> command; 86 for (int i = 0; i < original_argc; ++i) { 87 command.push_back(original_argv[i]); 88 } 89 return Join(command, ' '); 90} 91 92// A stripped version. Remove some less essential parameters. If we see a "--zip-fd=" parameter, be 93// even more aggressive. There won't be much reasonable data here for us in that case anyways (the 94// locations are all staged). 95static std::string StrippedCommandLine() { 96 std::vector<std::string> command; 97 98 // Do a pre-pass to look for zip-fd. 99 bool saw_zip_fd = false; 100 for (int i = 0; i < original_argc; ++i) { 101 if (StartsWith(original_argv[i], "--zip-fd=")) { 102 saw_zip_fd = true; 103 break; 104 } 105 } 106 107 // Now filter out things. 108 for (int i = 0; i < original_argc; ++i) { 109 // All runtime-arg parameters are dropped. 110 if (strcmp(original_argv[i], "--runtime-arg") == 0) { 111 i++; // Drop the next part, too. 112 continue; 113 } 114 115 // Any instruction-setXXX is dropped. 116 if (StartsWith(original_argv[i], "--instruction-set")) { 117 continue; 118 } 119 120 // The boot image is dropped. 121 if (StartsWith(original_argv[i], "--boot-image=")) { 122 continue; 123 } 124 125 // This should leave any dex-file and oat-file options, describing what we compiled. 126 127 // However, we prefer to drop this when we saw --zip-fd. 128 if (saw_zip_fd) { 129 // Drop anything --zip-X, --dex-X, --oat-X, --swap-X, or --app-image-X 130 if (StartsWith(original_argv[i], "--zip-") || 131 StartsWith(original_argv[i], "--dex-") || 132 StartsWith(original_argv[i], "--oat-") || 133 StartsWith(original_argv[i], "--swap-") || 134 StartsWith(original_argv[i], "--app-image-")) { 135 continue; 136 } 137 } 138 139 command.push_back(original_argv[i]); 140 } 141 142 // Construct the final output. 143 if (command.size() <= 1U) { 144 // It seems only "/system/bin/dex2oat" is left, or not even that. Use a pretty line. 145 return "Starting dex2oat."; 146 } 147 return Join(command, ' '); 148} 149 150static void UsageErrorV(const char* fmt, va_list ap) { 151 std::string error; 152 StringAppendV(&error, fmt, ap); 153 LOG(ERROR) << error; 154} 155 156static void UsageError(const char* fmt, ...) { 157 va_list ap; 158 va_start(ap, fmt); 159 UsageErrorV(fmt, ap); 160 va_end(ap); 161} 162 163NO_RETURN static void Usage(const char* fmt, ...) { 164 va_list ap; 165 va_start(ap, fmt); 166 UsageErrorV(fmt, ap); 167 va_end(ap); 168 169 UsageError("Command: %s", CommandLine().c_str()); 170 171 UsageError("Usage: dex2oat [options]..."); 172 UsageError(""); 173 UsageError(" -j<number>: specifies the number of threads used for compilation."); 174 UsageError(" Default is the number of detected hardware threads available on the"); 175 UsageError(" host system."); 176 UsageError(" Example: -j12"); 177 UsageError(""); 178 UsageError(" --dex-file=<dex-file>: specifies a .dex, .jar, or .apk file to compile."); 179 UsageError(" Example: --dex-file=/system/framework/core.jar"); 180 UsageError(""); 181 UsageError(" --dex-location=<dex-location>: specifies an alternative dex location to"); 182 UsageError(" encode in the oat file for the corresponding --dex-file argument."); 183 UsageError(" Example: --dex-file=/home/build/out/system/framework/core.jar"); 184 UsageError(" --dex-location=/system/framework/core.jar"); 185 UsageError(""); 186 UsageError(" --zip-fd=<file-descriptor>: specifies a file descriptor of a zip file"); 187 UsageError(" containing a classes.dex file to compile."); 188 UsageError(" Example: --zip-fd=5"); 189 UsageError(""); 190 UsageError(" --zip-location=<zip-location>: specifies a symbolic name for the file"); 191 UsageError(" corresponding to the file descriptor specified by --zip-fd."); 192 UsageError(" Example: --zip-location=/system/app/Calculator.apk"); 193 UsageError(""); 194 UsageError(" --oat-file=<file.oat>: specifies the oat output destination via a filename."); 195 UsageError(" Example: --oat-file=/system/framework/boot.oat"); 196 UsageError(""); 197 UsageError(" --oat-fd=<number>: specifies the oat output destination via a file descriptor."); 198 UsageError(" Example: --oat-fd=6"); 199 UsageError(""); 200 UsageError(" --oat-location=<oat-name>: specifies a symbolic name for the file corresponding"); 201 UsageError(" to the file descriptor specified by --oat-fd."); 202 UsageError(" Example: --oat-location=/data/dalvik-cache/system@app@Calculator.apk.oat"); 203 UsageError(""); 204 UsageError(" --oat-symbols=<file.oat>: specifies the oat output destination with full symbols."); 205 UsageError(" Example: --oat-symbols=/symbols/system/framework/boot.oat"); 206 UsageError(""); 207 UsageError(" --image=<file.art>: specifies the output image filename."); 208 UsageError(" Example: --image=/system/framework/boot.art"); 209 UsageError(""); 210 UsageError(" --image-classes=<classname-file>: specifies classes to include in an image."); 211 UsageError(" Example: --image=frameworks/base/preloaded-classes"); 212 UsageError(""); 213 UsageError(" --base=<hex-address>: specifies the base address when creating a boot image."); 214 UsageError(" Example: --base=0x50000000"); 215 UsageError(""); 216 UsageError(" --boot-image=<file.art>: provide the image file for the boot class path."); 217 UsageError(" Example: --boot-image=/system/framework/boot.art"); 218 UsageError(" Default: $ANDROID_ROOT/system/framework/boot.art"); 219 UsageError(""); 220 UsageError(" --android-root=<path>: used to locate libraries for portable linking."); 221 UsageError(" Example: --android-root=out/host/linux-x86"); 222 UsageError(" Default: $ANDROID_ROOT"); 223 UsageError(""); 224 UsageError(" --instruction-set=(arm|arm64|mips|mips64|x86|x86_64): compile for a particular"); 225 UsageError(" instruction set."); 226 UsageError(" Example: --instruction-set=x86"); 227 UsageError(" Default: arm"); 228 UsageError(""); 229 UsageError(" --instruction-set-features=...,: Specify instruction set features"); 230 UsageError(" Example: --instruction-set-features=div"); 231 UsageError(" Default: default"); 232 UsageError(""); 233 UsageError(" --compile-pic: Force indirect use of code, methods, and classes"); 234 UsageError(" Default: disabled"); 235 UsageError(""); 236 UsageError(" --compiler-backend=(Quick|Optimizing): select compiler backend"); 237 UsageError(" set."); 238 UsageError(" Example: --compiler-backend=Optimizing"); 239 UsageError(" Default: Optimizing"); 240 UsageError(""); 241 UsageError(" --compiler-filter=" 242 "(verify-none" 243 "|interpret-only" 244 "|space" 245 "|balanced" 246 "|speed" 247 "|everything" 248 "|time):"); 249 UsageError(" select compiler filter."); 250 UsageError(" Example: --compiler-filter=everything"); 251 UsageError(" Default: speed"); 252 UsageError(""); 253 UsageError(" --huge-method-max=<method-instruction-count>: threshold size for a huge"); 254 UsageError(" method for compiler filter tuning."); 255 UsageError(" Example: --huge-method-max=%d", CompilerOptions::kDefaultHugeMethodThreshold); 256 UsageError(" Default: %d", CompilerOptions::kDefaultHugeMethodThreshold); 257 UsageError(""); 258 UsageError(" --large-method-max=<method-instruction-count>: threshold size for a large"); 259 UsageError(" method for compiler filter tuning."); 260 UsageError(" Example: --large-method-max=%d", CompilerOptions::kDefaultLargeMethodThreshold); 261 UsageError(" Default: %d", CompilerOptions::kDefaultLargeMethodThreshold); 262 UsageError(""); 263 UsageError(" --small-method-max=<method-instruction-count>: threshold size for a small"); 264 UsageError(" method for compiler filter tuning."); 265 UsageError(" Example: --small-method-max=%d", CompilerOptions::kDefaultSmallMethodThreshold); 266 UsageError(" Default: %d", CompilerOptions::kDefaultSmallMethodThreshold); 267 UsageError(""); 268 UsageError(" --tiny-method-max=<method-instruction-count>: threshold size for a tiny"); 269 UsageError(" method for compiler filter tuning."); 270 UsageError(" Example: --tiny-method-max=%d", CompilerOptions::kDefaultTinyMethodThreshold); 271 UsageError(" Default: %d", CompilerOptions::kDefaultTinyMethodThreshold); 272 UsageError(""); 273 UsageError(" --num-dex-methods=<method-count>: threshold size for a small dex file for"); 274 UsageError(" compiler filter tuning. If the input has fewer than this many methods"); 275 UsageError(" and the filter is not interpret-only or verify-none, overrides the"); 276 UsageError(" filter to use speed"); 277 UsageError(" Example: --num-dex-method=%d", CompilerOptions::kDefaultNumDexMethodsThreshold); 278 UsageError(" Default: %d", CompilerOptions::kDefaultNumDexMethodsThreshold); 279 UsageError(""); 280 UsageError(" --inline-depth-limit=<depth-limit>: the depth limit of inlining for fine tuning"); 281 UsageError(" the compiler. A zero value will disable inlining. Honored only by Optimizing."); 282 UsageError(" Has priority over the --compiler-filter option. Intended for "); 283 UsageError(" development/experimental use."); 284 UsageError(" Example: --inline-depth-limit=%d", CompilerOptions::kDefaultInlineDepthLimit); 285 UsageError(" Default: %d", CompilerOptions::kDefaultInlineDepthLimit); 286 UsageError(""); 287 UsageError(" --inline-max-code-units=<code-units-count>: the maximum code units that a method"); 288 UsageError(" can have to be considered for inlining. A zero value will disable inlining."); 289 UsageError(" Honored only by Optimizing. Has priority over the --compiler-filter option."); 290 UsageError(" Intended for development/experimental use."); 291 UsageError(" Example: --inline-max-code-units=%d", 292 CompilerOptions::kDefaultInlineMaxCodeUnits); 293 UsageError(" Default: %d", CompilerOptions::kDefaultInlineMaxCodeUnits); 294 UsageError(""); 295 UsageError(" --dump-timing: display a breakdown of where time was spent"); 296 UsageError(""); 297 UsageError(" --include-patch-information: Include patching information so the generated code"); 298 UsageError(" can have its base address moved without full recompilation."); 299 UsageError(""); 300 UsageError(" --no-include-patch-information: Do not include patching information."); 301 UsageError(""); 302 UsageError(" -g"); 303 UsageError(" --generate-debug-info: Generate debug information for native debugging,"); 304 UsageError(" such as stack unwinding information, ELF symbols and DWARF sections."); 305 UsageError(" This generates all the available information. Unneeded parts can be"); 306 UsageError(" stripped using standard command line tools such as strip or objcopy."); 307 UsageError(" (enabled by default in debug builds, disabled by default otherwise)"); 308 UsageError(""); 309 UsageError(" --debuggable: Produce debuggable code. Implies --generate-debug-info."); 310 UsageError(""); 311 UsageError(" --no-generate-debug-info: Do not generate debug information for native debugging."); 312 UsageError(""); 313 UsageError(" --runtime-arg <argument>: used to specify various arguments for the runtime,"); 314 UsageError(" such as initial heap size, maximum heap size, and verbose output."); 315 UsageError(" Use a separate --runtime-arg switch for each argument."); 316 UsageError(" Example: --runtime-arg -Xms256m"); 317 UsageError(""); 318 UsageError(" --profile-file=<filename>: specify profiler output file to use for compilation."); 319 UsageError(""); 320 UsageError(" --print-pass-names: print a list of pass names"); 321 UsageError(""); 322 UsageError(" --disable-passes=<pass-names>: disable one or more passes separated by comma."); 323 UsageError(" Example: --disable-passes=UseCount,BBOptimizations"); 324 UsageError(""); 325 UsageError(" --print-pass-options: print a list of passes that have configurable options along " 326 "with the setting."); 327 UsageError(" Will print default if no overridden setting exists."); 328 UsageError(""); 329 UsageError(" --pass-options=Pass1Name:Pass1OptionName:Pass1Option#," 330 "Pass2Name:Pass2OptionName:Pass2Option#"); 331 UsageError(" Used to specify a pass specific option. The setting itself must be integer."); 332 UsageError(" Separator used between options is a comma."); 333 UsageError(""); 334 UsageError(" --swap-file=<file-name>: specifies a file to use for swap."); 335 UsageError(" Example: --swap-file=/data/tmp/swap.001"); 336 UsageError(""); 337 UsageError(" --swap-fd=<file-descriptor>: specifies a file to use for swap (by descriptor)."); 338 UsageError(" Example: --swap-fd=10"); 339 UsageError(""); 340 UsageError(" --app-image-fd=<file-descriptor>: specify output file descriptor for app image."); 341 UsageError(" Example: --app-image-fd=10"); 342 UsageError(""); 343 UsageError(" --app-image-file=<file-name>: specify a file name for app image."); 344 UsageError(" Example: --app-image-file=/data/dalvik-cache/system@app@Calculator.apk.art"); 345 UsageError(""); 346 std::cerr << "See log for usage error information\n"; 347 exit(EXIT_FAILURE); 348} 349 350// The primary goal of the watchdog is to prevent stuck build servers 351// during development when fatal aborts lead to a cascade of failures 352// that result in a deadlock. 353class WatchDog { 354// WatchDog defines its own CHECK_PTHREAD_CALL to avoid using LOG which uses locks 355#undef CHECK_PTHREAD_CALL 356#define CHECK_WATCH_DOG_PTHREAD_CALL(call, args, what) \ 357 do { \ 358 int rc = call args; \ 359 if (rc != 0) { \ 360 errno = rc; \ 361 std::string message(# call); \ 362 message += " failed for "; \ 363 message += reason; \ 364 Fatal(message); \ 365 } \ 366 } while (false) 367 368 public: 369 explicit WatchDog(bool is_watch_dog_enabled) { 370 is_watch_dog_enabled_ = is_watch_dog_enabled; 371 if (!is_watch_dog_enabled_) { 372 return; 373 } 374 shutting_down_ = false; 375 const char* reason = "dex2oat watch dog thread startup"; 376 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_init, (&mutex_, nullptr), reason); 377 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_init, (&cond_, nullptr), reason); 378 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_init, (&attr_), reason); 379 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_create, (&pthread_, &attr_, &CallBack, this), reason); 380 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_destroy, (&attr_), reason); 381 } 382 ~WatchDog() { 383 if (!is_watch_dog_enabled_) { 384 return; 385 } 386 const char* reason = "dex2oat watch dog thread shutdown"; 387 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason); 388 shutting_down_ = true; 389 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_signal, (&cond_), reason); 390 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason); 391 392 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_join, (pthread_, nullptr), reason); 393 394 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_destroy, (&cond_), reason); 395 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_destroy, (&mutex_), reason); 396 } 397 398 private: 399 static void* CallBack(void* arg) { 400 WatchDog* self = reinterpret_cast<WatchDog*>(arg); 401 ::art::SetThreadName("dex2oat watch dog"); 402 self->Wait(); 403 return nullptr; 404 } 405 406 NO_RETURN static void Fatal(const std::string& message) { 407 // TODO: When we can guarantee it won't prevent shutdown in error cases, move to LOG. However, 408 // it's rather easy to hang in unwinding. 409 // LogLine also avoids ART logging lock issues, as it's really only a wrapper around 410 // logcat logging or stderr output. 411 LogMessage::LogLine(__FILE__, __LINE__, LogSeverity::FATAL, message.c_str()); 412 exit(1); 413 } 414 415 void Wait() { 416 // TODO: tune the multiplier for GC verification, the following is just to make the timeout 417 // large. 418 constexpr int64_t multiplier = kVerifyObjectSupport > kVerifyObjectModeFast ? 100 : 1; 419 timespec timeout_ts; 420 InitTimeSpec(true, CLOCK_REALTIME, multiplier * kWatchDogTimeoutSeconds * 1000, 0, &timeout_ts); 421 const char* reason = "dex2oat watch dog thread waiting"; 422 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason); 423 while (!shutting_down_) { 424 int rc = TEMP_FAILURE_RETRY(pthread_cond_timedwait(&cond_, &mutex_, &timeout_ts)); 425 if (rc == ETIMEDOUT) { 426 Fatal(StringPrintf("dex2oat did not finish after %" PRId64 " seconds", 427 kWatchDogTimeoutSeconds)); 428 } else if (rc != 0) { 429 std::string message(StringPrintf("pthread_cond_timedwait failed: %s", 430 strerror(errno))); 431 Fatal(message.c_str()); 432 } 433 } 434 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason); 435 } 436 437 // When setting timeouts, keep in mind that the build server may not be as fast as your desktop. 438 // Debug builds are slower so they have larger timeouts. 439 static constexpr int64_t kSlowdownFactor = kIsDebugBuild ? 5U : 1U; 440 441 // 9.5 minutes scaled by kSlowdownFactor. This is slightly smaller than the Package Manager 442 // watchdog (PackageManagerService.WATCHDOG_TIMEOUT, 10 minutes), so that dex2oat will abort 443 // itself before that watchdog would take down the system server. 444 static constexpr int64_t kWatchDogTimeoutSeconds = kSlowdownFactor * (9 * 60 + 30); 445 446 bool is_watch_dog_enabled_; 447 bool shutting_down_; 448 // TODO: Switch to Mutex when we can guarantee it won't prevent shutdown in error cases. 449 pthread_mutex_t mutex_; 450 pthread_cond_t cond_; 451 pthread_attr_t attr_; 452 pthread_t pthread_; 453}; 454 455static constexpr size_t kMinDexFilesForSwap = 2; 456static constexpr size_t kMinDexFileCumulativeSizeForSwap = 20 * MB; 457 458static bool UseSwap(bool is_image, std::vector<const DexFile*>& dex_files) { 459 if (is_image) { 460 // Don't use swap, we know generation should succeed, and we don't want to slow it down. 461 return false; 462 } 463 if (dex_files.size() < kMinDexFilesForSwap) { 464 // If there are less dex files than the threshold, assume it's gonna be fine. 465 return false; 466 } 467 size_t dex_files_size = 0; 468 for (const auto* dex_file : dex_files) { 469 dex_files_size += dex_file->GetHeader().file_size_; 470 } 471 return dex_files_size >= kMinDexFileCumulativeSizeForSwap; 472} 473 474class Dex2Oat FINAL { 475 public: 476 explicit Dex2Oat(TimingLogger* timings) : 477 compiler_kind_(Compiler::kOptimizing), 478 instruction_set_(kRuntimeISA), 479 // Take the default set of instruction features from the build. 480 verification_results_(nullptr), 481 method_inliner_map_(), 482 runtime_(nullptr), 483 thread_count_(sysconf(_SC_NPROCESSORS_CONF)), 484 start_ns_(NanoTime()), 485 oat_fd_(-1), 486 zip_fd_(-1), 487 image_base_(0U), 488 image_classes_zip_filename_(nullptr), 489 image_classes_filename_(nullptr), 490 compiled_classes_zip_filename_(nullptr), 491 compiled_classes_filename_(nullptr), 492 compiled_methods_zip_filename_(nullptr), 493 compiled_methods_filename_(nullptr), 494 app_image_(false), 495 boot_image_(false), 496 is_host_(false), 497 driver_(nullptr), 498 dump_stats_(false), 499 dump_passes_(false), 500 dump_timing_(false), 501 dump_slow_timing_(kIsDebugBuild), 502 dump_cfg_append_(false), 503 swap_fd_(-1), 504 app_image_fd_(kInvalidImageFd), 505 timings_(timings) {} 506 507 ~Dex2Oat() { 508 // Free opened dex files before deleting the runtime_, because ~DexFile 509 // uses MemMap, which is shut down by ~Runtime. 510 class_path_files_.clear(); 511 opened_dex_files_.clear(); 512 513 // Log completion time before deleting the runtime_, because this accesses 514 // the runtime. 515 LogCompletionTime(); 516 517 if (!kIsDebugBuild && !(RUNNING_ON_MEMORY_TOOL && kMemoryToolDetectsLeaks)) { 518 // We want to just exit on non-debug builds, not bringing the runtime down 519 // in an orderly fashion. So release the following fields. 520 driver_.release(); 521 image_writer_.release(); 522 for (std::unique_ptr<const DexFile>& dex_file : opened_dex_files_) { 523 dex_file.release(); 524 } 525 oat_file_.release(); 526 runtime_.release(); 527 verification_results_.release(); 528 key_value_store_.release(); 529 } 530 } 531 532 struct ParserOptions { 533 std::string oat_symbols; 534 std::string boot_image_filename; 535 bool watch_dog_enabled = true; 536 bool requested_specific_compiler = false; 537 std::string error_msg; 538 }; 539 540 void ParseZipFd(const StringPiece& option) { 541 ParseUintOption(option, "--zip-fd", &zip_fd_, Usage); 542 } 543 544 void ParseOatFd(const StringPiece& option) { 545 ParseUintOption(option, "--oat-fd", &oat_fd_, Usage); 546 } 547 548 void ParseJ(const StringPiece& option) { 549 ParseUintOption(option, "-j", &thread_count_, Usage, /* is_long_option */ false); 550 } 551 552 void ParseBase(const StringPiece& option) { 553 DCHECK(option.starts_with("--base=")); 554 const char* image_base_str = option.substr(strlen("--base=")).data(); 555 char* end; 556 image_base_ = strtoul(image_base_str, &end, 16); 557 if (end == image_base_str || *end != '\0') { 558 Usage("Failed to parse hexadecimal value for option %s", option.data()); 559 } 560 } 561 562 void ParseInstructionSet(const StringPiece& option) { 563 DCHECK(option.starts_with("--instruction-set=")); 564 StringPiece instruction_set_str = option.substr(strlen("--instruction-set=")).data(); 565 // StringPiece is not necessarily zero-terminated, so need to make a copy and ensure it. 566 std::unique_ptr<char[]> buf(new char[instruction_set_str.length() + 1]); 567 strncpy(buf.get(), instruction_set_str.data(), instruction_set_str.length()); 568 buf.get()[instruction_set_str.length()] = 0; 569 instruction_set_ = GetInstructionSetFromString(buf.get()); 570 // arm actually means thumb2. 571 if (instruction_set_ == InstructionSet::kArm) { 572 instruction_set_ = InstructionSet::kThumb2; 573 } 574 } 575 576 void ParseInstructionSetVariant(const StringPiece& option, ParserOptions* parser_options) { 577 DCHECK(option.starts_with("--instruction-set-variant=")); 578 StringPiece str = option.substr(strlen("--instruction-set-variant=")).data(); 579 instruction_set_features_.reset( 580 InstructionSetFeatures::FromVariant( 581 instruction_set_, str.as_string(), &parser_options->error_msg)); 582 if (instruction_set_features_.get() == nullptr) { 583 Usage("%s", parser_options->error_msg.c_str()); 584 } 585 } 586 587 void ParseInstructionSetFeatures(const StringPiece& option, ParserOptions* parser_options) { 588 DCHECK(option.starts_with("--instruction-set-features=")); 589 StringPiece str = option.substr(strlen("--instruction-set-features=")).data(); 590 if (instruction_set_features_.get() == nullptr) { 591 instruction_set_features_.reset( 592 InstructionSetFeatures::FromVariant( 593 instruction_set_, "default", &parser_options->error_msg)); 594 if (instruction_set_features_.get() == nullptr) { 595 Usage("Problem initializing default instruction set features variant: %s", 596 parser_options->error_msg.c_str()); 597 } 598 } 599 instruction_set_features_.reset( 600 instruction_set_features_->AddFeaturesFromString(str.as_string(), 601 &parser_options->error_msg)); 602 if (instruction_set_features_.get() == nullptr) { 603 Usage("Error parsing '%s': %s", option.data(), parser_options->error_msg.c_str()); 604 } 605 } 606 607 void ParseCompilerBackend(const StringPiece& option, ParserOptions* parser_options) { 608 DCHECK(option.starts_with("--compiler-backend=")); 609 parser_options->requested_specific_compiler = true; 610 StringPiece backend_str = option.substr(strlen("--compiler-backend=")).data(); 611 if (backend_str == "Quick") { 612 compiler_kind_ = Compiler::kQuick; 613 } else if (backend_str == "Optimizing") { 614 compiler_kind_ = Compiler::kOptimizing; 615 } else { 616 Usage("Unknown compiler backend: %s", backend_str.data()); 617 } 618 } 619 620 void ProcessOptions(ParserOptions* parser_options) { 621 boot_image_ = !image_filename_.empty(); 622 app_image_ = app_image_fd_ != -1 || !app_image_file_name_.empty(); 623 624 if (IsAppImage() && IsBootImage()) { 625 Usage("Can't have both --image and (--app-image-fd or --app-image-file)"); 626 } 627 628 if (IsBootImage()) { 629 // We need the boot image to always be debuggable. 630 compiler_options_->debuggable_ = true; 631 } 632 633 if (oat_filename_.empty() && oat_fd_ == -1) { 634 Usage("Output must be supplied with either --oat-file or --oat-fd"); 635 } 636 637 if (!oat_filename_.empty() && oat_fd_ != -1) { 638 Usage("--oat-file should not be used with --oat-fd"); 639 } 640 641 if (!parser_options->oat_symbols.empty() && oat_fd_ != -1) { 642 Usage("--oat-symbols should not be used with --oat-fd"); 643 } 644 645 if (!parser_options->oat_symbols.empty() && is_host_) { 646 Usage("--oat-symbols should not be used with --host"); 647 } 648 649 if (oat_fd_ != -1 && !image_filename_.empty()) { 650 Usage("--oat-fd should not be used with --image"); 651 } 652 653 if (android_root_.empty()) { 654 const char* android_root_env_var = getenv("ANDROID_ROOT"); 655 if (android_root_env_var == nullptr) { 656 Usage("--android-root unspecified and ANDROID_ROOT not set"); 657 } 658 android_root_ += android_root_env_var; 659 } 660 661 if (!boot_image_ && parser_options->boot_image_filename.empty()) { 662 parser_options->boot_image_filename += android_root_; 663 parser_options->boot_image_filename += "/framework/boot.art"; 664 } 665 if (!parser_options->boot_image_filename.empty()) { 666 boot_image_option_ += "-Ximage:"; 667 boot_image_option_ += parser_options->boot_image_filename; 668 } 669 670 if (image_classes_filename_ != nullptr && !IsBootImage()) { 671 Usage("--image-classes should only be used with --image"); 672 } 673 674 if (image_classes_filename_ != nullptr && !boot_image_option_.empty()) { 675 Usage("--image-classes should not be used with --boot-image"); 676 } 677 678 if (image_classes_zip_filename_ != nullptr && image_classes_filename_ == nullptr) { 679 Usage("--image-classes-zip should be used with --image-classes"); 680 } 681 682 if (compiled_classes_filename_ != nullptr && !IsBootImage()) { 683 Usage("--compiled-classes should only be used with --image"); 684 } 685 686 if (compiled_classes_filename_ != nullptr && !boot_image_option_.empty()) { 687 Usage("--compiled-classes should not be used with --boot-image"); 688 } 689 690 if (compiled_classes_zip_filename_ != nullptr && compiled_classes_filename_ == nullptr) { 691 Usage("--compiled-classes-zip should be used with --compiled-classes"); 692 } 693 694 if (dex_filenames_.empty() && zip_fd_ == -1) { 695 Usage("Input must be supplied with either --dex-file or --zip-fd"); 696 } 697 698 if (!dex_filenames_.empty() && zip_fd_ != -1) { 699 Usage("--dex-file should not be used with --zip-fd"); 700 } 701 702 if (!dex_filenames_.empty() && !zip_location_.empty()) { 703 Usage("--dex-file should not be used with --zip-location"); 704 } 705 706 if (dex_locations_.empty()) { 707 for (const char* dex_file_name : dex_filenames_) { 708 dex_locations_.push_back(dex_file_name); 709 } 710 } else if (dex_locations_.size() != dex_filenames_.size()) { 711 Usage("--dex-location arguments do not match --dex-file arguments"); 712 } 713 714 if (zip_fd_ != -1 && zip_location_.empty()) { 715 Usage("--zip-location should be supplied with --zip-fd"); 716 } 717 718 if (boot_image_option_.empty()) { 719 if (image_base_ == 0) { 720 Usage("Non-zero --base not specified"); 721 } 722 } 723 724 oat_stripped_ = oat_filename_; 725 if (!parser_options->oat_symbols.empty()) { 726 oat_unstripped_ = parser_options->oat_symbols; 727 } else { 728 oat_unstripped_ = oat_filename_; 729 } 730 731 // If no instruction set feature was given, use the default one for the target 732 // instruction set. 733 if (instruction_set_features_.get() == nullptr) { 734 instruction_set_features_.reset( 735 InstructionSetFeatures::FromVariant( 736 instruction_set_, "default", &parser_options->error_msg)); 737 if (instruction_set_features_.get() == nullptr) { 738 Usage("Problem initializing default instruction set features variant: %s", 739 parser_options->error_msg.c_str()); 740 } 741 } 742 743 if (instruction_set_ == kRuntimeISA) { 744 std::unique_ptr<const InstructionSetFeatures> runtime_features( 745 InstructionSetFeatures::FromCppDefines()); 746 if (!instruction_set_features_->Equals(runtime_features.get())) { 747 LOG(WARNING) << "Mismatch between dex2oat instruction set features (" 748 << *instruction_set_features_ << ") and those of dex2oat executable (" 749 << *runtime_features <<") for the command line:\n" 750 << CommandLine(); 751 } 752 } 753 754 // It they are not set, use default values for inlining settings. 755 // TODO: We should rethink the compiler filter. We mostly save 756 // time here, which is orthogonal to space. 757 if (compiler_options_->inline_depth_limit_ == CompilerOptions::kUnsetInlineDepthLimit) { 758 compiler_options_->inline_depth_limit_ = 759 (compiler_options_->compiler_filter_ == CompilerOptions::kSpace) 760 // Implementation of the space filter: limit inlining depth. 761 ? CompilerOptions::kSpaceFilterInlineDepthLimit 762 : CompilerOptions::kDefaultInlineDepthLimit; 763 } 764 if (compiler_options_->inline_max_code_units_ == CompilerOptions::kUnsetInlineMaxCodeUnits) { 765 compiler_options_->inline_max_code_units_ = 766 (compiler_options_->compiler_filter_ == CompilerOptions::kSpace) 767 // Implementation of the space filter: limit inlining max code units. 768 ? CompilerOptions::kSpaceFilterInlineMaxCodeUnits 769 : CompilerOptions::kDefaultInlineMaxCodeUnits; 770 } 771 772 // Checks are all explicit until we know the architecture. 773 // Set the compilation target's implicit checks options. 774 switch (instruction_set_) { 775 case kArm: 776 case kThumb2: 777 case kArm64: 778 case kX86: 779 case kX86_64: 780 case kMips: 781 case kMips64: 782 compiler_options_->implicit_null_checks_ = true; 783 compiler_options_->implicit_so_checks_ = true; 784 break; 785 786 default: 787 // Defaults are correct. 788 break; 789 } 790 791 compiler_options_->verbose_methods_ = verbose_methods_.empty() ? nullptr : &verbose_methods_; 792 793 // Done with usage checks, enable watchdog if requested 794 if (parser_options->watch_dog_enabled) { 795 watchdog_.reset(new WatchDog(true)); 796 } 797 798 // Fill some values into the key-value store for the oat header. 799 key_value_store_.reset(new SafeMap<std::string, std::string>()); 800 } 801 802 void InsertCompileOptions(int argc, char** argv) { 803 std::ostringstream oss; 804 for (int i = 0; i < argc; ++i) { 805 if (i > 0) { 806 oss << ' '; 807 } 808 oss << argv[i]; 809 } 810 key_value_store_->Put(OatHeader::kDex2OatCmdLineKey, oss.str()); 811 oss.str(""); // Reset. 812 oss << kRuntimeISA; 813 key_value_store_->Put(OatHeader::kDex2OatHostKey, oss.str()); 814 key_value_store_->Put( 815 OatHeader::kPicKey, 816 compiler_options_->compile_pic_ ? OatHeader::kTrueValue : OatHeader::kFalseValue); 817 key_value_store_->Put( 818 OatHeader::kDebuggableKey, 819 compiler_options_->debuggable_ ? OatHeader::kTrueValue : OatHeader::kFalseValue); 820 } 821 822 // Parse the arguments from the command line. In case of an unrecognized option or impossible 823 // values/combinations, a usage error will be displayed and exit() is called. Thus, if the method 824 // returns, arguments have been successfully parsed. 825 void ParseArgs(int argc, char** argv) { 826 original_argc = argc; 827 original_argv = argv; 828 829 InitLogging(argv); 830 831 // Skip over argv[0]. 832 argv++; 833 argc--; 834 835 if (argc == 0) { 836 Usage("No arguments specified"); 837 } 838 839 std::unique_ptr<ParserOptions> parser_options(new ParserOptions()); 840 compiler_options_.reset(new CompilerOptions()); 841 842 for (int i = 0; i < argc; i++) { 843 const StringPiece option(argv[i]); 844 const bool log_options = false; 845 if (log_options) { 846 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i]; 847 } 848 if (option.starts_with("--dex-file=")) { 849 dex_filenames_.push_back(option.substr(strlen("--dex-file=")).data()); 850 } else if (option.starts_with("--dex-location=")) { 851 dex_locations_.push_back(option.substr(strlen("--dex-location=")).data()); 852 } else if (option.starts_with("--zip-fd=")) { 853 ParseZipFd(option); 854 } else if (option.starts_with("--zip-location=")) { 855 zip_location_ = option.substr(strlen("--zip-location=")).data(); 856 } else if (option.starts_with("--oat-file=")) { 857 oat_filename_ = option.substr(strlen("--oat-file=")).data(); 858 } else if (option.starts_with("--oat-symbols=")) { 859 parser_options->oat_symbols = option.substr(strlen("--oat-symbols=")).data(); 860 } else if (option.starts_with("--oat-fd=")) { 861 ParseOatFd(option); 862 } else if (option == "--watch-dog") { 863 parser_options->watch_dog_enabled = true; 864 } else if (option == "--no-watch-dog") { 865 parser_options->watch_dog_enabled = false; 866 } else if (option.starts_with("-j")) { 867 ParseJ(option); 868 } else if (option.starts_with("--oat-location=")) { 869 oat_location_ = option.substr(strlen("--oat-location=")).data(); 870 } else if (option.starts_with("--image=")) { 871 image_filename_ = option.substr(strlen("--image=")).data(); 872 } else if (option.starts_with("--image-classes=")) { 873 image_classes_filename_ = option.substr(strlen("--image-classes=")).data(); 874 } else if (option.starts_with("--image-classes-zip=")) { 875 image_classes_zip_filename_ = option.substr(strlen("--image-classes-zip=")).data(); 876 } else if (option.starts_with("--compiled-classes=")) { 877 compiled_classes_filename_ = option.substr(strlen("--compiled-classes=")).data(); 878 } else if (option.starts_with("--compiled-classes-zip=")) { 879 compiled_classes_zip_filename_ = option.substr(strlen("--compiled-classes-zip=")).data(); 880 } else if (option.starts_with("--compiled-methods=")) { 881 compiled_methods_filename_ = option.substr(strlen("--compiled-methods=")).data(); 882 } else if (option.starts_with("--compiled-methods-zip=")) { 883 compiled_methods_zip_filename_ = option.substr(strlen("--compiled-methods-zip=")).data(); 884 } else if (option.starts_with("--base=")) { 885 ParseBase(option); 886 } else if (option.starts_with("--boot-image=")) { 887 parser_options->boot_image_filename = option.substr(strlen("--boot-image=")).data(); 888 } else if (option.starts_with("--android-root=")) { 889 android_root_ = option.substr(strlen("--android-root=")).data(); 890 } else if (option.starts_with("--instruction-set=")) { 891 ParseInstructionSet(option); 892 } else if (option.starts_with("--instruction-set-variant=")) { 893 ParseInstructionSetVariant(option, parser_options.get()); 894 } else if (option.starts_with("--instruction-set-features=")) { 895 ParseInstructionSetFeatures(option, parser_options.get()); 896 } else if (option.starts_with("--compiler-backend=")) { 897 ParseCompilerBackend(option, parser_options.get()); 898 } else if (option.starts_with("--profile-file=")) { 899 profile_file_ = option.substr(strlen("--profile-file=")).data(); 900 VLOG(compiler) << "dex2oat: profile file is " << profile_file_; 901 } else if (option == "--no-profile-file") { 902 // No profile 903 } else if (option == "--host") { 904 is_host_ = true; 905 } else if (option == "--runtime-arg") { 906 if (++i >= argc) { 907 Usage("Missing required argument for --runtime-arg"); 908 } 909 if (log_options) { 910 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i]; 911 } 912 runtime_args_.push_back(argv[i]); 913 } else if (option == "--dump-timing") { 914 dump_timing_ = true; 915 } else if (option == "--dump-passes") { 916 dump_passes_ = true; 917 } else if (option.starts_with("--dump-cfg=")) { 918 dump_cfg_file_name_ = option.substr(strlen("--dump-cfg=")).data(); 919 } else if (option.starts_with("--dump-cfg-append")) { 920 dump_cfg_append_ = true; 921 } else if (option == "--dump-stats") { 922 dump_stats_ = true; 923 } else if (option.starts_with("--swap-file=")) { 924 swap_file_name_ = option.substr(strlen("--swap-file=")).data(); 925 } else if (option.starts_with("--swap-fd=")) { 926 ParseUintOption(option, "--swap-fd", &swap_fd_, Usage); 927 } else if (option.starts_with("--app-image-file=")) { 928 app_image_file_name_ = option.substr(strlen("--app-image-file=")).data(); 929 } else if (option.starts_with("--app-image-fd=")) { 930 ParseUintOption(option, "--app-image-fd", &app_image_fd_, Usage); 931 } else if (option.starts_with("--verbose-methods=")) { 932 // TODO: rather than switch off compiler logging, make all VLOG(compiler) messages 933 // conditional on having verbost methods. 934 gLogVerbosity.compiler = false; 935 Split(option.substr(strlen("--verbose-methods=")).ToString(), ',', &verbose_methods_); 936 } else if (!compiler_options_->ParseCompilerOption(option, Usage)) { 937 Usage("Unknown argument %s", option.data()); 938 } 939 } 940 941 ProcessOptions(parser_options.get()); 942 943 // Insert some compiler things. 944 InsertCompileOptions(argc, argv); 945 } 946 947 // Check whether the oat output file is writable, and open it for later. Also open a swap file, 948 // if a name is given. 949 bool OpenFile() { 950 bool create_file = !oat_unstripped_.empty(); // as opposed to using open file descriptor 951 if (create_file) { 952 oat_file_.reset(OS::CreateEmptyFile(oat_unstripped_.c_str())); 953 if (oat_location_.empty()) { 954 oat_location_ = oat_filename_; 955 } 956 } else { 957 oat_file_.reset(new File(oat_fd_, oat_location_, true)); 958 oat_file_->DisableAutoClose(); 959 if (oat_file_->SetLength(0) != 0) { 960 PLOG(WARNING) << "Truncating oat file " << oat_location_ << " failed."; 961 } 962 } 963 if (oat_file_.get() == nullptr) { 964 PLOG(ERROR) << "Failed to create oat file: " << oat_location_; 965 return false; 966 } 967 if (create_file && fchmod(oat_file_->Fd(), 0644) != 0) { 968 PLOG(ERROR) << "Failed to make oat file world readable: " << oat_location_; 969 oat_file_->Erase(); 970 return false; 971 } 972 973 // Swap file handling. 974 // 975 // If the swap fd is not -1, we assume this is the file descriptor of an open but unlinked file 976 // that we can use for swap. 977 // 978 // If the swap fd is -1 and we have a swap-file string, open the given file as a swap file. We 979 // will immediately unlink to satisfy the swap fd assumption. 980 if (swap_fd_ == -1 && !swap_file_name_.empty()) { 981 std::unique_ptr<File> swap_file(OS::CreateEmptyFile(swap_file_name_.c_str())); 982 if (swap_file.get() == nullptr) { 983 PLOG(ERROR) << "Failed to create swap file: " << swap_file_name_; 984 return false; 985 } 986 swap_fd_ = swap_file->Fd(); 987 swap_file->MarkUnchecked(); // We don't we to track this, it will be unlinked immediately. 988 swap_file->DisableAutoClose(); // We'll handle it ourselves, the File object will be 989 // released immediately. 990 unlink(swap_file_name_.c_str()); 991 } 992 return true; 993 } 994 995 void EraseOatFile() { 996 DCHECK(oat_file_.get() != nullptr); 997 oat_file_->Erase(); 998 oat_file_.reset(); 999 } 1000 1001 void Shutdown() { 1002 ScopedObjectAccess soa(Thread::Current()); 1003 for (jobject dex_cache : dex_caches_) { 1004 soa.Env()->DeleteLocalRef(dex_cache); 1005 } 1006 dex_caches_.clear(); 1007 } 1008 1009 // Set up the environment for compilation. Includes starting the runtime and loading/opening the 1010 // boot class path. 1011 bool Setup() { 1012 TimingLogger::ScopedTiming t("dex2oat Setup", timings_); 1013 RuntimeOptions runtime_options; 1014 art::MemMap::Init(); // For ZipEntry::ExtractToMemMap. 1015 if (boot_image_option_.empty()) { 1016 std::string boot_class_path = "-Xbootclasspath:"; 1017 boot_class_path += Join(dex_filenames_, ':'); 1018 runtime_options.push_back(std::make_pair(boot_class_path, nullptr)); 1019 std::string boot_class_path_locations = "-Xbootclasspath-locations:"; 1020 boot_class_path_locations += Join(dex_locations_, ':'); 1021 runtime_options.push_back(std::make_pair(boot_class_path_locations, nullptr)); 1022 } else { 1023 runtime_options.push_back(std::make_pair(boot_image_option_, nullptr)); 1024 } 1025 for (size_t i = 0; i < runtime_args_.size(); i++) { 1026 runtime_options.push_back(std::make_pair(runtime_args_[i], nullptr)); 1027 } 1028 1029 verification_results_.reset(new VerificationResults(compiler_options_.get())); 1030 callbacks_.reset(new QuickCompilerCallbacks( 1031 verification_results_.get(), 1032 &method_inliner_map_, 1033 IsBootImage() ? 1034 CompilerCallbacks::CallbackMode::kCompileBootImage : 1035 CompilerCallbacks::CallbackMode::kCompileApp)); 1036 runtime_options.push_back(std::make_pair("compilercallbacks", callbacks_.get())); 1037 runtime_options.push_back( 1038 std::make_pair("imageinstructionset", GetInstructionSetString(instruction_set_))); 1039 1040 // Only allow no boot image for the runtime if we're compiling one. When we compile an app, 1041 // we don't want fallback mode, it will abort as we do not push a boot classpath (it might 1042 // have been stripped in preopting, anyways). 1043 if (!IsBootImage()) { 1044 runtime_options.push_back(std::make_pair("-Xno-dex-file-fallback", nullptr)); 1045 } 1046 // Disable libsigchain. We don't don't need it during compilation and it prevents us 1047 // from getting a statically linked version of dex2oat (because of dlsym and RTLD_NEXT). 1048 runtime_options.push_back(std::make_pair("-Xno-sig-chain", nullptr)); 1049 1050 { 1051 TimingLogger::ScopedTiming t_runtime("Create runtime", timings_); 1052 if (!CreateRuntime(runtime_options)) { 1053 return false; 1054 } 1055 } 1056 1057 // Runtime::Create acquired the mutator_lock_ that is normally given away when we 1058 // Runtime::Start, give it away now so that we don't starve GC. 1059 Thread* self = Thread::Current(); 1060 self->TransitionFromRunnableToSuspended(kNative); 1061 // If we're doing the image, override the compiler filter to force full compilation. Must be 1062 // done ahead of WellKnownClasses::Init that causes verification. Note: doesn't force 1063 // compilation of class initializers. 1064 // Whilst we're in native take the opportunity to initialize well known classes. 1065 WellKnownClasses::Init(self->GetJniEnv()); 1066 1067 // If --image-classes was specified, calculate the full list of classes to include in the image 1068 if (image_classes_filename_ != nullptr) { 1069 std::string error_msg; 1070 if (image_classes_zip_filename_ != nullptr) { 1071 image_classes_.reset(ReadImageClassesFromZip(image_classes_zip_filename_, 1072 image_classes_filename_, 1073 &error_msg)); 1074 } else { 1075 image_classes_.reset(ReadImageClassesFromFile(image_classes_filename_)); 1076 } 1077 if (image_classes_.get() == nullptr) { 1078 LOG(ERROR) << "Failed to create list of image classes from '" << image_classes_filename_ << 1079 "': " << error_msg; 1080 return false; 1081 } 1082 } else if (IsBootImage()) { 1083 image_classes_.reset(new std::unordered_set<std::string>); 1084 } 1085 // If --compiled-classes was specified, calculate the full list of classes to compile in the 1086 // image. 1087 if (compiled_classes_filename_ != nullptr) { 1088 std::string error_msg; 1089 if (compiled_classes_zip_filename_ != nullptr) { 1090 compiled_classes_.reset(ReadImageClassesFromZip(compiled_classes_zip_filename_, 1091 compiled_classes_filename_, 1092 &error_msg)); 1093 } else { 1094 compiled_classes_.reset(ReadImageClassesFromFile(compiled_classes_filename_)); 1095 } 1096 if (compiled_classes_.get() == nullptr) { 1097 LOG(ERROR) << "Failed to create list of compiled classes from '" 1098 << compiled_classes_filename_ << "': " << error_msg; 1099 return false; 1100 } 1101 } else { 1102 compiled_classes_.reset(nullptr); // By default compile everything. 1103 } 1104 // If --compiled-methods was specified, read the methods to compile from the given file(s). 1105 if (compiled_methods_filename_ != nullptr) { 1106 std::string error_msg; 1107 if (compiled_methods_zip_filename_ != nullptr) { 1108 compiled_methods_.reset(ReadCommentedInputFromZip(compiled_methods_zip_filename_, 1109 compiled_methods_filename_, 1110 nullptr, // No post-processing. 1111 &error_msg)); 1112 } else { 1113 compiled_methods_.reset(ReadCommentedInputFromFile(compiled_methods_filename_, 1114 nullptr)); // No post-processing. 1115 } 1116 if (compiled_methods_.get() == nullptr) { 1117 LOG(ERROR) << "Failed to create list of compiled methods from '" 1118 << compiled_methods_filename_ << "': " << error_msg; 1119 return false; 1120 } 1121 } else { 1122 compiled_methods_.reset(nullptr); // By default compile everything. 1123 } 1124 1125 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker(); 1126 if (boot_image_option_.empty()) { 1127 dex_files_ = class_linker->GetBootClassPath(); 1128 } else { 1129 TimingLogger::ScopedTiming t_dex("Opening dex files", timings_); 1130 if (dex_filenames_.empty()) { 1131 ATRACE_BEGIN("Opening zip archive from file descriptor"); 1132 std::string error_msg; 1133 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(zip_fd_, 1134 zip_location_.c_str(), 1135 &error_msg)); 1136 if (zip_archive.get() == nullptr) { 1137 LOG(ERROR) << "Failed to open zip from file descriptor for '" << zip_location_ << "': " 1138 << error_msg; 1139 return false; 1140 } 1141 if (!DexFile::OpenFromZip(*zip_archive.get(), zip_location_, &error_msg, &opened_dex_files_)) { 1142 LOG(ERROR) << "Failed to open dex from file descriptor for zip file '" << zip_location_ 1143 << "': " << error_msg; 1144 return false; 1145 } 1146 for (auto& dex_file : opened_dex_files_) { 1147 dex_files_.push_back(dex_file.get()); 1148 } 1149 ATRACE_END(); 1150 } else { 1151 size_t failure_count = OpenDexFiles(dex_filenames_, dex_locations_, &opened_dex_files_); 1152 if (failure_count > 0) { 1153 LOG(ERROR) << "Failed to open some dex files: " << failure_count; 1154 return false; 1155 } 1156 for (auto& dex_file : opened_dex_files_) { 1157 dex_files_.push_back(dex_file.get()); 1158 } 1159 } 1160 1161 constexpr bool kSaveDexInput = false; 1162 if (kSaveDexInput) { 1163 for (size_t i = 0; i < dex_files_.size(); ++i) { 1164 const DexFile* dex_file = dex_files_[i]; 1165 std::string tmp_file_name(StringPrintf("/data/local/tmp/dex2oat.%d.%zd.dex", 1166 getpid(), i)); 1167 std::unique_ptr<File> tmp_file(OS::CreateEmptyFile(tmp_file_name.c_str())); 1168 if (tmp_file.get() == nullptr) { 1169 PLOG(ERROR) << "Failed to open file " << tmp_file_name 1170 << ". Try: adb shell chmod 777 /data/local/tmp"; 1171 continue; 1172 } 1173 // This is just dumping files for debugging. Ignore errors, and leave remnants. 1174 UNUSED(tmp_file->WriteFully(dex_file->Begin(), dex_file->Size())); 1175 UNUSED(tmp_file->Flush()); 1176 UNUSED(tmp_file->Close()); 1177 LOG(INFO) << "Wrote input to " << tmp_file_name; 1178 } 1179 } 1180 } 1181 // Ensure opened dex files are writable for dex-to-dex transformations. Also ensure that 1182 // the dex caches stay live since we don't want class unloading to occur during compilation. 1183 for (const auto& dex_file : dex_files_) { 1184 if (!dex_file->EnableWrite()) { 1185 PLOG(ERROR) << "Failed to make .dex file writeable '" << dex_file->GetLocation() << "'\n"; 1186 } 1187 ScopedObjectAccess soa(self); 1188 dex_caches_.push_back(soa.AddLocalReference<jobject>( 1189 class_linker->RegisterDexFile(*dex_file, Runtime::Current()->GetLinearAlloc()))); 1190 dex_file->CreateTypeLookupTable(); 1191 } 1192 1193 // If we use a swap file, ensure we are above the threshold to make it necessary. 1194 if (swap_fd_ != -1) { 1195 if (!UseSwap(IsBootImage(), dex_files_)) { 1196 close(swap_fd_); 1197 swap_fd_ = -1; 1198 VLOG(compiler) << "Decided to run without swap."; 1199 } else { 1200 LOG(INFO) << "Large app, accepted running with swap."; 1201 } 1202 } 1203 // Note that dex2oat won't close the swap_fd_. The compiler driver's swap space will do that. 1204 1205 /* 1206 * If we're not in interpret-only or verify-none mode, go ahead and compile small applications. 1207 * Don't bother to check if we're doing the image. 1208 */ 1209 if (!IsBootImage() && 1210 compiler_options_->IsCompilationEnabled() && 1211 compiler_kind_ == Compiler::kQuick) { 1212 size_t num_methods = 0; 1213 for (size_t i = 0; i != dex_files_.size(); ++i) { 1214 const DexFile* dex_file = dex_files_[i]; 1215 CHECK(dex_file != nullptr); 1216 num_methods += dex_file->NumMethodIds(); 1217 } 1218 if (num_methods <= compiler_options_->GetNumDexMethodsThreshold()) { 1219 compiler_options_->SetCompilerFilter(CompilerOptions::kSpeed); 1220 VLOG(compiler) << "Below method threshold, compiling anyways"; 1221 } 1222 } 1223 1224 return true; 1225 } 1226 1227 // Create and invoke the compiler driver. This will compile all the dex files. 1228 void Compile() { 1229 TimingLogger::ScopedTiming t("dex2oat Compile", timings_); 1230 compiler_phases_timings_.reset(new CumulativeLogger("compilation times")); 1231 1232 // Handle and ClassLoader creation needs to come after Runtime::Create 1233 jobject class_loader = nullptr; 1234 Thread* self = Thread::Current(); 1235 1236 if (!boot_image_option_.empty()) { 1237 ClassLinker* class_linker = Runtime::Current()->GetClassLinker(); 1238 OpenClassPathFiles(runtime_->GetClassPathString(), dex_files_, &class_path_files_); 1239 ScopedObjectAccess soa(self); 1240 1241 // Classpath: first the class-path given. 1242 std::vector<const DexFile*> class_path_files; 1243 for (auto& class_path_file : class_path_files_) { 1244 class_path_files.push_back(class_path_file.get()); 1245 } 1246 1247 // Store the classpath we have right now. 1248 key_value_store_->Put(OatHeader::kClassPathKey, 1249 OatFile::EncodeDexFileDependencies(class_path_files)); 1250 1251 // Then the dex files we'll compile. Thus we'll resolve the class-path first. 1252 class_path_files.insert(class_path_files.end(), dex_files_.begin(), dex_files_.end()); 1253 1254 class_loader = class_linker->CreatePathClassLoader(self, class_path_files); 1255 } 1256 1257 driver_.reset(new CompilerDriver(compiler_options_.get(), 1258 verification_results_.get(), 1259 &method_inliner_map_, 1260 compiler_kind_, 1261 instruction_set_, 1262 instruction_set_features_.get(), 1263 IsBootImage(), 1264 image_classes_.release(), 1265 compiled_classes_.release(), 1266 nullptr, 1267 thread_count_, 1268 dump_stats_, 1269 dump_passes_, 1270 dump_cfg_file_name_, 1271 dump_cfg_append_, 1272 compiler_phases_timings_.get(), 1273 swap_fd_, 1274 profile_file_)); 1275 1276 driver_->SetDexFilesForOatFile(dex_files_); 1277 driver_->CompileAll(class_loader, dex_files_, timings_); 1278 } 1279 1280 // Notes on the interleaving of creating the image and oat file to 1281 // ensure the references between the two are correct. 1282 // 1283 // Currently we have a memory layout that looks something like this: 1284 // 1285 // +--------------+ 1286 // | image | 1287 // +--------------+ 1288 // | boot oat | 1289 // +--------------+ 1290 // | alloc spaces | 1291 // +--------------+ 1292 // 1293 // There are several constraints on the loading of the image and boot.oat. 1294 // 1295 // 1. The image is expected to be loaded at an absolute address and 1296 // contains Objects with absolute pointers within the image. 1297 // 1298 // 2. There are absolute pointers from Methods in the image to their 1299 // code in the oat. 1300 // 1301 // 3. There are absolute pointers from the code in the oat to Methods 1302 // in the image. 1303 // 1304 // 4. There are absolute pointers from code in the oat to other code 1305 // in the oat. 1306 // 1307 // To get this all correct, we go through several steps. 1308 // 1309 // 1. We prepare offsets for all data in the oat file and calculate 1310 // the oat data size and code size. During this stage, we also set 1311 // oat code offsets in methods for use by the image writer. 1312 // 1313 // 2. We prepare offsets for the objects in the image and calculate 1314 // the image size. 1315 // 1316 // 3. We create the oat file. Originally this was just our own proprietary 1317 // file but now it is contained within an ELF dynamic object (aka an .so 1318 // file). Since we know the image size and oat data size and code size we 1319 // can prepare the ELF headers and we then know the ELF memory segment 1320 // layout and we can now resolve all references. The compiler provides 1321 // LinkerPatch information in each CompiledMethod and we resolve these, 1322 // using the layout information and image object locations provided by 1323 // image writer, as we're writing the method code. 1324 // 1325 // 4. We create the image file. It needs to know where the oat file 1326 // will be loaded after itself. Originally when oat file was simply 1327 // memory mapped so we could predict where its contents were based 1328 // on the file size. Now that it is an ELF file, we need to inspect 1329 // the ELF file to understand the in memory segment layout including 1330 // where the oat header is located within. 1331 // TODO: We could just remember this information from step 3. 1332 // 1333 // 5. We fixup the ELF program headers so that dlopen will try to 1334 // load the .so at the desired location at runtime by offsetting the 1335 // Elf32_Phdr.p_vaddr values by the desired base address. 1336 // TODO: Do this in step 3. We already know the layout there. 1337 // 1338 // Steps 1.-3. are done by the CreateOatFile() above, steps 4.-5. 1339 // are done by the CreateImageFile() below. 1340 1341 1342 // Write out the generated code part. Calls the OatWriter and ElfBuilder. Also prepares the 1343 // ImageWriter, if necessary. 1344 // Note: Flushing (and closing) the file is the caller's responsibility, except for the failure 1345 // case (when the file will be explicitly erased). 1346 bool CreateOatFile() { 1347 CHECK(key_value_store_.get() != nullptr); 1348 1349 TimingLogger::ScopedTiming t("dex2oat Oat", timings_); 1350 1351 std::unique_ptr<OatWriter> oat_writer; 1352 { 1353 TimingLogger::ScopedTiming t2("dex2oat OatWriter", timings_); 1354 std::string image_file_location; 1355 uint32_t image_file_location_oat_checksum = 0; 1356 uintptr_t image_file_location_oat_data_begin = 0; 1357 int32_t image_patch_delta = 0; 1358 1359 if (app_image_ && image_base_ == 0) { 1360 gc::space::ImageSpace* image_space = Runtime::Current()->GetHeap()->GetImageSpace(); 1361 image_base_ = RoundUp( 1362 reinterpret_cast<uintptr_t>(image_space->GetImageHeader().GetOatFileEnd()), 1363 kPageSize); 1364 VLOG(compiler) << "App image base=" << reinterpret_cast<void*>(image_base_); 1365 } 1366 1367 if (IsImage()) { 1368 PrepareImageWriter(image_base_); 1369 } 1370 1371 if (!IsBootImage()) { 1372 TimingLogger::ScopedTiming t3("Loading image checksum", timings_); 1373 gc::space::ImageSpace* image_space = Runtime::Current()->GetHeap()->GetImageSpace(); 1374 image_file_location_oat_checksum = image_space->GetImageHeader().GetOatChecksum(); 1375 image_file_location_oat_data_begin = 1376 reinterpret_cast<uintptr_t>(image_space->GetImageHeader().GetOatDataBegin()); 1377 image_file_location = image_space->GetImageFilename(); 1378 image_patch_delta = image_space->GetImageHeader().GetPatchDelta(); 1379 } 1380 1381 if (!image_file_location.empty()) { 1382 key_value_store_->Put(OatHeader::kImageLocationKey, image_file_location); 1383 } 1384 1385 oat_writer.reset(new OatWriter(dex_files_, 1386 image_file_location_oat_checksum, 1387 image_file_location_oat_data_begin, 1388 image_patch_delta, 1389 driver_.get(), 1390 image_writer_.get(), 1391 IsBootImage(), 1392 timings_, 1393 key_value_store_.get())); 1394 } 1395 1396 if (IsImage()) { 1397 // The OatWriter constructor has already updated offsets in methods and we need to 1398 // prepare method offsets in the image address space for direct method patching. 1399 TimingLogger::ScopedTiming t2("dex2oat Prepare image address space", timings_); 1400 if (!image_writer_->PrepareImageAddressSpace()) { 1401 LOG(ERROR) << "Failed to prepare image address space."; 1402 return false; 1403 } 1404 } 1405 1406 { 1407 TimingLogger::ScopedTiming t2("dex2oat Write ELF", timings_); 1408 if (!driver_->WriteElf(android_root_, is_host_, dex_files_, oat_writer.get(), 1409 oat_file_.get())) { 1410 LOG(ERROR) << "Failed to write ELF file " << oat_file_->GetPath(); 1411 return false; 1412 } 1413 } 1414 1415 VLOG(compiler) << "Oat file written successfully (unstripped): " << oat_location_; 1416 return true; 1417 } 1418 1419 // If we are compiling an image, invoke the image creation routine. Else just skip. 1420 bool HandleImage() { 1421 if (IsImage()) { 1422 TimingLogger::ScopedTiming t("dex2oat ImageWriter", timings_); 1423 if (!CreateImageFile()) { 1424 return false; 1425 } 1426 VLOG(compiler) << "Image written successfully: " << image_filename_; 1427 } 1428 return true; 1429 } 1430 1431 // Create a copy from unstripped to stripped. 1432 bool CopyUnstrippedToStripped() { 1433 // If we don't want to strip in place, copy from unstripped location to stripped location. 1434 // We need to strip after image creation because FixupElf needs to use .strtab. 1435 if (oat_unstripped_ != oat_stripped_) { 1436 // If the oat file is still open, flush it. 1437 if (oat_file_.get() != nullptr && oat_file_->IsOpened()) { 1438 if (!FlushCloseOatFile()) { 1439 return false; 1440 } 1441 } 1442 1443 TimingLogger::ScopedTiming t("dex2oat OatFile copy", timings_); 1444 std::unique_ptr<File> in(OS::OpenFileForReading(oat_unstripped_.c_str())); 1445 std::unique_ptr<File> out(OS::CreateEmptyFile(oat_stripped_.c_str())); 1446 size_t buffer_size = 8192; 1447 std::unique_ptr<uint8_t[]> buffer(new uint8_t[buffer_size]); 1448 while (true) { 1449 int bytes_read = TEMP_FAILURE_RETRY(read(in->Fd(), buffer.get(), buffer_size)); 1450 if (bytes_read <= 0) { 1451 break; 1452 } 1453 bool write_ok = out->WriteFully(buffer.get(), bytes_read); 1454 CHECK(write_ok); 1455 } 1456 if (out->FlushCloseOrErase() != 0) { 1457 PLOG(ERROR) << "Failed to flush and close copied oat file: " << oat_stripped_; 1458 return false; 1459 } 1460 VLOG(compiler) << "Oat file copied successfully (stripped): " << oat_stripped_; 1461 } 1462 return true; 1463 } 1464 1465 bool FlushOatFile() { 1466 if (oat_file_.get() != nullptr) { 1467 TimingLogger::ScopedTiming t2("dex2oat Flush ELF", timings_); 1468 if (oat_file_->Flush() != 0) { 1469 PLOG(ERROR) << "Failed to flush oat file: " << oat_location_ << " / " 1470 << oat_filename_; 1471 oat_file_->Erase(); 1472 return false; 1473 } 1474 } 1475 return true; 1476 } 1477 1478 bool FlushCloseOatFile() { 1479 if (oat_file_.get() != nullptr) { 1480 std::unique_ptr<File> tmp(oat_file_.release()); 1481 if (tmp->FlushCloseOrErase() != 0) { 1482 PLOG(ERROR) << "Failed to flush and close oat file: " << oat_location_ << " / " 1483 << oat_filename_; 1484 return false; 1485 } 1486 } 1487 return true; 1488 } 1489 1490 void DumpTiming() { 1491 if (dump_timing_ || (dump_slow_timing_ && timings_->GetTotalNs() > MsToNs(1000))) { 1492 LOG(INFO) << Dumpable<TimingLogger>(*timings_); 1493 } 1494 if (dump_passes_) { 1495 LOG(INFO) << Dumpable<CumulativeLogger>(*driver_->GetTimingsLogger()); 1496 } 1497 } 1498 1499 CompilerOptions* GetCompilerOptions() const { 1500 return compiler_options_.get(); 1501 } 1502 1503 bool IsImage() const { 1504 return IsAppImage() || IsBootImage(); 1505 } 1506 1507 bool IsAppImage() const { 1508 return app_image_; 1509 } 1510 1511 bool IsBootImage() const { 1512 return boot_image_; 1513 } 1514 1515 bool IsHost() const { 1516 return is_host_; 1517 } 1518 1519 private: 1520 static size_t OpenDexFiles(const std::vector<const char*>& dex_filenames, 1521 const std::vector<const char*>& dex_locations, 1522 std::vector<std::unique_ptr<const DexFile>>* dex_files) { 1523 DCHECK(dex_files != nullptr) << "OpenDexFiles out-param is nullptr"; 1524 size_t failure_count = 0; 1525 for (size_t i = 0; i < dex_filenames.size(); i++) { 1526 const char* dex_filename = dex_filenames[i]; 1527 const char* dex_location = dex_locations[i]; 1528 ATRACE_BEGIN(StringPrintf("Opening dex file '%s'", dex_filenames[i]).c_str()); 1529 std::string error_msg; 1530 if (!OS::FileExists(dex_filename)) { 1531 LOG(WARNING) << "Skipping non-existent dex file '" << dex_filename << "'"; 1532 continue; 1533 } 1534 if (!DexFile::Open(dex_filename, dex_location, &error_msg, dex_files)) { 1535 LOG(WARNING) << "Failed to open .dex from file '" << dex_filename << "': " << error_msg; 1536 ++failure_count; 1537 } 1538 ATRACE_END(); 1539 } 1540 return failure_count; 1541 } 1542 1543 // Returns true if dex_files has a dex with the named location. We compare canonical locations, 1544 // so that relative and absolute paths will match. Not caching for the dex_files isn't very 1545 // efficient, but under normal circumstances the list is neither large nor is this part too 1546 // sensitive. 1547 static bool DexFilesContains(const std::vector<const DexFile*>& dex_files, 1548 const std::string& location) { 1549 std::string canonical_location(DexFile::GetDexCanonicalLocation(location.c_str())); 1550 for (size_t i = 0; i < dex_files.size(); ++i) { 1551 if (DexFile::GetDexCanonicalLocation(dex_files[i]->GetLocation().c_str()) == 1552 canonical_location) { 1553 return true; 1554 } 1555 } 1556 return false; 1557 } 1558 1559 // Appends to opened_dex_files any elements of class_path that dex_files 1560 // doesn't already contain. This will open those dex files as necessary. 1561 static void OpenClassPathFiles(const std::string& class_path, 1562 std::vector<const DexFile*> dex_files, 1563 std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) { 1564 DCHECK(opened_dex_files != nullptr) << "OpenClassPathFiles out-param is nullptr"; 1565 std::vector<std::string> parsed; 1566 Split(class_path, ':', &parsed); 1567 // Take Locks::mutator_lock_ so that lock ordering on the ClassLinker::dex_lock_ is maintained. 1568 ScopedObjectAccess soa(Thread::Current()); 1569 for (size_t i = 0; i < parsed.size(); ++i) { 1570 if (DexFilesContains(dex_files, parsed[i])) { 1571 continue; 1572 } 1573 std::string error_msg; 1574 if (!DexFile::Open(parsed[i].c_str(), parsed[i].c_str(), &error_msg, opened_dex_files)) { 1575 LOG(WARNING) << "Failed to open dex file '" << parsed[i] << "': " << error_msg; 1576 } 1577 } 1578 } 1579 1580 // Create a runtime necessary for compilation. 1581 bool CreateRuntime(const RuntimeOptions& runtime_options) 1582 SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_) { 1583 if (!Runtime::Create(runtime_options, false)) { 1584 LOG(ERROR) << "Failed to create runtime"; 1585 return false; 1586 } 1587 runtime_.reset(Runtime::Current()); 1588 runtime_->SetInstructionSet(instruction_set_); 1589 for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) { 1590 Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i); 1591 if (!runtime_->HasCalleeSaveMethod(type)) { 1592 runtime_->SetCalleeSaveMethod(runtime_->CreateCalleeSaveMethod(), type); 1593 } 1594 } 1595 runtime_->GetClassLinker()->FixupDexCaches(runtime_->GetResolutionMethod()); 1596 1597 // Initialize maps for unstarted runtime. This needs to be here, as running clinits needs this 1598 // set up. 1599 interpreter::UnstartedRuntime::Initialize(); 1600 1601 runtime_->GetClassLinker()->RunRootClinits(); 1602 1603 return true; 1604 } 1605 1606 void PrepareImageWriter(uintptr_t image_base) { 1607 DCHECK(IsImage()); 1608 image_writer_.reset(new ImageWriter(*driver_, 1609 image_base, 1610 compiler_options_->GetCompilePic(), 1611 IsAppImage())); 1612 } 1613 1614 // Let the ImageWriter write the image file. If we do not compile PIC, also fix up the oat file. 1615 bool CreateImageFile() 1616 REQUIRES(!Locks::mutator_lock_) { 1617 CHECK(image_writer_ != nullptr); 1618 if (!image_writer_->Write(app_image_fd_, 1619 IsBootImage() ? image_filename_ : app_image_file_name_, 1620 oat_unstripped_, 1621 oat_location_)) { 1622 LOG(ERROR) << "Failed to create image file " << image_filename_; 1623 return false; 1624 } 1625 uintptr_t oat_data_begin = image_writer_->GetOatDataBegin(); 1626 1627 // Destroy ImageWriter before doing FixupElf. 1628 image_writer_.reset(); 1629 1630 // Do not fix up the ELF file if we are --compile-pic or compiing the app image 1631 if (!compiler_options_->GetCompilePic() && IsBootImage()) { 1632 std::unique_ptr<File> oat_file(OS::OpenFileReadWrite(oat_unstripped_.c_str())); 1633 if (oat_file.get() == nullptr) { 1634 PLOG(ERROR) << "Failed to open ELF file: " << oat_unstripped_; 1635 return false; 1636 } 1637 1638 if (!ElfWriter::Fixup(oat_file.get(), oat_data_begin)) { 1639 oat_file->Erase(); 1640 LOG(ERROR) << "Failed to fixup ELF file " << oat_file->GetPath(); 1641 return false; 1642 } 1643 1644 if (oat_file->FlushCloseOrErase()) { 1645 PLOG(ERROR) << "Failed to flush and close fixed ELF file " << oat_file->GetPath(); 1646 return false; 1647 } 1648 } 1649 1650 return true; 1651 } 1652 1653 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;) 1654 static std::unordered_set<std::string>* ReadImageClassesFromFile( 1655 const char* image_classes_filename) { 1656 std::function<std::string(const char*)> process = DotToDescriptor; 1657 return ReadCommentedInputFromFile(image_classes_filename, &process); 1658 } 1659 1660 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;) 1661 static std::unordered_set<std::string>* ReadImageClassesFromZip( 1662 const char* zip_filename, 1663 const char* image_classes_filename, 1664 std::string* error_msg) { 1665 std::function<std::string(const char*)> process = DotToDescriptor; 1666 return ReadCommentedInputFromZip(zip_filename, image_classes_filename, &process, error_msg); 1667 } 1668 1669 // Read lines from the given file, dropping comments and empty lines. Post-process each line with 1670 // the given function. 1671 static std::unordered_set<std::string>* ReadCommentedInputFromFile( 1672 const char* input_filename, std::function<std::string(const char*)>* process) { 1673 std::unique_ptr<std::ifstream> input_file(new std::ifstream(input_filename, std::ifstream::in)); 1674 if (input_file.get() == nullptr) { 1675 LOG(ERROR) << "Failed to open input file " << input_filename; 1676 return nullptr; 1677 } 1678 std::unique_ptr<std::unordered_set<std::string>> result( 1679 ReadCommentedInputStream(*input_file, process)); 1680 input_file->close(); 1681 return result.release(); 1682 } 1683 1684 // Read lines from the given file from the given zip file, dropping comments and empty lines. 1685 // Post-process each line with the given function. 1686 static std::unordered_set<std::string>* ReadCommentedInputFromZip( 1687 const char* zip_filename, 1688 const char* input_filename, 1689 std::function<std::string(const char*)>* process, 1690 std::string* error_msg) { 1691 std::unique_ptr<ZipArchive> zip_archive(ZipArchive::Open(zip_filename, error_msg)); 1692 if (zip_archive.get() == nullptr) { 1693 return nullptr; 1694 } 1695 std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(input_filename, error_msg)); 1696 if (zip_entry.get() == nullptr) { 1697 *error_msg = StringPrintf("Failed to find '%s' within '%s': %s", input_filename, 1698 zip_filename, error_msg->c_str()); 1699 return nullptr; 1700 } 1701 std::unique_ptr<MemMap> input_file(zip_entry->ExtractToMemMap(zip_filename, 1702 input_filename, 1703 error_msg)); 1704 if (input_file.get() == nullptr) { 1705 *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", input_filename, 1706 zip_filename, error_msg->c_str()); 1707 return nullptr; 1708 } 1709 const std::string input_string(reinterpret_cast<char*>(input_file->Begin()), 1710 input_file->Size()); 1711 std::istringstream input_stream(input_string); 1712 return ReadCommentedInputStream(input_stream, process); 1713 } 1714 1715 // Read lines from the given stream, dropping comments and empty lines. Post-process each line 1716 // with the given function. 1717 static std::unordered_set<std::string>* ReadCommentedInputStream( 1718 std::istream& in_stream, 1719 std::function<std::string(const char*)>* process) { 1720 std::unique_ptr<std::unordered_set<std::string>> image_classes( 1721 new std::unordered_set<std::string>); 1722 while (in_stream.good()) { 1723 std::string dot; 1724 std::getline(in_stream, dot); 1725 if (StartsWith(dot, "#") || dot.empty()) { 1726 continue; 1727 } 1728 if (process != nullptr) { 1729 std::string descriptor((*process)(dot.c_str())); 1730 image_classes->insert(descriptor); 1731 } else { 1732 image_classes->insert(dot); 1733 } 1734 } 1735 return image_classes.release(); 1736 } 1737 1738 void LogCompletionTime() { 1739 // Note: when creation of a runtime fails, e.g., when trying to compile an app but when there 1740 // is no image, there won't be a Runtime::Current(). 1741 // Note: driver creation can fail when loading an invalid dex file. 1742 LOG(INFO) << "dex2oat took " << PrettyDuration(NanoTime() - start_ns_) 1743 << " (threads: " << thread_count_ << ") " 1744 << ((Runtime::Current() != nullptr && driver_ != nullptr) ? 1745 driver_->GetMemoryUsageString(kIsDebugBuild || VLOG_IS_ON(compiler)) : 1746 ""); 1747 } 1748 1749 std::unique_ptr<CompilerOptions> compiler_options_; 1750 Compiler::Kind compiler_kind_; 1751 1752 InstructionSet instruction_set_; 1753 std::unique_ptr<const InstructionSetFeatures> instruction_set_features_; 1754 1755 std::unique_ptr<SafeMap<std::string, std::string> > key_value_store_; 1756 1757 std::unique_ptr<VerificationResults> verification_results_; 1758 1759 DexFileToMethodInlinerMap method_inliner_map_; 1760 std::unique_ptr<QuickCompilerCallbacks> callbacks_; 1761 1762 // Ownership for the class path files. 1763 std::vector<std::unique_ptr<const DexFile>> class_path_files_; 1764 1765 std::unique_ptr<Runtime> runtime_; 1766 1767 size_t thread_count_; 1768 uint64_t start_ns_; 1769 std::unique_ptr<WatchDog> watchdog_; 1770 std::unique_ptr<File> oat_file_; 1771 std::string oat_stripped_; 1772 std::string oat_unstripped_; 1773 std::string oat_location_; 1774 std::string oat_filename_; 1775 int oat_fd_; 1776 std::vector<const char*> dex_filenames_; 1777 std::vector<const char*> dex_locations_; 1778 int zip_fd_; 1779 std::string zip_location_; 1780 std::string boot_image_option_; 1781 std::vector<const char*> runtime_args_; 1782 std::string image_filename_; 1783 uintptr_t image_base_; 1784 const char* image_classes_zip_filename_; 1785 const char* image_classes_filename_; 1786 const char* compiled_classes_zip_filename_; 1787 const char* compiled_classes_filename_; 1788 const char* compiled_methods_zip_filename_; 1789 const char* compiled_methods_filename_; 1790 std::unique_ptr<std::unordered_set<std::string>> image_classes_; 1791 std::unique_ptr<std::unordered_set<std::string>> compiled_classes_; 1792 std::unique_ptr<std::unordered_set<std::string>> compiled_methods_; 1793 bool app_image_; 1794 bool boot_image_; 1795 bool is_host_; 1796 std::string android_root_; 1797 std::vector<const DexFile*> dex_files_; 1798 std::vector<jobject> dex_caches_; 1799 std::vector<std::unique_ptr<const DexFile>> opened_dex_files_; 1800 1801 std::unique_ptr<ImageWriter> image_writer_; 1802 std::unique_ptr<CompilerDriver> driver_; 1803 1804 std::vector<std::string> verbose_methods_; 1805 bool dump_stats_; 1806 bool dump_passes_; 1807 bool dump_timing_; 1808 bool dump_slow_timing_; 1809 std::string dump_cfg_file_name_; 1810 bool dump_cfg_append_; 1811 std::string swap_file_name_; 1812 int swap_fd_; 1813 std::string app_image_file_name_; 1814 int app_image_fd_; 1815 std::string profile_file_; // Profile file to use 1816 TimingLogger* timings_; 1817 std::unique_ptr<CumulativeLogger> compiler_phases_timings_; 1818 1819 DISALLOW_IMPLICIT_CONSTRUCTORS(Dex2Oat); 1820}; 1821 1822static void b13564922() { 1823#if defined(__linux__) && defined(__arm__) 1824 int major, minor; 1825 struct utsname uts; 1826 if (uname(&uts) != -1 && 1827 sscanf(uts.release, "%d.%d", &major, &minor) == 2 && 1828 ((major < 3) || ((major == 3) && (minor < 4)))) { 1829 // Kernels before 3.4 don't handle the ASLR well and we can run out of address 1830 // space (http://b/13564922). Work around the issue by inhibiting further mmap() randomization. 1831 int old_personality = personality(0xffffffff); 1832 if ((old_personality & ADDR_NO_RANDOMIZE) == 0) { 1833 int new_personality = personality(old_personality | ADDR_NO_RANDOMIZE); 1834 if (new_personality == -1) { 1835 LOG(WARNING) << "personality(. | ADDR_NO_RANDOMIZE) failed."; 1836 } 1837 } 1838 } 1839#endif 1840} 1841 1842static int CompileImage(Dex2Oat& dex2oat) { 1843 dex2oat.Compile(); 1844 1845 // Create the boot.oat. 1846 if (!dex2oat.CreateOatFile()) { 1847 dex2oat.EraseOatFile(); 1848 return EXIT_FAILURE; 1849 } 1850 1851 // Flush and close the boot.oat. We always expect the output file by name, and it will be 1852 // re-opened from the unstripped name. 1853 if (!dex2oat.FlushCloseOatFile()) { 1854 return EXIT_FAILURE; 1855 } 1856 1857 // Creates the boot.art and patches the boot.oat. 1858 if (!dex2oat.HandleImage()) { 1859 return EXIT_FAILURE; 1860 } 1861 1862 // When given --host, finish early without stripping. 1863 if (dex2oat.IsHost()) { 1864 dex2oat.DumpTiming(); 1865 return EXIT_SUCCESS; 1866 } 1867 1868 // Copy unstripped to stripped location, if necessary. 1869 if (!dex2oat.CopyUnstrippedToStripped()) { 1870 return EXIT_FAILURE; 1871 } 1872 1873 // FlushClose again, as stripping might have re-opened the oat file. 1874 if (!dex2oat.FlushCloseOatFile()) { 1875 return EXIT_FAILURE; 1876 } 1877 1878 dex2oat.DumpTiming(); 1879 return EXIT_SUCCESS; 1880} 1881 1882static int CompileApp(Dex2Oat& dex2oat) { 1883 dex2oat.Compile(); 1884 1885 // Create the app oat. 1886 if (!dex2oat.CreateOatFile()) { 1887 dex2oat.EraseOatFile(); 1888 return EXIT_FAILURE; 1889 } 1890 1891 // Do not close the oat file here. We might haven gotten the output file by file descriptor, 1892 // which we would lose. 1893 if (!dex2oat.FlushOatFile()) { 1894 return EXIT_FAILURE; 1895 } 1896 1897 // When given --host, finish early without stripping. 1898 if (dex2oat.IsHost()) { 1899 if (!dex2oat.FlushCloseOatFile()) { 1900 return EXIT_FAILURE; 1901 } 1902 1903 dex2oat.DumpTiming(); 1904 return EXIT_SUCCESS; 1905 } 1906 1907 // Copy unstripped to stripped location, if necessary. This will implicitly flush & close the 1908 // unstripped version. If this is given, we expect to be able to open writable files by name. 1909 if (!dex2oat.CopyUnstrippedToStripped()) { 1910 return EXIT_FAILURE; 1911 } 1912 1913 // Flush and close the file. 1914 if (!dex2oat.FlushCloseOatFile()) { 1915 return EXIT_FAILURE; 1916 } 1917 1918 dex2oat.DumpTiming(); 1919 return EXIT_SUCCESS; 1920} 1921 1922static int dex2oat(int argc, char** argv) { 1923 b13564922(); 1924 1925 TimingLogger timings("compiler", false, false); 1926 1927 Dex2Oat dex2oat(&timings); 1928 1929 // Parse arguments. Argument mistakes will lead to exit(EXIT_FAILURE) in UsageError. 1930 dex2oat.ParseArgs(argc, argv); 1931 1932 // Check early that the result of compilation can be written 1933 if (!dex2oat.OpenFile()) { 1934 return EXIT_FAILURE; 1935 } 1936 1937 // Print the complete line when any of the following is true: 1938 // 1) Debug build 1939 // 2) Compiling an image 1940 // 3) Compiling with --host 1941 // 4) Compiling on the host (not a target build) 1942 // Otherwise, print a stripped command line. 1943 if (kIsDebugBuild || dex2oat.IsBootImage() || dex2oat.IsHost() || !kIsTargetBuild) { 1944 LOG(INFO) << CommandLine(); 1945 } else { 1946 LOG(INFO) << StrippedCommandLine(); 1947 } 1948 1949 if (!dex2oat.Setup()) { 1950 dex2oat.EraseOatFile(); 1951 return EXIT_FAILURE; 1952 } 1953 1954 bool result; 1955 if (dex2oat.IsImage()) { 1956 result = CompileImage(dex2oat); 1957 } else { 1958 result = CompileApp(dex2oat); 1959 } 1960 1961 dex2oat.Shutdown(); 1962 return result; 1963} 1964} // namespace art 1965 1966int main(int argc, char** argv) { 1967 int result = art::dex2oat(argc, argv); 1968 // Everything was done, do an explicit exit here to avoid running Runtime destructors that take 1969 // time (bug 10645725) unless we're a debug build or running on valgrind. Note: The Dex2Oat class 1970 // should not destruct the runtime in this case. 1971 if (!art::kIsDebugBuild && (RUNNING_ON_MEMORY_TOOL == 0)) { 1972 exit(result); 1973 } 1974 return result; 1975} 1976