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