dex2oat.cc revision 155ecba1c9b56ce1b468135e6a591a3fe9258c52
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 21#include <fstream> 22#include <iostream> 23#include <sstream> 24#include <string> 25#include <vector> 26 27#include "base/stl_util.h" 28#include "base/stringpiece.h" 29#include "base/timing_logger.h" 30#include "base/unix_file/fd_file.h" 31#include "class_linker.h" 32#include "dex_file-inl.h" 33#include "driver/compiler_driver.h" 34#include "elf_fixup.h" 35#include "elf_stripper.h" 36#include "gc/space/image_space.h" 37#include "gc/space/space-inl.h" 38#include "image_writer.h" 39#include "leb128.h" 40#include "mirror/abstract_method-inl.h" 41#include "mirror/class-inl.h" 42#include "mirror/class_loader.h" 43#include "mirror/object-inl.h" 44#include "mirror/object_array-inl.h" 45#include "oat_writer.h" 46#include "object_utils.h" 47#include "os.h" 48#include "runtime.h" 49#include "ScopedLocalRef.h" 50#include "scoped_thread_state_change.h" 51#include "sirt_ref.h" 52#include "vector_output_stream.h" 53#include "well_known_classes.h" 54#include "zip_archive.h" 55 56namespace art { 57 58static void UsageErrorV(const char* fmt, va_list ap) { 59 std::string error; 60 StringAppendV(&error, fmt, ap); 61 LOG(ERROR) << error; 62} 63 64static void UsageError(const char* fmt, ...) { 65 va_list ap; 66 va_start(ap, fmt); 67 UsageErrorV(fmt, ap); 68 va_end(ap); 69} 70 71static void Usage(const char* fmt, ...) { 72 va_list ap; 73 va_start(ap, fmt); 74 UsageErrorV(fmt, ap); 75 va_end(ap); 76 77 UsageError("Usage: dex2oat [options]..."); 78 UsageError(""); 79 UsageError(" --dex-file=<dex-file>: specifies a .dex file to compile."); 80 UsageError(" Example: --dex-file=/system/framework/core.jar"); 81 UsageError(""); 82 UsageError(" --zip-fd=<file-descriptor>: specifies a file descriptor of a zip file"); 83 UsageError(" containing a classes.dex file to compile."); 84 UsageError(" Example: --zip-fd=5"); 85 UsageError(""); 86 UsageError(" --zip-location=<zip-location>: specifies a symbolic name for the file"); 87 UsageError(" corresponding to the file descriptor specified by --zip-fd."); 88 UsageError(" Example: --zip-location=/system/app/Calculator.apk"); 89 UsageError(""); 90 UsageError(" --oat-file=<file.oat>: specifies the oat output destination via a filename."); 91 UsageError(" Example: --oat-file=/system/framework/boot.oat"); 92 UsageError(""); 93 UsageError(" --oat-fd=<number>: specifies the oat output destination via a file descriptor."); 94 UsageError(" Example: --oat-file=/system/framework/boot.oat"); 95 UsageError(""); 96 UsageError(" --oat-location=<oat-name>: specifies a symbolic name for the file corresponding"); 97 UsageError(" to the file descriptor specified by --oat-fd."); 98 UsageError(" Example: --oat-location=/data/dalvik-cache/system@app@Calculator.apk.oat"); 99 UsageError(""); 100 UsageError(" --oat-symbols=<file.oat>: specifies the oat output destination with full symbols."); 101 UsageError(" Example: --oat-symbols=/symbols/system/framework/boot.oat"); 102 UsageError(""); 103 UsageError(" --bitcode=<file.bc>: specifies the optional bitcode filename."); 104 UsageError(" Example: --bitcode=/system/framework/boot.bc"); 105 UsageError(""); 106 UsageError(" --image=<file.art>: specifies the output image filename."); 107 UsageError(" Example: --image=/system/framework/boot.art"); 108 UsageError(""); 109 UsageError(" --image-classes=<classname-file>: specifies classes to include in an image."); 110 UsageError(" Example: --image=frameworks/base/preloaded-classes"); 111 UsageError(""); 112 UsageError(" --base=<hex-address>: specifies the base address when creating a boot image."); 113 UsageError(" Example: --base=0x50000000"); 114 UsageError(""); 115 UsageError(" --boot-image=<file.art>: provide the image file for the boot class path."); 116 UsageError(" Example: --boot-image=/system/framework/boot.art"); 117 UsageError(" Default: <host-prefix>/system/framework/boot.art"); 118 UsageError(""); 119 UsageError(" --host-prefix=<path>: used to translate host paths to target paths during"); 120 UsageError(" cross compilation."); 121 UsageError(" Example: --host-prefix=out/target/product/crespo"); 122 UsageError(" Default: $ANDROID_PRODUCT_OUT"); 123 UsageError(""); 124 UsageError(" --android-root=<path>: used to locate libraries for portable linking."); 125 UsageError(" Example: --android-root=out/host/linux-x86"); 126 UsageError(" Default: $ANDROID_ROOT"); 127 UsageError(""); 128 UsageError(" --instruction-set=(arm|mips|x86): compile for a particular instruction"); 129 UsageError(" set."); 130 UsageError(" Example: --instruction-set=x86"); 131 UsageError(" Default: arm"); 132 UsageError(""); 133 UsageError(" --compiler-backend=(Quick|QuickGBC|Portable): select compiler backend"); 134 UsageError(" set."); 135 UsageError(" Example: --instruction-set=Portable"); 136 UsageError(" Default: Quick"); 137 UsageError(""); 138 UsageError(" --host: used with Portable backend to link against host runtime libraries"); 139 UsageError(""); 140 UsageError(" --runtime-arg <argument>: used to specify various arguments for the runtime,"); 141 UsageError(" such as initial heap size, maximum heap size, and verbose output."); 142 UsageError(" Use a separate --runtime-arg switch for each argument."); 143 UsageError(" Example: --runtime-arg -Xms256m"); 144 UsageError(""); 145 std::cerr << "See log for usage error information\n"; 146 exit(EXIT_FAILURE); 147} 148 149class Dex2Oat { 150 public: 151 static bool Create(Dex2Oat** p_dex2oat, 152 Runtime::Options& options, 153 CompilerBackend compiler_backend, 154 InstructionSet instruction_set, 155 size_t thread_count) 156 SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_) { 157 if (!CreateRuntime(options, instruction_set)) { 158 *p_dex2oat = NULL; 159 return false; 160 } 161 *p_dex2oat = new Dex2Oat(Runtime::Current(), compiler_backend, instruction_set, thread_count); 162 return true; 163 } 164 165 ~Dex2Oat() { 166 delete runtime_; 167 LOG(INFO) << "dex2oat took " << PrettyDuration(NanoTime() - start_ns_) 168 << " (threads: " << thread_count_ << ")"; 169 } 170 171 172 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;) 173 CompilerDriver::DescriptorSet* ReadImageClassesFromFile(const char* image_classes_filename) { 174 UniquePtr<std::ifstream> image_classes_file(new std::ifstream(image_classes_filename, 175 std::ifstream::in)); 176 if (image_classes_file.get() == NULL) { 177 LOG(ERROR) << "Failed to open image classes file " << image_classes_filename; 178 return NULL; 179 } 180 UniquePtr<CompilerDriver::DescriptorSet> result(ReadImageClasses(*image_classes_file.get())); 181 image_classes_file->close(); 182 return result.release(); 183 } 184 185 CompilerDriver::DescriptorSet* ReadImageClasses(std::istream& image_classes_stream) { 186 UniquePtr<CompilerDriver::DescriptorSet> image_classes(new CompilerDriver::DescriptorSet); 187 while (image_classes_stream.good()) { 188 std::string dot; 189 std::getline(image_classes_stream, dot); 190 if (StartsWith(dot, "#") || dot.empty()) { 191 continue; 192 } 193 std::string descriptor(DotToDescriptor(dot.c_str())); 194 image_classes->insert(descriptor); 195 } 196 return image_classes.release(); 197 } 198 199 // Reads the class names (java.lang.Object) and returns a set of descriptors (Ljava/lang/Object;) 200 CompilerDriver::DescriptorSet* ReadImageClassesFromZip(const std::string& zip_filename, 201 const char* image_classes_filename) { 202 UniquePtr<ZipArchive> zip_archive(ZipArchive::Open(zip_filename)); 203 if (zip_archive.get() == NULL) { 204 LOG(ERROR) << "Failed to open zip file " << zip_filename; 205 return NULL; 206 } 207 UniquePtr<ZipEntry> zip_entry(zip_archive->Find(image_classes_filename)); 208 if (zip_entry.get() == NULL) { 209 LOG(ERROR) << "Failed to find " << image_classes_filename << " within " << zip_filename; 210 return NULL; 211 } 212 UniquePtr<MemMap> image_classes_file(zip_entry->ExtractToMemMap(image_classes_filename)); 213 if (image_classes_file.get() == NULL) { 214 LOG(ERROR) << "Failed to extract " << image_classes_filename << " from " << zip_filename; 215 return NULL; 216 } 217 const std::string image_classes_string(reinterpret_cast<char*>(image_classes_file->Begin()), 218 image_classes_file->Size()); 219 std::istringstream image_classes_stream(image_classes_string); 220 return ReadImageClasses(image_classes_stream); 221 } 222 223 const CompilerDriver* CreateOatFile(const std::string& boot_image_option, 224 const std::string* host_prefix, 225 const std::string& android_root, 226 bool is_host, 227 const std::vector<const DexFile*>& dex_files, 228 File* oat_file, 229 const std::string& bitcode_filename, 230 bool image, 231 UniquePtr<CompilerDriver::DescriptorSet>& image_classes, 232 bool dump_stats, 233 base::TimingLogger& timings) 234 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { 235 // SirtRef and ClassLoader creation needs to come after Runtime::Create 236 jobject class_loader = NULL; 237 if (!boot_image_option.empty()) { 238 ClassLinker* class_linker = Runtime::Current()->GetClassLinker(); 239 std::vector<const DexFile*> class_path_files(dex_files); 240 OpenClassPathFiles(runtime_->GetClassPathString(), class_path_files); 241 for (size_t i = 0; i < class_path_files.size(); i++) { 242 class_linker->RegisterDexFile(*class_path_files[i]); 243 } 244 ScopedObjectAccessUnchecked soa(Thread::Current()); 245 soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader); 246 ScopedLocalRef<jobject> class_loader_local(soa.Env(), 247 soa.Env()->AllocObject(WellKnownClasses::dalvik_system_PathClassLoader)); 248 class_loader = soa.Env()->NewGlobalRef(class_loader_local.get()); 249 Runtime::Current()->SetCompileTimeClassPath(class_loader, class_path_files); 250 } 251 252 UniquePtr<CompilerDriver> driver(new CompilerDriver(compiler_backend_, 253 instruction_set_, 254 image, 255 image_classes.release(), 256 thread_count_, 257 dump_stats)); 258 259 if (compiler_backend_ == kPortable) { 260 driver->SetBitcodeFileName(bitcode_filename); 261 } 262 263 264 Thread::Current()->TransitionFromRunnableToSuspended(kNative); 265 266 driver->CompileAll(class_loader, dex_files, timings); 267 268 Thread::Current()->TransitionFromSuspendedToRunnable(); 269 270 timings.NewSplit("dex2oat OatWriter"); 271 std::string image_file_location; 272 uint32_t image_file_location_oat_checksum = 0; 273 uint32_t image_file_location_oat_data_begin = 0; 274 if (!driver->IsImage()) { 275 gc::space::ImageSpace* image_space = Runtime::Current()->GetHeap()->GetImageSpace(); 276 image_file_location_oat_checksum = image_space->GetImageHeader().GetOatChecksum(); 277 image_file_location_oat_data_begin = 278 reinterpret_cast<uint32_t>(image_space->GetImageHeader().GetOatDataBegin()); 279 image_file_location = image_space->GetImageFilename(); 280 if (host_prefix != NULL && StartsWith(image_file_location, host_prefix->c_str())) { 281 image_file_location = image_file_location.substr(host_prefix->size()); 282 } 283 } 284 285 OatWriter oat_writer(dex_files, 286 image_file_location_oat_checksum, 287 image_file_location_oat_data_begin, 288 image_file_location, 289 driver.get()); 290 291 if (!driver->WriteElf(android_root, is_host, dex_files, oat_writer, oat_file)) { 292 LOG(ERROR) << "Failed to write ELF file " << oat_file->GetPath(); 293 return NULL; 294 } 295 296 return driver.release(); 297 } 298 299 bool CreateImageFile(const std::string& image_filename, 300 uintptr_t image_base, 301 const std::string& oat_filename, 302 const std::string& oat_location, 303 const CompilerDriver& compiler) 304 LOCKS_EXCLUDED(Locks::mutator_lock_) { 305 uintptr_t oat_data_begin; 306 { 307 // ImageWriter is scoped so it can free memory before doing FixupElf 308 ImageWriter image_writer(compiler); 309 if (!image_writer.Write(image_filename, image_base, oat_filename, oat_location)) { 310 LOG(ERROR) << "Failed to create image file " << image_filename; 311 return false; 312 } 313 oat_data_begin = image_writer.GetOatDataBegin(); 314 } 315 316 UniquePtr<File> oat_file(OS::OpenFile(oat_filename.c_str(), true, false)); 317 if (oat_file.get() == NULL) { 318 PLOG(ERROR) << "Failed to open ELF file: " << oat_filename; 319 return false; 320 } 321 if (!ElfFixup::Fixup(oat_file.get(), oat_data_begin)) { 322 LOG(ERROR) << "Failed to fixup ELF file " << oat_file->GetPath(); 323 return false; 324 } 325 return true; 326 } 327 328 private: 329 explicit Dex2Oat(Runtime* runtime, 330 CompilerBackend compiler_backend, 331 InstructionSet instruction_set, 332 size_t thread_count) 333 : compiler_backend_(compiler_backend), 334 instruction_set_(instruction_set), 335 runtime_(runtime), 336 thread_count_(thread_count), 337 start_ns_(NanoTime()) { 338 } 339 340 static bool CreateRuntime(Runtime::Options& options, InstructionSet instruction_set) 341 SHARED_TRYLOCK_FUNCTION(true, Locks::mutator_lock_) { 342 if (!Runtime::Create(options, false)) { 343 LOG(ERROR) << "Failed to create runtime"; 344 return false; 345 } 346 Runtime* runtime = Runtime::Current(); 347 // if we loaded an existing image, we will reuse values from the image roots. 348 if (!runtime->HasResolutionMethod()) { 349 runtime->SetResolutionMethod(runtime->CreateResolutionMethod()); 350 } 351 for (int i = 0; i < Runtime::kLastCalleeSaveType; i++) { 352 Runtime::CalleeSaveType type = Runtime::CalleeSaveType(i); 353 if (!runtime->HasCalleeSaveMethod(type)) { 354 runtime->SetCalleeSaveMethod(runtime->CreateCalleeSaveMethod(instruction_set, type), type); 355 } 356 } 357 runtime->GetClassLinker()->FixupDexCaches(runtime->GetResolutionMethod()); 358 return true; 359 } 360 361 // Appends to dex_files any elements of class_path that it doesn't already 362 // contain. This will open those dex files as necessary. 363 static void OpenClassPathFiles(const std::string& class_path, 364 std::vector<const DexFile*>& dex_files) { 365 std::vector<std::string> parsed; 366 Split(class_path, ':', parsed); 367 // Take Locks::mutator_lock_ so that lock ordering on the ClassLinker::dex_lock_ is maintained. 368 ScopedObjectAccess soa(Thread::Current()); 369 for (size_t i = 0; i < parsed.size(); ++i) { 370 if (DexFilesContains(dex_files, parsed[i])) { 371 continue; 372 } 373 const DexFile* dex_file = DexFile::Open(parsed[i], parsed[i]); 374 if (dex_file == NULL) { 375 LOG(WARNING) << "Failed to open dex file " << parsed[i]; 376 } else { 377 dex_files.push_back(dex_file); 378 } 379 } 380 } 381 382 // Returns true if dex_files has a dex with the named location. 383 static bool DexFilesContains(const std::vector<const DexFile*>& dex_files, 384 const std::string& location) { 385 for (size_t i = 0; i < dex_files.size(); ++i) { 386 if (dex_files[i]->GetLocation() == location) { 387 return true; 388 } 389 } 390 return false; 391 } 392 393 const CompilerBackend compiler_backend_; 394 395 const InstructionSet instruction_set_; 396 397 Runtime* runtime_; 398 size_t thread_count_; 399 uint64_t start_ns_; 400 401 DISALLOW_IMPLICIT_CONSTRUCTORS(Dex2Oat); 402}; 403 404static bool ParseInt(const char* in, int* out) { 405 char* end; 406 int result = strtol(in, &end, 10); 407 if (in == end || *end != '\0') { 408 return false; 409 } 410 *out = result; 411 return true; 412} 413 414static size_t OpenDexFiles(const std::vector<const char*>& dex_filenames, 415 const std::vector<const char*>& dex_locations, 416 std::vector<const DexFile*>& dex_files) { 417 size_t failure_count = 0; 418 for (size_t i = 0; i < dex_filenames.size(); i++) { 419 const char* dex_filename = dex_filenames[i]; 420 const char* dex_location = dex_locations[i]; 421 const DexFile* dex_file = DexFile::Open(dex_filename, dex_location); 422 if (dex_file == NULL) { 423 LOG(WARNING) << "Could not open .dex from file '" << dex_filename << "'\n"; 424 ++failure_count; 425 } else { 426 dex_files.push_back(dex_file); 427 } 428 } 429 return failure_count; 430} 431 432// The primary goal of the watchdog is to prevent stuck build servers 433// during development when fatal aborts lead to a cascade of failures 434// that result in a deadlock. 435class WatchDog { 436// WatchDog defines its own CHECK_PTHREAD_CALL to avoid using Log which uses locks 437#undef CHECK_PTHREAD_CALL 438#define CHECK_WATCH_DOG_PTHREAD_CALL(call, args, what) \ 439 do { \ 440 int rc = call args; \ 441 if (rc != 0) { \ 442 errno = rc; \ 443 std::string message(# call); \ 444 message += " failed for "; \ 445 message += reason; \ 446 Fatal(message); \ 447 } \ 448 } while (false) 449 450 public: 451 explicit WatchDog(bool is_watch_dog_enabled) { 452 is_watch_dog_enabled_ = is_watch_dog_enabled; 453 if (!is_watch_dog_enabled_) { 454 return; 455 } 456 shutting_down_ = false; 457 const char* reason = "dex2oat watch dog thread startup"; 458 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_init, (&mutex_, NULL), reason); 459 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_init, (&cond_, NULL), reason); 460 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_init, (&attr_), reason); 461 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_create, (&pthread_, &attr_, &CallBack, this), reason); 462 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_attr_destroy, (&attr_), reason); 463 } 464 ~WatchDog() { 465 if (!is_watch_dog_enabled_) { 466 return; 467 } 468 const char* reason = "dex2oat watch dog thread shutdown"; 469 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason); 470 shutting_down_ = true; 471 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_signal, (&cond_), reason); 472 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason); 473 474 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_join, (pthread_, NULL), reason); 475 476 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_cond_destroy, (&cond_), reason); 477 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_destroy, (&mutex_), reason); 478 } 479 480 private: 481 static void* CallBack(void* arg) { 482 WatchDog* self = reinterpret_cast<WatchDog*>(arg); 483 ::art::SetThreadName("dex2oat watch dog"); 484 self->Wait(); 485 return NULL; 486 } 487 488 static void Message(char severity, const std::string& message) { 489 // TODO: Remove when we switch to LOG when we can guarantee it won't prevent shutdown in error 490 // cases. 491 fprintf(stderr, "dex2oat%s %c %d %d %s\n", 492 kIsDebugBuild ? "d" : "", 493 severity, 494 getpid(), 495 GetTid(), 496 message.c_str()); 497 } 498 499 static void Warn(const std::string& message) { 500 Message('W', message); 501 } 502 503 static void Fatal(const std::string& message) { 504 Message('F', message); 505 exit(1); 506 } 507 508 void Wait() { 509 bool warning = true; 510 CHECK_GT(kWatchDogTimeoutSeconds, kWatchDogWarningSeconds); 511 // TODO: tune the multiplier for GC verification, the following is just to make the timeout 512 // large. 513 int64_t multiplier = gc::kDesiredHeapVerification > gc::kVerifyAllFast ? 100 : 1; 514 timespec warning_ts; 515 InitTimeSpec(true, CLOCK_REALTIME, multiplier * kWatchDogWarningSeconds * 1000, 0, &warning_ts); 516 timespec timeout_ts; 517 InitTimeSpec(true, CLOCK_REALTIME, multiplier * kWatchDogTimeoutSeconds * 1000, 0, &timeout_ts); 518 const char* reason = "dex2oat watch dog thread waiting"; 519 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_lock, (&mutex_), reason); 520 while (!shutting_down_) { 521 int rc = TEMP_FAILURE_RETRY(pthread_cond_timedwait(&cond_, &mutex_, 522 warning ? &warning_ts 523 : &timeout_ts)); 524 if (rc == ETIMEDOUT) { 525 std::string message(StringPrintf("dex2oat did not finish after %d seconds", 526 warning ? kWatchDogWarningSeconds 527 : kWatchDogTimeoutSeconds)); 528 if (warning) { 529 Warn(message.c_str()); 530 warning = false; 531 } else { 532 Fatal(message.c_str()); 533 } 534 } else if (rc != 0) { 535 std::string message(StringPrintf("pthread_cond_timedwait failed: %s", 536 strerror(errno))); 537 Fatal(message.c_str()); 538 } 539 } 540 CHECK_WATCH_DOG_PTHREAD_CALL(pthread_mutex_unlock, (&mutex_), reason); 541 } 542 543 // When setting timeouts, keep in mind that the build server may not be as fast as your desktop. 544#if ART_USE_PORTABLE_COMPILER 545 static const unsigned int kWatchDogWarningSeconds = 2 * 60; // 2 minutes. 546 static const unsigned int kWatchDogTimeoutSeconds = 30 * 60; // 25 minutes + buffer. 547#else 548 static const unsigned int kWatchDogWarningSeconds = 1 * 60; // 1 minute. 549 static const unsigned int kWatchDogTimeoutSeconds = 6 * 60; // 5 minutes + buffer. 550#endif 551 552 bool is_watch_dog_enabled_; 553 bool shutting_down_; 554 // TODO: Switch to Mutex when we can guarantee it won't prevent shutdown in error cases. 555 pthread_mutex_t mutex_; 556 pthread_cond_t cond_; 557 pthread_attr_t attr_; 558 pthread_t pthread_; 559}; 560const unsigned int WatchDog::kWatchDogWarningSeconds; 561const unsigned int WatchDog::kWatchDogTimeoutSeconds; 562 563static int dex2oat(int argc, char** argv) { 564 base::TimingLogger timings("compiler", false, false); 565 566 InitLogging(argv); 567 568 // Skip over argv[0]. 569 argv++; 570 argc--; 571 572 if (argc == 0) { 573 Usage("no arguments specified"); 574 } 575 576 std::vector<const char*> dex_filenames; 577 std::vector<const char*> dex_locations; 578 int zip_fd = -1; 579 std::string zip_location; 580 std::string oat_filename; 581 std::string oat_symbols; 582 std::string oat_location; 583 int oat_fd = -1; 584 std::string bitcode_filename; 585 const char* image_classes_zip_filename = NULL; 586 const char* image_classes_filename = NULL; 587 std::string image_filename; 588 std::string boot_image_filename; 589 uintptr_t image_base = 0; 590 UniquePtr<std::string> host_prefix; 591 std::string android_root; 592 std::vector<const char*> runtime_args; 593 int thread_count = sysconf(_SC_NPROCESSORS_CONF); 594#if defined(ART_USE_PORTABLE_COMPILER) 595 CompilerBackend compiler_backend = kPortable; 596#else 597 CompilerBackend compiler_backend = kQuick; 598#endif 599#if defined(__arm__) 600 InstructionSet instruction_set = kThumb2; 601#elif defined(__i386__) 602 InstructionSet instruction_set = kX86; 603#elif defined(__mips__) 604 InstructionSet instruction_set = kMips; 605#else 606#error "Unsupported architecture" 607#endif 608 bool is_host = false; 609 bool dump_stats = kIsDebugBuild; 610 bool dump_timings = kIsDebugBuild; 611 bool watch_dog_enabled = !kIsTargetBuild; 612 613 614 for (int i = 0; i < argc; i++) { 615 const StringPiece option(argv[i]); 616 bool log_options = false; 617 if (log_options) { 618 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i]; 619 } 620 if (option.starts_with("--dex-file=")) { 621 dex_filenames.push_back(option.substr(strlen("--dex-file=")).data()); 622 } else if (option.starts_with("--dex-location=")) { 623 dex_locations.push_back(option.substr(strlen("--dex-location=")).data()); 624 } else if (option.starts_with("--zip-fd=")) { 625 const char* zip_fd_str = option.substr(strlen("--zip-fd=")).data(); 626 if (!ParseInt(zip_fd_str, &zip_fd)) { 627 Usage("could not parse --zip-fd argument '%s' as an integer", zip_fd_str); 628 } 629 } else if (option.starts_with("--zip-location=")) { 630 zip_location = option.substr(strlen("--zip-location=")).data(); 631 } else if (option.starts_with("--oat-file=")) { 632 oat_filename = option.substr(strlen("--oat-file=")).data(); 633 } else if (option.starts_with("--oat-symbols=")) { 634 oat_symbols = option.substr(strlen("--oat-symbols=")).data(); 635 } else if (option.starts_with("--oat-fd=")) { 636 const char* oat_fd_str = option.substr(strlen("--oat-fd=")).data(); 637 if (!ParseInt(oat_fd_str, &oat_fd)) { 638 Usage("could not parse --oat-fd argument '%s' as an integer", oat_fd_str); 639 } 640 } else if (option == "--watch-dog") { 641 watch_dog_enabled = true; 642 } else if (option == "--no-watch-dog") { 643 watch_dog_enabled = false; 644 } else if (option.starts_with("-j")) { 645 const char* thread_count_str = option.substr(strlen("-j")).data(); 646 if (!ParseInt(thread_count_str, &thread_count)) { 647 Usage("could not parse -j argument '%s' as an integer", thread_count_str); 648 } 649 } else if (option.starts_with("--oat-location=")) { 650 oat_location = option.substr(strlen("--oat-location=")).data(); 651 } else if (option.starts_with("--bitcode=")) { 652 bitcode_filename = option.substr(strlen("--bitcode=")).data(); 653 } else if (option.starts_with("--image=")) { 654 image_filename = option.substr(strlen("--image=")).data(); 655 } else if (option.starts_with("--image-classes=")) { 656 image_classes_filename = option.substr(strlen("--image-classes=")).data(); 657 } else if (option.starts_with("--image-classes-zip=")) { 658 image_classes_zip_filename = option.substr(strlen("--image-classes-zip=")).data(); 659 } else if (option.starts_with("--base=")) { 660 const char* image_base_str = option.substr(strlen("--base=")).data(); 661 char* end; 662 image_base = strtoul(image_base_str, &end, 16); 663 if (end == image_base_str || *end != '\0') { 664 Usage("Failed to parse hexadecimal value for option %s", option.data()); 665 } 666 } else if (option.starts_with("--boot-image=")) { 667 boot_image_filename = option.substr(strlen("--boot-image=")).data(); 668 } else if (option.starts_with("--host-prefix=")) { 669 host_prefix.reset(new std::string(option.substr(strlen("--host-prefix=")).data())); 670 } else if (option.starts_with("--android-root=")) { 671 android_root = option.substr(strlen("--android-root=")).data(); 672 } else if (option.starts_with("--instruction-set=")) { 673 StringPiece instruction_set_str = option.substr(strlen("--instruction-set=")).data(); 674 if (instruction_set_str == "arm") { 675 instruction_set = kThumb2; 676 } else if (instruction_set_str == "mips") { 677 instruction_set = kMips; 678 } else if (instruction_set_str == "x86") { 679 instruction_set = kX86; 680 } 681 } else if (option.starts_with("--compiler-backend=")) { 682 StringPiece backend_str = option.substr(strlen("--compiler-backend=")).data(); 683 if (backend_str == "Quick") { 684 compiler_backend = kQuick; 685 } else if (backend_str == "Portable") { 686 compiler_backend = kPortable; 687 } 688 } else if (option == "--host") { 689 is_host = true; 690 } else if (option == "--runtime-arg") { 691 if (++i >= argc) { 692 Usage("Missing required argument for --runtime-arg"); 693 } 694 if (log_options) { 695 LOG(INFO) << "dex2oat: option[" << i << "]=" << argv[i]; 696 } 697 runtime_args.push_back(argv[i]); 698 } else { 699 Usage("unknown argument %s", option.data()); 700 } 701 } 702 703 if (oat_filename.empty() && oat_fd == -1) { 704 Usage("Output must be supplied with either --oat-file or --oat-fd"); 705 } 706 707 if (!oat_filename.empty() && oat_fd != -1) { 708 Usage("--oat-file should not be used with --oat-fd"); 709 } 710 711 if (!oat_symbols.empty() && oat_fd != -1) { 712 Usage("--oat-symbols should not be used with --oat-fd"); 713 } 714 715 if (!oat_symbols.empty() && is_host) { 716 Usage("--oat-symbols should not be used with --host"); 717 } 718 719 if (oat_fd != -1 && !image_filename.empty()) { 720 Usage("--oat-fd should not be used with --image"); 721 } 722 723 if (host_prefix.get() == NULL) { 724 const char* android_product_out = getenv("ANDROID_PRODUCT_OUT"); 725 if (android_product_out != NULL) { 726 host_prefix.reset(new std::string(android_product_out)); 727 } 728 } 729 730 if (android_root.empty()) { 731 const char* android_root_env_var = getenv("ANDROID_ROOT"); 732 if (android_root_env_var == NULL) { 733 Usage("--android-root unspecified and ANDROID_ROOT not set"); 734 } 735 android_root += android_root_env_var; 736 } 737 738 bool image = (!image_filename.empty()); 739 if (!image && boot_image_filename.empty()) { 740 if (host_prefix.get() == NULL) { 741 boot_image_filename += GetAndroidRoot(); 742 } else { 743 boot_image_filename += *host_prefix.get(); 744 boot_image_filename += "/system"; 745 } 746 boot_image_filename += "/framework/boot.art"; 747 } 748 std::string boot_image_option; 749 if (!boot_image_filename.empty()) { 750 boot_image_option += "-Ximage:"; 751 boot_image_option += boot_image_filename; 752 } 753 754 if (image_classes_filename != NULL && !image) { 755 Usage("--image-classes should only be used with --image"); 756 } 757 758 if (image_classes_filename != NULL && !boot_image_option.empty()) { 759 Usage("--image-classes should not be used with --boot-image"); 760 } 761 762 if (image_classes_zip_filename != NULL && image_classes_filename == NULL) { 763 Usage("--image-classes-zip should be used with --image-classes"); 764 } 765 766 if (dex_filenames.empty() && zip_fd == -1) { 767 Usage("Input must be supplied with either --dex-file or --zip-fd"); 768 } 769 770 if (!dex_filenames.empty() && zip_fd != -1) { 771 Usage("--dex-file should not be used with --zip-fd"); 772 } 773 774 if (!dex_filenames.empty() && !zip_location.empty()) { 775 Usage("--dex-file should not be used with --zip-location"); 776 } 777 778 if (dex_locations.empty()) { 779 for (size_t i = 0; i < dex_filenames.size(); i++) { 780 dex_locations.push_back(dex_filenames[i]); 781 } 782 } else if (dex_locations.size() != dex_filenames.size()) { 783 Usage("--dex-location arguments do not match --dex-file arguments"); 784 } 785 786 if (zip_fd != -1 && zip_location.empty()) { 787 Usage("--zip-location should be supplied with --zip-fd"); 788 } 789 790 if (boot_image_option.empty()) { 791 if (image_base == 0) { 792 Usage("non-zero --base not specified"); 793 } 794 } 795 796 std::string oat_stripped(oat_filename); 797 std::string oat_unstripped; 798 if (!oat_symbols.empty()) { 799 oat_unstripped += oat_symbols; 800 } else { 801 oat_unstripped += oat_filename; 802 } 803 804 // Done with usage checks, enable watchdog if requested 805 WatchDog watch_dog(watch_dog_enabled); 806 807 // Check early that the result of compilation can be written 808 UniquePtr<File> oat_file; 809 bool create_file = !oat_unstripped.empty(); // as opposed to using open file descriptor 810 if (create_file) { 811 oat_file.reset(OS::OpenFile(oat_unstripped.c_str(), true)); 812 if (oat_location.empty()) { 813 oat_location = oat_filename; 814 } 815 } else { 816 oat_file.reset(new File(oat_fd, oat_location)); 817 oat_file->DisableAutoClose(); 818 } 819 if (oat_file.get() == NULL) { 820 PLOG(ERROR) << "Failed to create oat file: " << oat_location; 821 return EXIT_FAILURE; 822 } 823 if (create_file && fchmod(oat_file->Fd(), 0644) != 0) { 824 PLOG(ERROR) << "Failed to make oat file world readable: " << oat_location; 825 return EXIT_FAILURE; 826 } 827 828 LOG(INFO) << "dex2oat: " << oat_location; 829 830 Runtime::Options options; 831 options.push_back(std::make_pair("compiler", reinterpret_cast<void*>(NULL))); 832 std::vector<const DexFile*> boot_class_path; 833 if (boot_image_option.empty()) { 834 size_t failure_count = OpenDexFiles(dex_filenames, dex_locations, boot_class_path); 835 if (failure_count > 0) { 836 LOG(ERROR) << "Failed to open some dex files: " << failure_count; 837 return EXIT_FAILURE; 838 } 839 options.push_back(std::make_pair("bootclasspath", &boot_class_path)); 840 } else { 841 options.push_back(std::make_pair(boot_image_option.c_str(), reinterpret_cast<void*>(NULL))); 842 } 843 if (host_prefix.get() != NULL) { 844 options.push_back(std::make_pair("host-prefix", host_prefix->c_str())); 845 } 846 for (size_t i = 0; i < runtime_args.size(); i++) { 847 options.push_back(std::make_pair(runtime_args[i], reinterpret_cast<void*>(NULL))); 848 } 849 850#ifdef ART_SEA_IR_MODE 851 options.push_back(std::make_pair("-sea_ir", reinterpret_cast<void*>(NULL))); 852#endif 853 854 855 Dex2Oat* p_dex2oat; 856 if (!Dex2Oat::Create(&p_dex2oat, options, compiler_backend, instruction_set, thread_count)) { 857 LOG(ERROR) << "Failed to create dex2oat"; 858 return EXIT_FAILURE; 859 } 860 UniquePtr<Dex2Oat> dex2oat(p_dex2oat); 861 // Runtime::Create acquired the mutator_lock_ that is normally given away when we Runtime::Start, 862 // give it away now and then switch to a more managable ScopedObjectAccess. 863 Thread::Current()->TransitionFromRunnableToSuspended(kNative); 864 // Whilst we're in native take the opportunity to initialize well known classes. 865 WellKnownClasses::InitClasses(Thread::Current()->GetJniEnv()); 866 ScopedObjectAccess soa(Thread::Current()); 867 868 // If --image-classes was specified, calculate the full list of classes to include in the image 869 UniquePtr<CompilerDriver::DescriptorSet> image_classes(NULL); 870 if (image_classes_filename != NULL) { 871 if (image_classes_zip_filename != NULL) { 872 image_classes.reset(dex2oat->ReadImageClassesFromZip(image_classes_zip_filename, 873 image_classes_filename)); 874 } else { 875 image_classes.reset(dex2oat->ReadImageClassesFromFile(image_classes_filename)); 876 } 877 if (image_classes.get() == NULL) { 878 LOG(ERROR) << "Failed to create list of image classes from " << image_classes_filename; 879 return EXIT_FAILURE; 880 } 881 } 882 883 std::vector<const DexFile*> dex_files; 884 if (boot_image_option.empty()) { 885 dex_files = Runtime::Current()->GetClassLinker()->GetBootClassPath(); 886 } else { 887 if (dex_filenames.empty()) { 888 UniquePtr<ZipArchive> zip_archive(ZipArchive::OpenFromFd(zip_fd)); 889 if (zip_archive.get() == NULL) { 890 LOG(ERROR) << "Failed to open zip from file descriptor for " << zip_location; 891 return EXIT_FAILURE; 892 } 893 const DexFile* dex_file = DexFile::Open(*zip_archive.get(), zip_location); 894 if (dex_file == NULL) { 895 LOG(ERROR) << "Failed to open dex from file descriptor for zip file: " << zip_location; 896 return EXIT_FAILURE; 897 } 898 dex_files.push_back(dex_file); 899 } else { 900 size_t failure_count = OpenDexFiles(dex_filenames, dex_locations, dex_files); 901 if (failure_count > 0) { 902 LOG(ERROR) << "Failed to open some dex files: " << failure_count; 903 return EXIT_FAILURE; 904 } 905 } 906 } 907 908 // If we're doing the image, override the compiler filter to force full compilation. 909 if (image && Runtime::Current()->GetCompilerFilter() == Runtime::kInterpretOnly) { 910 Runtime::Current()->SetCompilerFilter(Runtime::kSpeed); 911 } 912 913 /* 914 * If we're not in interpret-only mode, go ahead and compile small applications. Don't 915 * bother to check if we're doing the image. 916 */ 917 if (!image && (Runtime::Current()->GetCompilerFilter() != Runtime::kInterpretOnly)) { 918 size_t num_methods = 0; 919 for (size_t i = 0; i != dex_files.size(); ++i) { 920 const DexFile* dex_file = dex_files[i]; 921 CHECK(dex_file != NULL); 922 num_methods += dex_file->NumMethodIds(); 923 } 924 if (num_methods <= Runtime::Current()->GetNumDexMethodsThreshold()) { 925 Runtime::Current()->SetCompilerFilter(Runtime::kSpeed); 926 LOG(INFO) << "Below method threshold, compiling anyways"; 927 } 928 } 929 930 timings.StartSplit("dex2oat Setup"); 931 UniquePtr<const CompilerDriver> compiler(dex2oat->CreateOatFile(boot_image_option, 932 host_prefix.get(), 933 android_root, 934 is_host, 935 dex_files, 936 oat_file.get(), 937 bitcode_filename, 938 image, 939 image_classes, 940 dump_stats, 941 timings)); 942 943 if (compiler.get() == NULL) { 944 LOG(ERROR) << "Failed to create oat file: " << oat_location; 945 return EXIT_FAILURE; 946 } 947 948 LOG(INFO) << "Oat file written successfully (unstripped): " << oat_location; 949 950 // Notes on the interleaving of creating the image and oat file to 951 // ensure the references between the two are correct. 952 // 953 // Currently we have a memory layout that looks something like this: 954 // 955 // +--------------+ 956 // | image | 957 // +--------------+ 958 // | boot oat | 959 // +--------------+ 960 // | alloc spaces | 961 // +--------------+ 962 // 963 // There are several constraints on the loading of the image and boot.oat. 964 // 965 // 1. The image is expected to be loaded at an absolute address and 966 // contains Objects with absolute pointers within the image. 967 // 968 // 2. There are absolute pointers from Methods in the image to their 969 // code in the oat. 970 // 971 // 3. There are absolute pointers from the code in the oat to Methods 972 // in the image. 973 // 974 // 4. There are absolute pointers from code in the oat to other code 975 // in the oat. 976 // 977 // To get this all correct, we go through several steps. 978 // 979 // 1. We have already created that oat file above with 980 // CreateOatFile. Originally this was just our own proprietary file 981 // but now it is contained within an ELF dynamic object (aka an .so 982 // file). The Compiler returned by CreateOatFile provides 983 // PatchInformation for references to oat code and Methods that need 984 // to be update once we know where the oat file will be located 985 // after the image. 986 // 987 // 2. We create the image file. It needs to know where the oat file 988 // will be loaded after itself. Originally when oat file was simply 989 // memory mapped so we could predict where its contents were based 990 // on the file size. Now that it is an ELF file, we need to inspect 991 // the ELF file to understand the in memory segment layout including 992 // where the oat header is located within. ImageWriter's 993 // PatchOatCodeAndMethods uses the PatchInformation from the 994 // Compiler to touch up absolute references in the oat file. 995 // 996 // 3. We fixup the ELF program headers so that dlopen will try to 997 // load the .so at the desired location at runtime by offsetting the 998 // Elf32_Phdr.p_vaddr values by the desired base address. 999 // 1000 if (image) { 1001 timings.NewSplit("dex2oat ImageWriter"); 1002 Thread::Current()->TransitionFromRunnableToSuspended(kNative); 1003 bool image_creation_success = dex2oat->CreateImageFile(image_filename, 1004 image_base, 1005 oat_unstripped, 1006 oat_location, 1007 *compiler.get()); 1008 Thread::Current()->TransitionFromSuspendedToRunnable(); 1009 if (!image_creation_success) { 1010 return EXIT_FAILURE; 1011 } 1012 LOG(INFO) << "Image written successfully: " << image_filename; 1013 } 1014 1015 if (is_host) { 1016 if (dump_timings && timings.GetTotalNs() > MsToNs(1000)) { 1017 LOG(INFO) << Dumpable<base::TimingLogger>(timings); 1018 } 1019 return EXIT_SUCCESS; 1020 } 1021 1022 // If we don't want to strip in place, copy from unstripped location to stripped location. 1023 // We need to strip after image creation because FixupElf needs to use .strtab. 1024 if (oat_unstripped != oat_stripped) { 1025 timings.NewSplit("dex2oat OatFile copy"); 1026 oat_file.reset(); 1027 UniquePtr<File> in(OS::OpenFile(oat_unstripped.c_str(), false)); 1028 UniquePtr<File> out(OS::OpenFile(oat_stripped.c_str(), true)); 1029 size_t buffer_size = 8192; 1030 UniquePtr<uint8_t> buffer(new uint8_t[buffer_size]); 1031 while (true) { 1032 int bytes_read = TEMP_FAILURE_RETRY(read(in->Fd(), buffer.get(), buffer_size)); 1033 if (bytes_read <= 0) { 1034 break; 1035 } 1036 bool write_ok = out->WriteFully(buffer.get(), bytes_read); 1037 CHECK(write_ok); 1038 } 1039 oat_file.reset(out.release()); 1040 LOG(INFO) << "Oat file copied successfully (stripped): " << oat_stripped; 1041 } 1042 1043#if ART_USE_PORTABLE_COMPILER // We currently only generate symbols on Portable 1044 timings.NewSplit("dex2oat ElfStripper"); 1045 // Strip unneeded sections for target 1046 off_t seek_actual = lseek(oat_file->Fd(), 0, SEEK_SET); 1047 CHECK_EQ(0, seek_actual); 1048 ElfStripper::Strip(oat_file.get()); 1049 1050 1051 // We wrote the oat file successfully, and want to keep it. 1052 LOG(INFO) << "Oat file written successfully (stripped): " << oat_location; 1053#endif // ART_USE_PORTABLE_COMPILER 1054 1055 timings.EndSplit(); 1056 1057 if (dump_timings && timings.GetTotalNs() > MsToNs(1000)) { 1058 LOG(INFO) << Dumpable<base::TimingLogger>(timings); 1059 } 1060 return EXIT_SUCCESS; 1061} 1062 1063 1064} // namespace art 1065 1066int main(int argc, char** argv) { 1067 return art::dex2oat(argc, argv); 1068} 1069