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