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