patchoat.cc revision d4c4d953035d4418126d36517e402f411d6a87f3
1/* 2 * Copyright (C) 2014 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#include "patchoat.h" 17 18#include <stdio.h> 19#include <stdlib.h> 20#include <sys/file.h> 21#include <sys/stat.h> 22#include <unistd.h> 23 24#include <string> 25#include <vector> 26 27#include "base/scoped_flock.h" 28#include "base/stringpiece.h" 29#include "base/stringprintf.h" 30#include "base/unix_file/fd_file.h" 31#include "elf_utils.h" 32#include "elf_file.h" 33#include "elf_file_impl.h" 34#include "gc/space/image_space.h" 35#include "image.h" 36#include "instruction_set.h" 37#include "mirror/art_field.h" 38#include "mirror/art_field-inl.h" 39#include "mirror/art_method.h" 40#include "mirror/art_method-inl.h" 41#include "mirror/object.h" 42#include "mirror/object-inl.h" 43#include "mirror/reference.h" 44#include "noop_compiler_callbacks.h" 45#include "offsets.h" 46#include "os.h" 47#include "runtime.h" 48#include "scoped_thread_state_change.h" 49#include "thread.h" 50#include "utils.h" 51 52namespace art { 53 54static InstructionSet ElfISAToInstructionSet(Elf32_Word isa) { 55 switch (isa) { 56 case EM_ARM: 57 return kArm; 58 case EM_AARCH64: 59 return kArm64; 60 case EM_386: 61 return kX86; 62 case EM_X86_64: 63 return kX86_64; 64 case EM_MIPS: 65 return kMips; 66 default: 67 return kNone; 68 } 69} 70 71static bool LocationToFilename(const std::string& location, InstructionSet isa, 72 std::string* filename) { 73 bool has_system = false; 74 bool has_cache = false; 75 // image_location = /system/framework/boot.art 76 // system_image_location = /system/framework/<image_isa>/boot.art 77 std::string system_filename(GetSystemImageFilename(location.c_str(), isa)); 78 if (OS::FileExists(system_filename.c_str())) { 79 has_system = true; 80 } 81 82 bool have_android_data = false; 83 bool dalvik_cache_exists = false; 84 bool is_global_cache = false; 85 std::string dalvik_cache; 86 GetDalvikCache(GetInstructionSetString(isa), false, &dalvik_cache, 87 &have_android_data, &dalvik_cache_exists, &is_global_cache); 88 89 std::string cache_filename; 90 if (have_android_data && dalvik_cache_exists) { 91 // Always set output location even if it does not exist, 92 // so that the caller knows where to create the image. 93 // 94 // image_location = /system/framework/boot.art 95 // *image_filename = /data/dalvik-cache/<image_isa>/boot.art 96 std::string error_msg; 97 if (GetDalvikCacheFilename(location.c_str(), dalvik_cache.c_str(), 98 &cache_filename, &error_msg)) { 99 has_cache = true; 100 } 101 } 102 if (has_system) { 103 *filename = system_filename; 104 return true; 105 } else if (has_cache) { 106 *filename = cache_filename; 107 return true; 108 } else { 109 return false; 110 } 111} 112 113bool PatchOat::Patch(const std::string& image_location, off_t delta, 114 File* output_image, InstructionSet isa, 115 TimingLogger* timings) { 116 CHECK(Runtime::Current() == nullptr); 117 CHECK(output_image != nullptr); 118 CHECK_GE(output_image->Fd(), 0); 119 CHECK(!image_location.empty()) << "image file must have a filename."; 120 CHECK_NE(isa, kNone); 121 122 TimingLogger::ScopedTiming t("Runtime Setup", timings); 123 const char *isa_name = GetInstructionSetString(isa); 124 std::string image_filename; 125 if (!LocationToFilename(image_location, isa, &image_filename)) { 126 LOG(ERROR) << "Unable to find image at location " << image_location; 127 return false; 128 } 129 std::unique_ptr<File> input_image(OS::OpenFileForReading(image_filename.c_str())); 130 if (input_image.get() == nullptr) { 131 LOG(ERROR) << "unable to open input image file at " << image_filename 132 << " for location " << image_location; 133 return false; 134 } 135 int64_t image_len = input_image->GetLength(); 136 if (image_len < 0) { 137 LOG(ERROR) << "Error while getting image length"; 138 return false; 139 } 140 ImageHeader image_header; 141 if (sizeof(image_header) != input_image->Read(reinterpret_cast<char*>(&image_header), 142 sizeof(image_header), 0)) { 143 LOG(ERROR) << "Unable to read image header from image file " << input_image->GetPath(); 144 return false; 145 } 146 147 // Set up the runtime 148 RuntimeOptions options; 149 NoopCompilerCallbacks callbacks; 150 options.push_back(std::make_pair("compilercallbacks", &callbacks)); 151 std::string img = "-Ximage:" + image_location; 152 options.push_back(std::make_pair(img.c_str(), nullptr)); 153 options.push_back(std::make_pair("imageinstructionset", reinterpret_cast<const void*>(isa_name))); 154 if (!Runtime::Create(options, false)) { 155 LOG(ERROR) << "Unable to initialize runtime"; 156 return false; 157 } 158 // Runtime::Create acquired the mutator_lock_ that is normally given away when we Runtime::Start, 159 // give it away now and then switch to a more manageable ScopedObjectAccess. 160 Thread::Current()->TransitionFromRunnableToSuspended(kNative); 161 ScopedObjectAccess soa(Thread::Current()); 162 163 t.NewTiming("Image and oat Patching setup"); 164 // Create the map where we will write the image patches to. 165 std::string error_msg; 166 std::unique_ptr<MemMap> image(MemMap::MapFile(image_len, PROT_READ | PROT_WRITE, MAP_PRIVATE, 167 input_image->Fd(), 0, 168 input_image->GetPath().c_str(), 169 &error_msg)); 170 if (image.get() == nullptr) { 171 LOG(ERROR) << "unable to map image file " << input_image->GetPath() << " : " << error_msg; 172 return false; 173 } 174 gc::space::ImageSpace* ispc = Runtime::Current()->GetHeap()->GetImageSpace(); 175 176 PatchOat p(image.release(), ispc->GetLiveBitmap(), ispc->GetMemMap(), 177 delta, timings); 178 t.NewTiming("Patching files"); 179 if (!p.PatchImage()) { 180 LOG(ERROR) << "Failed to patch image file " << input_image->GetPath(); 181 return false; 182 } 183 184 t.NewTiming("Writing files"); 185 if (!p.WriteImage(output_image)) { 186 return false; 187 } 188 return true; 189} 190 191bool PatchOat::Patch(const File* input_oat, const std::string& image_location, off_t delta, 192 File* output_oat, File* output_image, InstructionSet isa, 193 TimingLogger* timings) { 194 CHECK(Runtime::Current() == nullptr); 195 CHECK(output_image != nullptr); 196 CHECK_GE(output_image->Fd(), 0); 197 CHECK(input_oat != nullptr); 198 CHECK(output_oat != nullptr); 199 CHECK_GE(input_oat->Fd(), 0); 200 CHECK_GE(output_oat->Fd(), 0); 201 CHECK(!image_location.empty()) << "image file must have a filename."; 202 203 TimingLogger::ScopedTiming t("Runtime Setup", timings); 204 205 if (isa == kNone) { 206 Elf32_Ehdr elf_hdr; 207 if (sizeof(elf_hdr) != input_oat->Read(reinterpret_cast<char*>(&elf_hdr), sizeof(elf_hdr), 0)) { 208 LOG(ERROR) << "unable to read elf header"; 209 return false; 210 } 211 isa = ElfISAToInstructionSet(elf_hdr.e_machine); 212 } 213 const char* isa_name = GetInstructionSetString(isa); 214 std::string image_filename; 215 if (!LocationToFilename(image_location, isa, &image_filename)) { 216 LOG(ERROR) << "Unable to find image at location " << image_location; 217 return false; 218 } 219 std::unique_ptr<File> input_image(OS::OpenFileForReading(image_filename.c_str())); 220 if (input_image.get() == nullptr) { 221 LOG(ERROR) << "unable to open input image file at " << image_filename 222 << " for location " << image_location; 223 return false; 224 } 225 int64_t image_len = input_image->GetLength(); 226 if (image_len < 0) { 227 LOG(ERROR) << "Error while getting image length"; 228 return false; 229 } 230 ImageHeader image_header; 231 if (sizeof(image_header) != input_image->Read(reinterpret_cast<char*>(&image_header), 232 sizeof(image_header), 0)) { 233 LOG(ERROR) << "Unable to read image header from image file " << input_image->GetPath(); 234 } 235 236 // Set up the runtime 237 RuntimeOptions options; 238 NoopCompilerCallbacks callbacks; 239 options.push_back(std::make_pair("compilercallbacks", &callbacks)); 240 std::string img = "-Ximage:" + image_location; 241 options.push_back(std::make_pair(img.c_str(), nullptr)); 242 options.push_back(std::make_pair("imageinstructionset", reinterpret_cast<const void*>(isa_name))); 243 if (!Runtime::Create(options, false)) { 244 LOG(ERROR) << "Unable to initialize runtime"; 245 return false; 246 } 247 // Runtime::Create acquired the mutator_lock_ that is normally given away when we Runtime::Start, 248 // give it away now and then switch to a more manageable ScopedObjectAccess. 249 Thread::Current()->TransitionFromRunnableToSuspended(kNative); 250 ScopedObjectAccess soa(Thread::Current()); 251 252 t.NewTiming("Image and oat Patching setup"); 253 // Create the map where we will write the image patches to. 254 std::string error_msg; 255 std::unique_ptr<MemMap> image(MemMap::MapFile(image_len, PROT_READ | PROT_WRITE, MAP_PRIVATE, 256 input_image->Fd(), 0, 257 input_image->GetPath().c_str(), 258 &error_msg)); 259 if (image.get() == nullptr) { 260 LOG(ERROR) << "unable to map image file " << input_image->GetPath() << " : " << error_msg; 261 return false; 262 } 263 gc::space::ImageSpace* ispc = Runtime::Current()->GetHeap()->GetImageSpace(); 264 265 std::unique_ptr<ElfFile> elf(ElfFile::Open(const_cast<File*>(input_oat), 266 PROT_READ | PROT_WRITE, MAP_PRIVATE, &error_msg)); 267 if (elf.get() == nullptr) { 268 LOG(ERROR) << "unable to open oat file " << input_oat->GetPath() << " : " << error_msg; 269 return false; 270 } 271 272 PatchOat p(elf.release(), image.release(), ispc->GetLiveBitmap(), ispc->GetMemMap(), 273 delta, timings); 274 t.NewTiming("Patching files"); 275 if (!p.PatchElf()) { 276 LOG(ERROR) << "Failed to patch oat file " << input_oat->GetPath(); 277 return false; 278 } 279 if (!p.PatchImage()) { 280 LOG(ERROR) << "Failed to patch image file " << input_image->GetPath(); 281 return false; 282 } 283 284 t.NewTiming("Writing files"); 285 if (!p.WriteElf(output_oat)) { 286 return false; 287 } 288 if (!p.WriteImage(output_image)) { 289 return false; 290 } 291 return true; 292} 293 294bool PatchOat::WriteElf(File* out) { 295 TimingLogger::ScopedTiming t("Writing Elf File", timings_); 296 297 CHECK(oat_file_.get() != nullptr); 298 CHECK(out != nullptr); 299 size_t expect = oat_file_->Size(); 300 if (out->WriteFully(reinterpret_cast<char*>(oat_file_->Begin()), expect) && 301 out->SetLength(expect) == 0) { 302 return true; 303 } else { 304 LOG(ERROR) << "Writing to oat file " << out->GetPath() << " failed."; 305 return false; 306 } 307} 308 309bool PatchOat::WriteImage(File* out) { 310 TimingLogger::ScopedTiming t("Writing image File", timings_); 311 std::string error_msg; 312 313 ScopedFlock img_flock; 314 img_flock.Init(out, &error_msg); 315 316 CHECK(image_ != nullptr); 317 CHECK(out != nullptr); 318 size_t expect = image_->Size(); 319 if (out->WriteFully(reinterpret_cast<char*>(image_->Begin()), expect) && 320 out->SetLength(expect) == 0) { 321 return true; 322 } else { 323 LOG(ERROR) << "Writing to image file " << out->GetPath() << " failed."; 324 return false; 325 } 326} 327 328bool PatchOat::PatchImage() { 329 ImageHeader* image_header = reinterpret_cast<ImageHeader*>(image_->Begin()); 330 CHECK_GT(image_->Size(), sizeof(ImageHeader)); 331 // These are the roots from the original file. 332 mirror::Object* img_roots = image_header->GetImageRoots(); 333 image_header->RelocateImage(delta_); 334 335 VisitObject(img_roots); 336 if (!image_header->IsValid()) { 337 LOG(ERROR) << "reloction renders image header invalid"; 338 return false; 339 } 340 341 { 342 TimingLogger::ScopedTiming t("Walk Bitmap", timings_); 343 // Walk the bitmap. 344 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_); 345 bitmap_->Walk(PatchOat::BitmapCallback, this); 346 } 347 return true; 348} 349 350bool PatchOat::InHeap(mirror::Object* o) { 351 uintptr_t begin = reinterpret_cast<uintptr_t>(heap_->Begin()); 352 uintptr_t end = reinterpret_cast<uintptr_t>(heap_->End()); 353 uintptr_t obj = reinterpret_cast<uintptr_t>(o); 354 return o == nullptr || (begin <= obj && obj < end); 355} 356 357void PatchOat::PatchVisitor::operator() (mirror::Object* obj, MemberOffset off, 358 bool is_static_unused) const { 359 mirror::Object* referent = obj->GetFieldObject<mirror::Object, kVerifyNone>(off); 360 DCHECK(patcher_->InHeap(referent)) << "Referent is not in the heap."; 361 mirror::Object* moved_object = patcher_->RelocatedAddressOf(referent); 362 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(off, moved_object); 363} 364 365void PatchOat::PatchVisitor::operator() (mirror::Class* cls, mirror::Reference* ref) const { 366 MemberOffset off = mirror::Reference::ReferentOffset(); 367 mirror::Object* referent = ref->GetReferent(); 368 DCHECK(patcher_->InHeap(referent)) << "Referent is not in the heap."; 369 mirror::Object* moved_object = patcher_->RelocatedAddressOf(referent); 370 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(off, moved_object); 371} 372 373mirror::Object* PatchOat::RelocatedCopyOf(mirror::Object* obj) { 374 if (obj == nullptr) { 375 return nullptr; 376 } 377 DCHECK_GT(reinterpret_cast<uintptr_t>(obj), reinterpret_cast<uintptr_t>(heap_->Begin())); 378 DCHECK_LT(reinterpret_cast<uintptr_t>(obj), reinterpret_cast<uintptr_t>(heap_->End())); 379 uintptr_t heap_off = 380 reinterpret_cast<uintptr_t>(obj) - reinterpret_cast<uintptr_t>(heap_->Begin()); 381 DCHECK_LT(heap_off, image_->Size()); 382 return reinterpret_cast<mirror::Object*>(image_->Begin() + heap_off); 383} 384 385mirror::Object* PatchOat::RelocatedAddressOf(mirror::Object* obj) { 386 if (obj == nullptr) { 387 return nullptr; 388 } else { 389 return reinterpret_cast<mirror::Object*>(reinterpret_cast<uint8_t*>(obj) + delta_); 390 } 391} 392 393// Called by BitmapCallback 394void PatchOat::VisitObject(mirror::Object* object) { 395 mirror::Object* copy = RelocatedCopyOf(object); 396 CHECK(copy != nullptr); 397 if (kUseBakerOrBrooksReadBarrier) { 398 object->AssertReadBarrierPointer(); 399 if (kUseBrooksReadBarrier) { 400 mirror::Object* moved_to = RelocatedAddressOf(object); 401 copy->SetReadBarrierPointer(moved_to); 402 DCHECK_EQ(copy->GetReadBarrierPointer(), moved_to); 403 } 404 } 405 PatchOat::PatchVisitor visitor(this, copy); 406 object->VisitReferences<true, kVerifyNone>(visitor, visitor); 407 if (object->IsArtMethod<kVerifyNone>()) { 408 FixupMethod(static_cast<mirror::ArtMethod*>(object), 409 static_cast<mirror::ArtMethod*>(copy)); 410 } 411} 412 413void PatchOat::FixupMethod(mirror::ArtMethod* object, mirror::ArtMethod* copy) { 414 // Just update the entry points if it looks like we should. 415 // TODO: sanity check all the pointers' values 416 uintptr_t portable = reinterpret_cast<uintptr_t>( 417 object->GetEntryPointFromPortableCompiledCode<kVerifyNone>()); 418 if (portable != 0) { 419 copy->SetEntryPointFromPortableCompiledCode(reinterpret_cast<void*>(portable + delta_)); 420 } 421 uintptr_t quick= reinterpret_cast<uintptr_t>( 422 object->GetEntryPointFromQuickCompiledCode<kVerifyNone>()); 423 if (quick != 0) { 424 copy->SetEntryPointFromQuickCompiledCode(reinterpret_cast<void*>(quick + delta_)); 425 } 426 uintptr_t interpreter = reinterpret_cast<uintptr_t>( 427 object->GetEntryPointFromInterpreter<kVerifyNone>()); 428 if (interpreter != 0) { 429 copy->SetEntryPointFromInterpreter( 430 reinterpret_cast<mirror::EntryPointFromInterpreter*>(interpreter + delta_)); 431 } 432 433 uintptr_t native_method = reinterpret_cast<uintptr_t>(object->GetNativeMethod()); 434 if (native_method != 0) { 435 copy->SetNativeMethod(reinterpret_cast<void*>(native_method + delta_)); 436 } 437 438 uintptr_t native_gc_map = reinterpret_cast<uintptr_t>(object->GetNativeGcMap()); 439 if (native_gc_map != 0) { 440 copy->SetNativeGcMap(reinterpret_cast<uint8_t*>(native_gc_map + delta_)); 441 } 442} 443 444bool PatchOat::Patch(File* input_oat, off_t delta, File* output_oat, TimingLogger* timings) { 445 CHECK(input_oat != nullptr); 446 CHECK(output_oat != nullptr); 447 CHECK_GE(input_oat->Fd(), 0); 448 CHECK_GE(output_oat->Fd(), 0); 449 TimingLogger::ScopedTiming t("Setup Oat File Patching", timings); 450 451 std::string error_msg; 452 std::unique_ptr<ElfFile> elf(ElfFile::Open(const_cast<File*>(input_oat), 453 PROT_READ | PROT_WRITE, MAP_PRIVATE, &error_msg)); 454 if (elf.get() == nullptr) { 455 LOG(ERROR) << "unable to open oat file " << input_oat->GetPath() << " : " << error_msg; 456 return false; 457 } 458 459 PatchOat p(elf.release(), delta, timings); 460 t.NewTiming("Patch Oat file"); 461 if (!p.PatchElf()) { 462 return false; 463 } 464 465 t.NewTiming("Writing oat file"); 466 if (!p.WriteElf(output_oat)) { 467 return false; 468 } 469 return true; 470} 471 472template <typename ElfFileImpl, typename ptr_t> 473bool PatchOat::CheckOatFile(ElfFileImpl* oat_file) { 474 auto patches_sec = oat_file->FindSectionByName(".oat_patches"); 475 if (patches_sec->sh_type != SHT_OAT_PATCH) { 476 return false; 477 } 478 ptr_t* patches = reinterpret_cast<ptr_t*>(oat_file->Begin() + patches_sec->sh_offset); 479 ptr_t* patches_end = patches + (patches_sec->sh_size / sizeof(ptr_t)); 480 auto oat_data_sec = oat_file->FindSectionByName(".rodata"); 481 auto oat_text_sec = oat_file->FindSectionByName(".text"); 482 if (oat_data_sec == nullptr) { 483 return false; 484 } 485 if (oat_text_sec == nullptr) { 486 return false; 487 } 488 if (oat_text_sec->sh_offset <= oat_data_sec->sh_offset) { 489 return false; 490 } 491 492 for (; patches < patches_end; patches++) { 493 if (oat_text_sec->sh_size <= *patches) { 494 return false; 495 } 496 } 497 498 return true; 499} 500 501template <typename ElfFileImpl> 502bool PatchOat::PatchOatHeader(ElfFileImpl* oat_file) { 503 auto rodata_sec = oat_file->FindSectionByName(".rodata"); 504 if (rodata_sec == nullptr) { 505 return false; 506 } 507 OatHeader* oat_header = reinterpret_cast<OatHeader*>(oat_file->Begin() + rodata_sec->sh_offset); 508 if (!oat_header->IsValid()) { 509 LOG(ERROR) << "Elf file " << oat_file->GetFile().GetPath() << " has an invalid oat header"; 510 return false; 511 } 512 oat_header->RelocateOat(delta_); 513 return true; 514} 515 516bool PatchOat::PatchElf() { 517 if (oat_file_->Is64Bit()) 518 return PatchElf<ElfFileImpl64>(oat_file_->GetImpl64()); 519 else 520 return PatchElf<ElfFileImpl32>(oat_file_->GetImpl32()); 521} 522 523template <typename ElfFileImpl> 524bool PatchOat::PatchElf(ElfFileImpl* oat_file) { 525 TimingLogger::ScopedTiming t("Fixup Elf Text Section", timings_); 526 if (!PatchTextSection<ElfFileImpl>(oat_file)) { 527 return false; 528 } 529 530 if (!PatchOatHeader<ElfFileImpl>(oat_file)) { 531 return false; 532 } 533 534 bool need_fixup = false; 535 for (unsigned int i = 0; i < oat_file->GetProgramHeaderNum(); ++i) { 536 auto hdr = oat_file->GetProgramHeader(i); 537 if ((hdr->p_vaddr != 0 && hdr->p_vaddr != hdr->p_offset) || 538 (hdr->p_paddr != 0 && hdr->p_paddr != hdr->p_offset)) { 539 need_fixup = true; 540 break; 541 } 542 } 543 if (!need_fixup) { 544 // This was never passed through ElfFixup so all headers/symbols just have their offset as 545 // their addr. Therefore we do not need to update these parts. 546 return true; 547 } 548 549 t.NewTiming("Fixup Elf Headers"); 550 // Fixup Phdr's 551 oat_file->FixupProgramHeaders(delta_); 552 553 t.NewTiming("Fixup Section Headers"); 554 // Fixup Shdr's 555 oat_file->FixupSectionHeaders(delta_); 556 557 t.NewTiming("Fixup Dynamics"); 558 oat_file->FixupDynamic(delta_); 559 560 t.NewTiming("Fixup Elf Symbols"); 561 // Fixup dynsym 562 if (!oat_file->FixupSymbols(delta_, true)) { 563 return false; 564 } 565 // Fixup symtab 566 if (!oat_file->FixupSymbols(delta_, false)) { 567 return false; 568 } 569 570 t.NewTiming("Fixup Debug Sections"); 571 if (!oat_file->FixupDebugSections(delta_)) { 572 return false; 573 } 574 575 return true; 576} 577 578template <typename ElfFileImpl> 579bool PatchOat::PatchTextSection(ElfFileImpl* oat_file) { 580 auto patches_sec = oat_file->FindSectionByName(".oat_patches"); 581 if (patches_sec == nullptr) { 582 LOG(ERROR) << ".oat_patches section not found. Aborting patch"; 583 return false; 584 } 585 if (patches_sec->sh_type != SHT_OAT_PATCH) { 586 LOG(ERROR) << "Unexpected type of .oat_patches"; 587 return false; 588 } 589 590 switch (patches_sec->sh_entsize) { 591 case sizeof(uint32_t): 592 return PatchTextSection<ElfFileImpl, uint32_t>(oat_file); 593 case sizeof(uint64_t): 594 return PatchTextSection<ElfFileImpl, uint64_t>(oat_file); 595 default: 596 LOG(ERROR) << ".oat_patches Entsize of " << patches_sec->sh_entsize << "bits " 597 << "is not valid"; 598 return false; 599 } 600} 601 602template <typename ElfFileImpl, typename patch_loc_t> 603bool PatchOat::PatchTextSection(ElfFileImpl* oat_file) { 604 bool oat_file_valid = CheckOatFile<ElfFileImpl, patch_loc_t>(oat_file); 605 CHECK(oat_file_valid) << "Oat file invalid"; 606 auto patches_sec = oat_file->FindSectionByName(".oat_patches"); 607 patch_loc_t* patches = reinterpret_cast<patch_loc_t*>(oat_file->Begin() + patches_sec->sh_offset); 608 patch_loc_t* patches_end = patches + (patches_sec->sh_size / sizeof(patch_loc_t)); 609 auto oat_text_sec = oat_file->FindSectionByName(".text"); 610 CHECK(oat_text_sec != nullptr); 611 uint8_t* to_patch = oat_file->Begin() + oat_text_sec->sh_offset; 612 uintptr_t to_patch_end = reinterpret_cast<uintptr_t>(to_patch) + oat_text_sec->sh_size; 613 614 for (; patches < patches_end; patches++) { 615 CHECK_LT(*patches, oat_text_sec->sh_size) << "Bad Patch"; 616 uint32_t* patch_loc = reinterpret_cast<uint32_t*>(to_patch + *patches); 617 CHECK_LT(reinterpret_cast<uintptr_t>(patch_loc), to_patch_end); 618 *patch_loc += delta_; 619 } 620 return true; 621} 622 623static int orig_argc; 624static char** orig_argv; 625 626static std::string CommandLine() { 627 std::vector<std::string> command; 628 for (int i = 0; i < orig_argc; ++i) { 629 command.push_back(orig_argv[i]); 630 } 631 return Join(command, ' '); 632} 633 634static void UsageErrorV(const char* fmt, va_list ap) { 635 std::string error; 636 StringAppendV(&error, fmt, ap); 637 LOG(ERROR) << error; 638} 639 640static void UsageError(const char* fmt, ...) { 641 va_list ap; 642 va_start(ap, fmt); 643 UsageErrorV(fmt, ap); 644 va_end(ap); 645} 646 647[[noreturn]] static void Usage(const char *fmt, ...) { 648 va_list ap; 649 va_start(ap, fmt); 650 UsageErrorV(fmt, ap); 651 va_end(ap); 652 653 UsageError("Command: %s", CommandLine().c_str()); 654 UsageError("Usage: patchoat [options]..."); 655 UsageError(""); 656 UsageError(" --instruction-set=<isa>: Specifies the instruction set the patched code is"); 657 UsageError(" compiled for. Required if you use --input-oat-location"); 658 UsageError(""); 659 UsageError(" --input-oat-file=<file.oat>: Specifies the exact filename of the oat file to be"); 660 UsageError(" patched."); 661 UsageError(""); 662 UsageError(" --input-oat-fd=<file-descriptor>: Specifies the file-descriptor of the oat file"); 663 UsageError(" to be patched."); 664 UsageError(""); 665 UsageError(" --input-oat-location=<file.oat>: Specifies the 'location' to read the patched"); 666 UsageError(" oat file from. If used one must also supply the --instruction-set"); 667 UsageError(""); 668 UsageError(" --input-image-location=<file.art>: Specifies the 'location' of the image file to"); 669 UsageError(" be patched. If --instruction-set is not given it will use the instruction set"); 670 UsageError(" extracted from the --input-oat-file."); 671 UsageError(""); 672 UsageError(" --output-oat-file=<file.oat>: Specifies the exact file to write the patched oat"); 673 UsageError(" file to."); 674 UsageError(""); 675 UsageError(" --output-oat-fd=<file-descriptor>: Specifies the file-descriptor to write the"); 676 UsageError(" the patched oat file to."); 677 UsageError(""); 678 UsageError(" --output-image-file=<file.art>: Specifies the exact file to write the patched"); 679 UsageError(" image file to."); 680 UsageError(""); 681 UsageError(" --output-image-fd=<file-descriptor>: Specifies the file-descriptor to write the"); 682 UsageError(" the patched image file to."); 683 UsageError(""); 684 UsageError(" --orig-base-offset=<original-base-offset>: Specify the base offset the input file"); 685 UsageError(" was compiled with. This is needed if one is specifying a --base-offset"); 686 UsageError(""); 687 UsageError(" --base-offset=<new-base-offset>: Specify the base offset we will repatch the"); 688 UsageError(" given files to use. This requires that --orig-base-offset is also given."); 689 UsageError(""); 690 UsageError(" --base-offset-delta=<delta>: Specify the amount to change the old base-offset by."); 691 UsageError(" This value may be negative."); 692 UsageError(""); 693 UsageError(" --patched-image-file=<file.art>: Use the same patch delta as was used to patch"); 694 UsageError(" the given image file."); 695 UsageError(""); 696 UsageError(" --patched-image-location=<file.art>: Use the same patch delta as was used to"); 697 UsageError(" patch the given image location. If used one must also specify the"); 698 UsageError(" --instruction-set flag. It will search for this image in the same way that"); 699 UsageError(" is done when loading one."); 700 UsageError(""); 701 UsageError(" --lock-output: Obtain a flock on output oat file before starting."); 702 UsageError(""); 703 UsageError(" --no-lock-output: Do not attempt to obtain a flock on output oat file."); 704 UsageError(""); 705 UsageError(" --dump-timings: dump out patch timing information"); 706 UsageError(""); 707 UsageError(" --no-dump-timings: do not dump out patch timing information"); 708 UsageError(""); 709 710 exit(EXIT_FAILURE); 711} 712 713static bool ReadBaseDelta(const char* name, off_t* delta, std::string* error_msg) { 714 CHECK(name != nullptr); 715 CHECK(delta != nullptr); 716 std::unique_ptr<File> file; 717 if (OS::FileExists(name)) { 718 file.reset(OS::OpenFileForReading(name)); 719 if (file.get() == nullptr) { 720 *error_msg = "Failed to open file %s for reading"; 721 return false; 722 } 723 } else { 724 *error_msg = "File %s does not exist"; 725 return false; 726 } 727 CHECK(file.get() != nullptr); 728 ImageHeader hdr; 729 if (sizeof(hdr) != file->Read(reinterpret_cast<char*>(&hdr), sizeof(hdr), 0)) { 730 *error_msg = "Failed to read file %s"; 731 return false; 732 } 733 if (!hdr.IsValid()) { 734 *error_msg = "%s does not contain a valid image header."; 735 return false; 736 } 737 *delta = hdr.GetPatchDelta(); 738 return true; 739} 740 741static File* CreateOrOpen(const char* name, bool* created) { 742 if (OS::FileExists(name)) { 743 *created = false; 744 return OS::OpenFileReadWrite(name); 745 } else { 746 *created = true; 747 std::unique_ptr<File> f(OS::CreateEmptyFile(name)); 748 if (f.get() != nullptr) { 749 if (fchmod(f->Fd(), 0644) != 0) { 750 PLOG(ERROR) << "Unable to make " << name << " world readable"; 751 TEMP_FAILURE_RETRY(unlink(name)); 752 return nullptr; 753 } 754 } 755 return f.release(); 756 } 757} 758 759static int patchoat(int argc, char **argv) { 760 InitLogging(argv); 761 MemMap::Init(); 762 const bool debug = kIsDebugBuild; 763 orig_argc = argc; 764 orig_argv = argv; 765 TimingLogger timings("patcher", false, false); 766 767 InitLogging(argv); 768 769 // Skip over the command name. 770 argv++; 771 argc--; 772 773 if (argc == 0) { 774 Usage("No arguments specified"); 775 } 776 777 timings.StartTiming("Patchoat"); 778 779 // cmd line args 780 bool isa_set = false; 781 InstructionSet isa = kNone; 782 std::string input_oat_filename; 783 std::string input_oat_location; 784 int input_oat_fd = -1; 785 bool have_input_oat = false; 786 std::string input_image_location; 787 std::string output_oat_filename; 788 int output_oat_fd = -1; 789 bool have_output_oat = false; 790 std::string output_image_filename; 791 int output_image_fd = -1; 792 bool have_output_image = false; 793 uintptr_t base_offset = 0; 794 bool base_offset_set = false; 795 uintptr_t orig_base_offset = 0; 796 bool orig_base_offset_set = false; 797 off_t base_delta = 0; 798 bool base_delta_set = false; 799 std::string patched_image_filename; 800 std::string patched_image_location; 801 bool dump_timings = kIsDebugBuild; 802 bool lock_output = true; 803 804 for (int i = 0; i < argc; ++i) { 805 const StringPiece option(argv[i]); 806 const bool log_options = false; 807 if (log_options) { 808 LOG(INFO) << "patchoat: option[" << i << "]=" << argv[i]; 809 } 810 if (option.starts_with("--instruction-set=")) { 811 isa_set = true; 812 const char* isa_str = option.substr(strlen("--instruction-set=")).data(); 813 isa = GetInstructionSetFromString(isa_str); 814 if (isa == kNone) { 815 Usage("Unknown or invalid instruction set %s", isa_str); 816 } 817 } else if (option.starts_with("--input-oat-location=")) { 818 if (have_input_oat) { 819 Usage("Only one of --input-oat-file, --input-oat-location and --input-oat-fd may be used."); 820 } 821 have_input_oat = true; 822 input_oat_location = option.substr(strlen("--input-oat-location=")).data(); 823 } else if (option.starts_with("--input-oat-file=")) { 824 if (have_input_oat) { 825 Usage("Only one of --input-oat-file, --input-oat-location and --input-oat-fd may be used."); 826 } 827 have_input_oat = true; 828 input_oat_filename = option.substr(strlen("--input-oat-file=")).data(); 829 } else if (option.starts_with("--input-oat-fd=")) { 830 if (have_input_oat) { 831 Usage("Only one of --input-oat-file, --input-oat-location and --input-oat-fd may be used."); 832 } 833 have_input_oat = true; 834 const char* oat_fd_str = option.substr(strlen("--input-oat-fd=")).data(); 835 if (!ParseInt(oat_fd_str, &input_oat_fd)) { 836 Usage("Failed to parse --input-oat-fd argument '%s' as an integer", oat_fd_str); 837 } 838 if (input_oat_fd < 0) { 839 Usage("--input-oat-fd pass a negative value %d", input_oat_fd); 840 } 841 } else if (option.starts_with("--input-image-location=")) { 842 input_image_location = option.substr(strlen("--input-image-location=")).data(); 843 } else if (option.starts_with("--output-oat-file=")) { 844 if (have_output_oat) { 845 Usage("Only one of --output-oat-file, and --output-oat-fd may be used."); 846 } 847 have_output_oat = true; 848 output_oat_filename = option.substr(strlen("--output-oat-file=")).data(); 849 } else if (option.starts_with("--output-oat-fd=")) { 850 if (have_output_oat) { 851 Usage("Only one of --output-oat-file, --output-oat-fd may be used."); 852 } 853 have_output_oat = true; 854 const char* oat_fd_str = option.substr(strlen("--output-oat-fd=")).data(); 855 if (!ParseInt(oat_fd_str, &output_oat_fd)) { 856 Usage("Failed to parse --output-oat-fd argument '%s' as an integer", oat_fd_str); 857 } 858 if (output_oat_fd < 0) { 859 Usage("--output-oat-fd pass a negative value %d", output_oat_fd); 860 } 861 } else if (option.starts_with("--output-image-file=")) { 862 if (have_output_image) { 863 Usage("Only one of --output-image-file, and --output-image-fd may be used."); 864 } 865 have_output_image = true; 866 output_image_filename = option.substr(strlen("--output-image-file=")).data(); 867 } else if (option.starts_with("--output-image-fd=")) { 868 if (have_output_image) { 869 Usage("Only one of --output-image-file, and --output-image-fd may be used."); 870 } 871 have_output_image = true; 872 const char* image_fd_str = option.substr(strlen("--output-image-fd=")).data(); 873 if (!ParseInt(image_fd_str, &output_image_fd)) { 874 Usage("Failed to parse --output-image-fd argument '%s' as an integer", image_fd_str); 875 } 876 if (output_image_fd < 0) { 877 Usage("--output-image-fd pass a negative value %d", output_image_fd); 878 } 879 } else if (option.starts_with("--orig-base-offset=")) { 880 const char* orig_base_offset_str = option.substr(strlen("--orig-base-offset=")).data(); 881 orig_base_offset_set = true; 882 if (!ParseUint(orig_base_offset_str, &orig_base_offset)) { 883 Usage("Failed to parse --orig-base-offset argument '%s' as an uintptr_t", 884 orig_base_offset_str); 885 } 886 } else if (option.starts_with("--base-offset=")) { 887 const char* base_offset_str = option.substr(strlen("--base-offset=")).data(); 888 base_offset_set = true; 889 if (!ParseUint(base_offset_str, &base_offset)) { 890 Usage("Failed to parse --base-offset argument '%s' as an uintptr_t", base_offset_str); 891 } 892 } else if (option.starts_with("--base-offset-delta=")) { 893 const char* base_delta_str = option.substr(strlen("--base-offset-delta=")).data(); 894 base_delta_set = true; 895 if (!ParseInt(base_delta_str, &base_delta)) { 896 Usage("Failed to parse --base-offset-delta argument '%s' as an off_t", base_delta_str); 897 } 898 } else if (option.starts_with("--patched-image-location=")) { 899 patched_image_location = option.substr(strlen("--patched-image-location=")).data(); 900 } else if (option.starts_with("--patched-image-file=")) { 901 patched_image_filename = option.substr(strlen("--patched-image-file=")).data(); 902 } else if (option == "--lock-output") { 903 lock_output = true; 904 } else if (option == "--no-lock-output") { 905 lock_output = false; 906 } else if (option == "--dump-timings") { 907 dump_timings = true; 908 } else if (option == "--no-dump-timings") { 909 dump_timings = false; 910 } else { 911 Usage("Unknown argument %s", option.data()); 912 } 913 } 914 915 { 916 // Only 1 of these may be set. 917 uint32_t cnt = 0; 918 cnt += (base_delta_set) ? 1 : 0; 919 cnt += (base_offset_set && orig_base_offset_set) ? 1 : 0; 920 cnt += (!patched_image_filename.empty()) ? 1 : 0; 921 cnt += (!patched_image_location.empty()) ? 1 : 0; 922 if (cnt > 1) { 923 Usage("Only one of --base-offset/--orig-base-offset, --base-offset-delta, " 924 "--patched-image-filename or --patched-image-location may be used."); 925 } else if (cnt == 0) { 926 Usage("Must specify --base-offset-delta, --base-offset and --orig-base-offset, " 927 "--patched-image-location or --patched-image-file"); 928 } 929 } 930 931 if (have_input_oat != have_output_oat) { 932 Usage("Either both input and output oat must be supplied or niether must be."); 933 } 934 935 if ((!input_image_location.empty()) != have_output_image) { 936 Usage("Either both input and output image must be supplied or niether must be."); 937 } 938 939 // We know we have both the input and output so rename for clarity. 940 bool have_image_files = have_output_image; 941 bool have_oat_files = have_output_oat; 942 943 if (!have_oat_files && !have_image_files) { 944 Usage("Must be patching either an oat or an image file or both."); 945 } 946 947 if (!have_oat_files && !isa_set) { 948 Usage("Must include ISA if patching an image file without an oat file."); 949 } 950 951 if (!input_oat_location.empty()) { 952 if (!isa_set) { 953 Usage("specifying a location requires specifying an instruction set"); 954 } 955 if (!LocationToFilename(input_oat_location, isa, &input_oat_filename)) { 956 Usage("Unable to find filename for input oat location %s", input_oat_location.c_str()); 957 } 958 if (debug) { 959 LOG(INFO) << "Using input-oat-file " << input_oat_filename; 960 } 961 } 962 if (!patched_image_location.empty()) { 963 if (!isa_set) { 964 Usage("specifying a location requires specifying an instruction set"); 965 } 966 std::string system_filename; 967 bool has_system = false; 968 std::string cache_filename; 969 bool has_cache = false; 970 bool has_android_data_unused = false; 971 bool is_global_cache = false; 972 if (!gc::space::ImageSpace::FindImageFilename(patched_image_location.c_str(), isa, 973 &system_filename, &has_system, &cache_filename, 974 &has_android_data_unused, &has_cache, 975 &is_global_cache)) { 976 Usage("Unable to determine image file for location %s", patched_image_location.c_str()); 977 } 978 if (has_cache) { 979 patched_image_filename = cache_filename; 980 } else if (has_system) { 981 LOG(WARNING) << "Only image file found was in /system for image location " 982 << patched_image_location; 983 patched_image_filename = system_filename; 984 } else { 985 Usage("Unable to determine image file for location %s", patched_image_location.c_str()); 986 } 987 if (debug) { 988 LOG(INFO) << "Using patched-image-file " << patched_image_filename; 989 } 990 } 991 992 if (!base_delta_set) { 993 if (orig_base_offset_set && base_offset_set) { 994 base_delta_set = true; 995 base_delta = base_offset - orig_base_offset; 996 } else if (!patched_image_filename.empty()) { 997 base_delta_set = true; 998 std::string error_msg; 999 if (!ReadBaseDelta(patched_image_filename.c_str(), &base_delta, &error_msg)) { 1000 Usage(error_msg.c_str(), patched_image_filename.c_str()); 1001 } 1002 } else { 1003 if (base_offset_set) { 1004 Usage("Unable to determine original base offset."); 1005 } else { 1006 Usage("Must supply a desired new offset or delta."); 1007 } 1008 } 1009 } 1010 1011 if (!IsAligned<kPageSize>(base_delta)) { 1012 Usage("Base offset/delta must be alligned to a pagesize (0x%08x) boundary.", kPageSize); 1013 } 1014 1015 // Do we need to cleanup output files if we fail? 1016 bool new_image_out = false; 1017 bool new_oat_out = false; 1018 1019 std::unique_ptr<File> input_oat; 1020 std::unique_ptr<File> output_oat; 1021 std::unique_ptr<File> output_image; 1022 1023 if (have_image_files) { 1024 CHECK(!input_image_location.empty()); 1025 1026 if (output_image_fd != -1) { 1027 if (output_image_filename.empty()) { 1028 output_image_filename = "output-image-file"; 1029 } 1030 output_image.reset(new File(output_image_fd, output_image_filename)); 1031 } else { 1032 CHECK(!output_image_filename.empty()); 1033 output_image.reset(CreateOrOpen(output_image_filename.c_str(), &new_image_out)); 1034 } 1035 } else { 1036 CHECK(output_image_filename.empty() && output_image_fd == -1 && input_image_location.empty()); 1037 } 1038 1039 if (have_oat_files) { 1040 if (input_oat_fd != -1) { 1041 if (input_oat_filename.empty()) { 1042 input_oat_filename = "input-oat-file"; 1043 } 1044 input_oat.reset(new File(input_oat_fd, input_oat_filename)); 1045 } else { 1046 CHECK(!input_oat_filename.empty()); 1047 input_oat.reset(OS::OpenFileForReading(input_oat_filename.c_str())); 1048 if (input_oat.get() == nullptr) { 1049 LOG(ERROR) << "Could not open input oat file: " << strerror(errno); 1050 } 1051 } 1052 1053 if (output_oat_fd != -1) { 1054 if (output_oat_filename.empty()) { 1055 output_oat_filename = "output-oat-file"; 1056 } 1057 output_oat.reset(new File(output_oat_fd, output_oat_filename)); 1058 } else { 1059 CHECK(!output_oat_filename.empty()); 1060 output_oat.reset(CreateOrOpen(output_oat_filename.c_str(), &new_oat_out)); 1061 } 1062 } 1063 1064 auto cleanup = [&output_image_filename, &output_oat_filename, 1065 &new_oat_out, &new_image_out, &timings, &dump_timings](bool success) { 1066 timings.EndTiming(); 1067 if (!success) { 1068 if (new_oat_out) { 1069 CHECK(!output_oat_filename.empty()); 1070 TEMP_FAILURE_RETRY(unlink(output_oat_filename.c_str())); 1071 } 1072 if (new_image_out) { 1073 CHECK(!output_image_filename.empty()); 1074 TEMP_FAILURE_RETRY(unlink(output_image_filename.c_str())); 1075 } 1076 } 1077 if (dump_timings) { 1078 LOG(INFO) << Dumpable<TimingLogger>(timings); 1079 } 1080 }; 1081 1082 if ((have_oat_files && (input_oat.get() == nullptr || output_oat.get() == nullptr)) || 1083 (have_image_files && output_image.get() == nullptr)) { 1084 cleanup(false); 1085 return EXIT_FAILURE; 1086 } 1087 1088 ScopedFlock output_oat_lock; 1089 if (lock_output) { 1090 std::string error_msg; 1091 if (have_oat_files && !output_oat_lock.Init(output_oat.get(), &error_msg)) { 1092 LOG(ERROR) << "Unable to lock output oat " << output_image->GetPath() << ": " << error_msg; 1093 cleanup(false); 1094 return EXIT_FAILURE; 1095 } 1096 } 1097 1098 if (debug) { 1099 LOG(INFO) << "moving offset by " << base_delta 1100 << " (0x" << std::hex << base_delta << ") bytes or " 1101 << std::dec << (base_delta/kPageSize) << " pages."; 1102 } 1103 1104 bool ret; 1105 if (have_image_files && have_oat_files) { 1106 TimingLogger::ScopedTiming pt("patch image and oat", &timings); 1107 ret = PatchOat::Patch(input_oat.get(), input_image_location, base_delta, 1108 output_oat.get(), output_image.get(), isa, &timings); 1109 } else if (have_oat_files) { 1110 TimingLogger::ScopedTiming pt("patch oat", &timings); 1111 ret = PatchOat::Patch(input_oat.get(), base_delta, output_oat.get(), &timings); 1112 } else { 1113 TimingLogger::ScopedTiming pt("patch image", &timings); 1114 CHECK(have_image_files); 1115 ret = PatchOat::Patch(input_image_location, base_delta, output_image.get(), isa, &timings); 1116 } 1117 cleanup(ret); 1118 return (ret) ? EXIT_SUCCESS : EXIT_FAILURE; 1119} 1120 1121} // namespace art 1122 1123int main(int argc, char **argv) { 1124 return art::patchoat(argc, argv); 1125} 1126