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