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