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