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