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