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