patchoat.cc revision 54d220eb9cc51215d75b9e0fe921b94bebbb3fd6
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 "art_field-inl.h"
28#include "art_method-inl.h"
29#include "base/dumpable.h"
30#include "base/scoped_flock.h"
31#include "base/stringpiece.h"
32#include "base/stringprintf.h"
33#include "base/unix_file/fd_file.h"
34#include "elf_utils.h"
35#include "elf_file.h"
36#include "elf_file_impl.h"
37#include "gc/space/image_space.h"
38#include "image.h"
39#include "mirror/abstract_method.h"
40#include "mirror/object-inl.h"
41#include "mirror/method.h"
42#include "mirror/reference.h"
43#include "noop_compiler_callbacks.h"
44#include "offsets.h"
45#include "os.h"
46#include "runtime.h"
47#include "scoped_thread_state_change.h"
48#include "thread.h"
49#include "utils.h"
50
51namespace art {
52
53static bool LocationToFilename(const std::string& location, InstructionSet isa,
54                               std::string* filename) {
55  bool has_system = false;
56  bool has_cache = false;
57  // image_location = /system/framework/boot.art
58  // system_image_filename = /system/framework/<image_isa>/boot.art
59  std::string system_filename(GetSystemImageFilename(location.c_str(), isa));
60  if (OS::FileExists(system_filename.c_str())) {
61    has_system = true;
62  }
63
64  bool have_android_data = false;
65  bool dalvik_cache_exists = false;
66  bool is_global_cache = false;
67  std::string dalvik_cache;
68  GetDalvikCache(GetInstructionSetString(isa), false, &dalvik_cache,
69                 &have_android_data, &dalvik_cache_exists, &is_global_cache);
70
71  std::string cache_filename;
72  if (have_android_data && dalvik_cache_exists) {
73    // Always set output location even if it does not exist,
74    // so that the caller knows where to create the image.
75    //
76    // image_location = /system/framework/boot.art
77    // *image_filename = /data/dalvik-cache/<image_isa>/boot.art
78    std::string error_msg;
79    if (GetDalvikCacheFilename(location.c_str(), dalvik_cache.c_str(),
80                               &cache_filename, &error_msg)) {
81      has_cache = true;
82    }
83  }
84  if (has_system) {
85    *filename = system_filename;
86    return true;
87  } else if (has_cache) {
88    *filename = cache_filename;
89    return true;
90  } else {
91    return false;
92  }
93}
94
95bool PatchOat::Patch(const std::string& image_location, off_t delta,
96                     File* output_image, InstructionSet isa,
97                     TimingLogger* timings) {
98  CHECK(Runtime::Current() == nullptr);
99  CHECK(output_image != nullptr);
100  CHECK_GE(output_image->Fd(), 0);
101  CHECK(!image_location.empty()) << "image file must have a filename.";
102  CHECK_NE(isa, kNone);
103
104  TimingLogger::ScopedTiming t("Runtime Setup", timings);
105  const char *isa_name = GetInstructionSetString(isa);
106  std::string image_filename;
107  if (!LocationToFilename(image_location, isa, &image_filename)) {
108    LOG(ERROR) << "Unable to find image at location " << image_location;
109    return false;
110  }
111  std::unique_ptr<File> input_image(OS::OpenFileForReading(image_filename.c_str()));
112  if (input_image.get() == nullptr) {
113    LOG(ERROR) << "unable to open input image file at " << image_filename
114               << " for location " << image_location;
115    return false;
116  }
117
118  int64_t image_len = input_image->GetLength();
119  if (image_len < 0) {
120    LOG(ERROR) << "Error while getting image length";
121    return false;
122  }
123  ImageHeader image_header;
124  if (sizeof(image_header) != input_image->Read(reinterpret_cast<char*>(&image_header),
125                                                sizeof(image_header), 0)) {
126    LOG(ERROR) << "Unable to read image header from image file " << input_image->GetPath();
127    return false;
128  }
129
130  /*bool is_image_pic = */IsImagePic(image_header, input_image->GetPath());
131  // Nothing special to do right now since the image always needs to get patched.
132  // Perhaps in some far-off future we may have images with relative addresses that are true-PIC.
133
134  // Set up the runtime
135  RuntimeOptions options;
136  NoopCompilerCallbacks callbacks;
137  options.push_back(std::make_pair("compilercallbacks", &callbacks));
138  std::string img = "-Ximage:" + image_location;
139  options.push_back(std::make_pair(img.c_str(), nullptr));
140  options.push_back(std::make_pair("imageinstructionset", reinterpret_cast<const void*>(isa_name)));
141  options.push_back(std::make_pair("-Xno-sig-chain", nullptr));
142  if (!Runtime::Create(options, false)) {
143    LOG(ERROR) << "Unable to initialize runtime";
144    return false;
145  }
146  // Runtime::Create acquired the mutator_lock_ that is normally given away when we Runtime::Start,
147  // give it away now and then switch to a more manageable ScopedObjectAccess.
148  Thread::Current()->TransitionFromRunnableToSuspended(kNative);
149  ScopedObjectAccess soa(Thread::Current());
150
151  t.NewTiming("Image and oat Patching setup");
152  // Create the map where we will write the image patches to.
153  std::string error_msg;
154  std::unique_ptr<MemMap> image(MemMap::MapFile(image_len, PROT_READ | PROT_WRITE, MAP_PRIVATE,
155                                                input_image->Fd(), 0,
156                                                input_image->GetPath().c_str(),
157                                                &error_msg));
158  if (image.get() == nullptr) {
159    LOG(ERROR) << "unable to map image file " << input_image->GetPath() << " : " << error_msg;
160    return false;
161  }
162  gc::space::ImageSpace* ispc = Runtime::Current()->GetHeap()->GetImageSpace();
163
164  PatchOat p(isa, image.release(), ispc->GetLiveBitmap(), ispc->GetMemMap(),
165             delta, timings);
166  t.NewTiming("Patching files");
167  if (!p.PatchImage()) {
168    LOG(ERROR) << "Failed to patch image file " << input_image->GetPath();
169    return false;
170  }
171
172  t.NewTiming("Writing files");
173  if (!p.WriteImage(output_image)) {
174    return false;
175  }
176  return true;
177}
178
179bool PatchOat::Patch(File* input_oat, const std::string& image_location, off_t delta,
180                     File* output_oat, File* output_image, InstructionSet isa,
181                     TimingLogger* timings,
182                     bool output_oat_opened_from_fd,
183                     bool new_oat_out) {
184  CHECK(Runtime::Current() == nullptr);
185  CHECK(output_image != nullptr);
186  CHECK_GE(output_image->Fd(), 0);
187  CHECK(input_oat != nullptr);
188  CHECK(output_oat != nullptr);
189  CHECK_GE(input_oat->Fd(), 0);
190  CHECK_GE(output_oat->Fd(), 0);
191  CHECK(!image_location.empty()) << "image file must have a filename.";
192
193  TimingLogger::ScopedTiming t("Runtime Setup", timings);
194
195  if (isa == kNone) {
196    Elf32_Ehdr elf_hdr;
197    if (sizeof(elf_hdr) != input_oat->Read(reinterpret_cast<char*>(&elf_hdr), sizeof(elf_hdr), 0)) {
198      LOG(ERROR) << "unable to read elf header";
199      return false;
200    }
201    isa = GetInstructionSetFromELF(elf_hdr.e_machine, elf_hdr.e_flags);
202  }
203  const char* isa_name = GetInstructionSetString(isa);
204  std::string image_filename;
205  if (!LocationToFilename(image_location, isa, &image_filename)) {
206    LOG(ERROR) << "Unable to find image at location " << image_location;
207    return false;
208  }
209  std::unique_ptr<File> input_image(OS::OpenFileForReading(image_filename.c_str()));
210  if (input_image.get() == nullptr) {
211    LOG(ERROR) << "unable to open input image file at " << image_filename
212               << " for location " << image_location;
213    return false;
214  }
215  int64_t image_len = input_image->GetLength();
216  if (image_len < 0) {
217    LOG(ERROR) << "Error while getting image length";
218    return false;
219  }
220  ImageHeader image_header;
221  if (sizeof(image_header) != input_image->Read(reinterpret_cast<char*>(&image_header),
222                                              sizeof(image_header), 0)) {
223    LOG(ERROR) << "Unable to read image header from image file " << input_image->GetPath();
224  }
225
226  /*bool is_image_pic = */IsImagePic(image_header, input_image->GetPath());
227  // Nothing special to do right now since the image always needs to get patched.
228  // Perhaps in some far-off future we may have images with relative addresses that are true-PIC.
229
230  // Set up the runtime
231  RuntimeOptions options;
232  NoopCompilerCallbacks callbacks;
233  options.push_back(std::make_pair("compilercallbacks", &callbacks));
234  std::string img = "-Ximage:" + image_location;
235  options.push_back(std::make_pair(img.c_str(), nullptr));
236  options.push_back(std::make_pair("imageinstructionset", reinterpret_cast<const void*>(isa_name)));
237  options.push_back(std::make_pair("-Xno-sig-chain", nullptr));
238  if (!Runtime::Create(options, false)) {
239    LOG(ERROR) << "Unable to initialize runtime";
240    return false;
241  }
242  // Runtime::Create acquired the mutator_lock_ that is normally given away when we Runtime::Start,
243  // give it away now and then switch to a more manageable ScopedObjectAccess.
244  Thread::Current()->TransitionFromRunnableToSuspended(kNative);
245  ScopedObjectAccess soa(Thread::Current());
246
247  t.NewTiming("Image and oat Patching setup");
248  // Create the map where we will write the image patches to.
249  std::string error_msg;
250  std::unique_ptr<MemMap> image(MemMap::MapFile(image_len, PROT_READ | PROT_WRITE, MAP_PRIVATE,
251                                                input_image->Fd(), 0,
252                                                input_image->GetPath().c_str(),
253                                                &error_msg));
254  if (image.get() == nullptr) {
255    LOG(ERROR) << "unable to map image file " << input_image->GetPath() << " : " << error_msg;
256    return false;
257  }
258  gc::space::ImageSpace* ispc = Runtime::Current()->GetHeap()->GetImageSpace();
259
260  std::unique_ptr<ElfFile> elf(ElfFile::Open(input_oat,
261                                             PROT_READ | PROT_WRITE, MAP_PRIVATE, &error_msg));
262  if (elf.get() == nullptr) {
263    LOG(ERROR) << "unable to open oat file " << input_oat->GetPath() << " : " << error_msg;
264    return false;
265  }
266
267  bool skip_patching_oat = false;
268  MaybePic is_oat_pic = IsOatPic(elf.get());
269  if (is_oat_pic >= ERROR_FIRST) {
270    // Error logged by IsOatPic
271    return false;
272  } else if (is_oat_pic == PIC) {
273    // Do not need to do ELF-file patching. Create a symlink and skip the ELF patching.
274    if (!ReplaceOatFileWithSymlink(input_oat->GetPath(),
275                                   output_oat->GetPath(),
276                                   output_oat_opened_from_fd,
277                                   new_oat_out)) {
278      // Errors already logged by above call.
279      return false;
280    }
281    // Don't patch the OAT, since we just symlinked it. Image still needs patching.
282    skip_patching_oat = true;
283  } else {
284    CHECK(is_oat_pic == NOT_PIC);
285  }
286
287  PatchOat p(isa, elf.release(), image.release(), ispc->GetLiveBitmap(), ispc->GetMemMap(),
288             delta, timings);
289  t.NewTiming("Patching files");
290  if (!skip_patching_oat && !p.PatchElf()) {
291    LOG(ERROR) << "Failed to patch oat file " << input_oat->GetPath();
292    return false;
293  }
294  if (!p.PatchImage()) {
295    LOG(ERROR) << "Failed to patch image file " << input_image->GetPath();
296    return false;
297  }
298
299  t.NewTiming("Writing files");
300  if (!skip_patching_oat && !p.WriteElf(output_oat)) {
301    LOG(ERROR) << "Failed to write oat file " << input_oat->GetPath();
302    return false;
303  }
304  if (!p.WriteImage(output_image)) {
305    LOG(ERROR) << "Failed to write image file " << input_image->GetPath();
306    return false;
307  }
308  return true;
309}
310
311bool PatchOat::WriteElf(File* out) {
312  TimingLogger::ScopedTiming t("Writing Elf File", timings_);
313
314  CHECK(oat_file_.get() != nullptr);
315  CHECK(out != nullptr);
316  size_t expect = oat_file_->Size();
317  if (out->WriteFully(reinterpret_cast<char*>(oat_file_->Begin()), expect) &&
318      out->SetLength(expect) == 0) {
319    return true;
320  } else {
321    LOG(ERROR) << "Writing to oat file " << out->GetPath() << " failed.";
322    return false;
323  }
324}
325
326bool PatchOat::WriteImage(File* out) {
327  TimingLogger::ScopedTiming t("Writing image File", timings_);
328  std::string error_msg;
329
330  ScopedFlock img_flock;
331  img_flock.Init(out, &error_msg);
332
333  CHECK(image_ != nullptr);
334  CHECK(out != nullptr);
335  size_t expect = image_->Size();
336  if (out->WriteFully(reinterpret_cast<char*>(image_->Begin()), expect) &&
337      out->SetLength(expect) == 0) {
338    return true;
339  } else {
340    LOG(ERROR) << "Writing to image file " << out->GetPath() << " failed.";
341    return false;
342  }
343}
344
345bool PatchOat::IsImagePic(const ImageHeader& image_header, const std::string& image_path) {
346  if (!image_header.CompilePic()) {
347    if (kIsDebugBuild) {
348      LOG(INFO) << "image at location " << image_path << " was *not* compiled pic";
349    }
350    return false;
351  }
352
353  if (kIsDebugBuild) {
354    LOG(INFO) << "image at location " << image_path << " was compiled PIC";
355  }
356
357  return true;
358}
359
360PatchOat::MaybePic PatchOat::IsOatPic(const ElfFile* oat_in) {
361  if (oat_in == nullptr) {
362    LOG(ERROR) << "No ELF input oat fie available";
363    return ERROR_OAT_FILE;
364  }
365
366  const std::string& file_path = oat_in->GetFile().GetPath();
367
368  const OatHeader* oat_header = GetOatHeader(oat_in);
369  if (oat_header == nullptr) {
370    LOG(ERROR) << "Failed to find oat header in oat file " << file_path;
371    return ERROR_OAT_FILE;
372  }
373
374  if (!oat_header->IsValid()) {
375    LOG(ERROR) << "Elf file " << file_path << " has an invalid oat header";
376    return ERROR_OAT_FILE;
377  }
378
379  bool is_pic = oat_header->IsPic();
380  if (kIsDebugBuild) {
381    LOG(INFO) << "Oat file at " << file_path << " is " << (is_pic ? "PIC" : "not pic");
382  }
383
384  return is_pic ? PIC : NOT_PIC;
385}
386
387bool PatchOat::ReplaceOatFileWithSymlink(const std::string& input_oat_filename,
388                                         const std::string& output_oat_filename,
389                                         bool output_oat_opened_from_fd,
390                                         bool new_oat_out) {
391  // Need a file when we are PIC, since we symlink over it. Refusing to symlink into FD.
392  if (output_oat_opened_from_fd) {
393    // TODO: installd uses --output-oat-fd. Should we change class linking logic for PIC?
394    LOG(ERROR) << "No output oat filename specified, needs filename for when we are PIC";
395    return false;
396  }
397
398  // Image was PIC. Create symlink where the oat is supposed to go.
399  if (!new_oat_out) {
400    LOG(ERROR) << "Oat file " << output_oat_filename << " already exists, refusing to overwrite";
401    return false;
402  }
403
404  // Delete the original file, since we won't need it.
405  TEMP_FAILURE_RETRY(unlink(output_oat_filename.c_str()));
406
407  // Create a symlink from the old oat to the new oat
408  if (symlink(input_oat_filename.c_str(), output_oat_filename.c_str()) < 0) {
409    int err = errno;
410    LOG(ERROR) << "Failed to create symlink at " << output_oat_filename
411               << " error(" << err << "): " << strerror(err);
412    return false;
413  }
414
415  if (kIsDebugBuild) {
416    LOG(INFO) << "Created symlink " << output_oat_filename << " -> " << input_oat_filename;
417  }
418
419  return true;
420}
421
422class PatchOatArtFieldVisitor : public ArtFieldVisitor {
423 public:
424  explicit PatchOatArtFieldVisitor(PatchOat* patch_oat) : patch_oat_(patch_oat) {}
425
426  void Visit(ArtField* field) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
427    ArtField* const dest = patch_oat_->RelocatedCopyOf(field);
428    dest->SetDeclaringClass(patch_oat_->RelocatedAddressOfPointer(field->GetDeclaringClass()));
429  }
430
431 private:
432  PatchOat* const patch_oat_;
433};
434
435void PatchOat::PatchArtFields(const ImageHeader* image_header) {
436  PatchOatArtFieldVisitor visitor(this);
437  const auto& section = image_header->GetImageSection(ImageHeader::kSectionArtFields);
438  section.VisitPackedArtFields(&visitor, heap_->Begin());
439}
440
441class PatchOatArtMethodVisitor : public ArtMethodVisitor {
442 public:
443  explicit PatchOatArtMethodVisitor(PatchOat* patch_oat) : patch_oat_(patch_oat) {}
444
445  void Visit(ArtMethod* method) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
446    ArtMethod* const dest = patch_oat_->RelocatedCopyOf(method);
447    patch_oat_->FixupMethod(method, dest);
448  }
449
450 private:
451  PatchOat* const patch_oat_;
452};
453
454void PatchOat::PatchArtMethods(const ImageHeader* image_header) {
455  const auto& section = image_header->GetMethodsSection();
456  const size_t pointer_size = InstructionSetPointerSize(isa_);
457  const size_t method_size = ArtMethod::ObjectSize(pointer_size);
458  PatchOatArtMethodVisitor visitor(this);
459  section.VisitPackedArtMethods(&visitor, heap_->Begin(), method_size);
460}
461
462class FixupRootVisitor : public RootVisitor {
463 public:
464  explicit FixupRootVisitor(const PatchOat* patch_oat) : patch_oat_(patch_oat) {
465  }
466
467  void VisitRoots(mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED)
468      OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
469    for (size_t i = 0; i < count; ++i) {
470      *roots[i] = patch_oat_->RelocatedAddressOfPointer(*roots[i]);
471    }
472  }
473
474  void VisitRoots(mirror::CompressedReference<mirror::Object>** roots, size_t count,
475                  const RootInfo& info ATTRIBUTE_UNUSED)
476      OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
477    for (size_t i = 0; i < count; ++i) {
478      roots[i]->Assign(patch_oat_->RelocatedAddressOfPointer(roots[i]->AsMirrorPtr()));
479    }
480  }
481
482 private:
483  const PatchOat* const patch_oat_;
484};
485
486void PatchOat::PatchInternedStrings(const ImageHeader* image_header) {
487  const auto& section = image_header->GetImageSection(ImageHeader::kSectionInternedStrings);
488  InternTable temp_table;
489  // Note that we require that ReadFromMemory does not make an internal copy of the elements.
490  // This also relies on visit roots not doing any verification which could fail after we update
491  // the roots to be the image addresses.
492  temp_table.ReadFromMemory(image_->Begin() + section.Offset());
493  FixupRootVisitor visitor(this);
494  temp_table.VisitRoots(&visitor, kVisitRootFlagAllRoots);
495}
496
497void PatchOat::PatchDexFileArrays(mirror::ObjectArray<mirror::Object>* img_roots) {
498  auto* dex_caches = down_cast<mirror::ObjectArray<mirror::DexCache>*>(
499      img_roots->Get(ImageHeader::kDexCaches));
500  for (size_t i = 0, count = dex_caches->GetLength(); i < count; ++i) {
501    auto* dex_cache = dex_caches->GetWithoutChecks(i);
502    auto* fields = dex_cache->GetResolvedFields();
503    if (fields != nullptr) {
504      CHECK(!fields->IsObjectArray());
505      CHECK(fields->IsArrayInstance());
506      FixupNativePointerArray(fields);
507    }
508    auto* methods = dex_cache->GetResolvedMethods();
509    if (methods != nullptr) {
510      CHECK(!methods->IsObjectArray());
511      CHECK(methods->IsArrayInstance());
512      FixupNativePointerArray(methods);
513    }
514  }
515}
516
517void PatchOat::FixupNativePointerArray(mirror::PointerArray* object) {
518  if (object->IsIntArray()) {
519    mirror::IntArray* arr = object->AsIntArray();
520    mirror::IntArray* copy_arr = down_cast<mirror::IntArray*>(RelocatedCopyOf(arr));
521    for (size_t j = 0, count2 = arr->GetLength(); j < count2; ++j) {
522      copy_arr->SetWithoutChecks<false>(
523          j, RelocatedAddressOfIntPointer(arr->GetWithoutChecks(j)));
524    }
525  } else {
526    CHECK(object->IsLongArray());
527    mirror::LongArray* arr = object->AsLongArray();
528    mirror::LongArray* copy_arr = down_cast<mirror::LongArray*>(RelocatedCopyOf(arr));
529    for (size_t j = 0, count2 = arr->GetLength(); j < count2; ++j) {
530      copy_arr->SetWithoutChecks<false>(
531          j, RelocatedAddressOfIntPointer(arr->GetWithoutChecks(j)));
532    }
533  }
534}
535
536bool PatchOat::PatchImage() {
537  ImageHeader* image_header = reinterpret_cast<ImageHeader*>(image_->Begin());
538  CHECK_GT(image_->Size(), sizeof(ImageHeader));
539  // These are the roots from the original file.
540  auto* img_roots = image_header->GetImageRoots();
541  image_header->RelocateImage(delta_);
542
543  PatchArtFields(image_header);
544  PatchArtMethods(image_header);
545  PatchInternedStrings(image_header);
546  // Patch dex file int/long arrays which point to ArtFields.
547  PatchDexFileArrays(img_roots);
548
549  VisitObject(img_roots);
550  if (!image_header->IsValid()) {
551    LOG(ERROR) << "reloction renders image header invalid";
552    return false;
553  }
554
555  {
556    TimingLogger::ScopedTiming t("Walk Bitmap", timings_);
557    // Walk the bitmap.
558    WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
559    bitmap_->Walk(PatchOat::BitmapCallback, this);
560  }
561  return true;
562}
563
564bool PatchOat::InHeap(mirror::Object* o) {
565  uintptr_t begin = reinterpret_cast<uintptr_t>(heap_->Begin());
566  uintptr_t end = reinterpret_cast<uintptr_t>(heap_->End());
567  uintptr_t obj = reinterpret_cast<uintptr_t>(o);
568  return o == nullptr || (begin <= obj && obj < end);
569}
570
571void PatchOat::PatchVisitor::operator() (mirror::Object* obj, MemberOffset off,
572                                         bool is_static_unused ATTRIBUTE_UNUSED) const {
573  mirror::Object* referent = obj->GetFieldObject<mirror::Object, kVerifyNone>(off);
574  DCHECK(patcher_->InHeap(referent)) << "Referent is not in the heap.";
575  mirror::Object* moved_object = patcher_->RelocatedAddressOfPointer(referent);
576  copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(off, moved_object);
577}
578
579void PatchOat::PatchVisitor::operator() (mirror::Class* cls ATTRIBUTE_UNUSED,
580                                         mirror::Reference* ref) const {
581  MemberOffset off = mirror::Reference::ReferentOffset();
582  mirror::Object* referent = ref->GetReferent();
583  DCHECK(patcher_->InHeap(referent)) << "Referent is not in the heap.";
584  mirror::Object* moved_object = patcher_->RelocatedAddressOfPointer(referent);
585  copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(off, moved_object);
586}
587
588const OatHeader* PatchOat::GetOatHeader(const ElfFile* elf_file) {
589  if (elf_file->Is64Bit()) {
590    return GetOatHeader<ElfFileImpl64>(elf_file->GetImpl64());
591  } else {
592    return GetOatHeader<ElfFileImpl32>(elf_file->GetImpl32());
593  }
594}
595
596template <typename ElfFileImpl>
597const OatHeader* PatchOat::GetOatHeader(const ElfFileImpl* elf_file) {
598  auto rodata_sec = elf_file->FindSectionByName(".rodata");
599  if (rodata_sec == nullptr) {
600    return nullptr;
601  }
602
603  OatHeader* oat_header = reinterpret_cast<OatHeader*>(elf_file->Begin() + rodata_sec->sh_offset);
604  return oat_header;
605}
606
607// Called by BitmapCallback
608void PatchOat::VisitObject(mirror::Object* object) {
609  mirror::Object* copy = RelocatedCopyOf(object);
610  CHECK(copy != nullptr);
611  if (kUseBakerOrBrooksReadBarrier) {
612    object->AssertReadBarrierPointer();
613    if (kUseBrooksReadBarrier) {
614      mirror::Object* moved_to = RelocatedAddressOfPointer(object);
615      copy->SetReadBarrierPointer(moved_to);
616      DCHECK_EQ(copy->GetReadBarrierPointer(), moved_to);
617    }
618  }
619  PatchOat::PatchVisitor visitor(this, copy);
620  object->VisitReferences<true, kVerifyNone>(visitor, visitor);
621  if (object->IsClass<kVerifyNone>()) {
622    auto* klass = object->AsClass();
623    auto* copy_klass = down_cast<mirror::Class*>(copy);
624    copy_klass->SetSFieldsPtrUnchecked(RelocatedAddressOfPointer(klass->GetSFieldsPtr()));
625    copy_klass->SetIFieldsPtrUnchecked(RelocatedAddressOfPointer(klass->GetIFieldsPtr()));
626    copy_klass->SetDirectMethodsPtrUnchecked(
627        RelocatedAddressOfPointer(klass->GetDirectMethodsPtr()));
628    copy_klass->SetVirtualMethodsPtr(RelocatedAddressOfPointer(klass->GetVirtualMethodsPtr()));
629    auto* vtable = klass->GetVTable();
630    if (vtable != nullptr) {
631      FixupNativePointerArray(vtable);
632    }
633    auto* iftable = klass->GetIfTable();
634    if (iftable != nullptr) {
635      for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
636        if (iftable->GetMethodArrayCount(i) > 0) {
637          auto* method_array = iftable->GetMethodArray(i);
638          CHECK(method_array != nullptr);
639          FixupNativePointerArray(method_array);
640        }
641      }
642    }
643    if (klass->ShouldHaveEmbeddedImtAndVTable()) {
644      const size_t pointer_size = InstructionSetPointerSize(isa_);
645      for (int32_t i = 0; i < klass->GetEmbeddedVTableLength(); ++i) {
646        copy_klass->SetEmbeddedVTableEntryUnchecked(i, RelocatedAddressOfPointer(
647            klass->GetEmbeddedVTableEntry(i, pointer_size)), pointer_size);
648      }
649      for (size_t i = 0; i < mirror::Class::kImtSize; ++i) {
650        copy_klass->SetEmbeddedImTableEntry(i, RelocatedAddressOfPointer(
651            klass->GetEmbeddedImTableEntry(i, pointer_size)), pointer_size);
652      }
653    }
654  }
655  if (object->GetClass() == mirror::Method::StaticClass() ||
656      object->GetClass() == mirror::Constructor::StaticClass()) {
657    // Need to go update the ArtMethod.
658    auto* dest = down_cast<mirror::AbstractMethod*>(copy);
659    auto* src = down_cast<mirror::AbstractMethod*>(object);
660    dest->SetArtMethod(RelocatedAddressOfPointer(src->GetArtMethod()));
661  }
662}
663
664void PatchOat::FixupMethod(ArtMethod* object, ArtMethod* copy) {
665  const size_t pointer_size = InstructionSetPointerSize(isa_);
666  copy->CopyFrom(object, pointer_size);
667  // Just update the entry points if it looks like we should.
668  // TODO: sanity check all the pointers' values
669  copy->SetDeclaringClass(RelocatedAddressOfPointer(object->GetDeclaringClass()));
670  copy->SetDexCacheResolvedMethods(RelocatedAddressOfPointer(object->GetDexCacheResolvedMethods()));
671  copy->SetDexCacheResolvedTypes(RelocatedAddressOfPointer(object->GetDexCacheResolvedTypes()));
672  copy->SetEntryPointFromQuickCompiledCodePtrSize(RelocatedAddressOfPointer(
673      object->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size)), pointer_size);
674  copy->SetEntryPointFromJniPtrSize(RelocatedAddressOfPointer(
675      object->GetEntryPointFromJniPtrSize(pointer_size)), pointer_size);
676}
677
678bool PatchOat::Patch(File* input_oat, off_t delta, File* output_oat, TimingLogger* timings,
679                     bool output_oat_opened_from_fd, bool new_oat_out) {
680  CHECK(input_oat != nullptr);
681  CHECK(output_oat != nullptr);
682  CHECK_GE(input_oat->Fd(), 0);
683  CHECK_GE(output_oat->Fd(), 0);
684  TimingLogger::ScopedTiming t("Setup Oat File Patching", timings);
685
686  std::string error_msg;
687  std::unique_ptr<ElfFile> elf(ElfFile::Open(input_oat,
688                                             PROT_READ | PROT_WRITE, MAP_PRIVATE, &error_msg));
689  if (elf.get() == nullptr) {
690    LOG(ERROR) << "unable to open oat file " << input_oat->GetPath() << " : " << error_msg;
691    return false;
692  }
693
694  MaybePic is_oat_pic = IsOatPic(elf.get());
695  if (is_oat_pic >= ERROR_FIRST) {
696    // Error logged by IsOatPic
697    return false;
698  } else if (is_oat_pic == PIC) {
699    // Do not need to do ELF-file patching. Create a symlink and skip the rest.
700    // Any errors will be logged by the function call.
701    return ReplaceOatFileWithSymlink(input_oat->GetPath(),
702                                     output_oat->GetPath(),
703                                     output_oat_opened_from_fd,
704                                     new_oat_out);
705  } else {
706    CHECK(is_oat_pic == NOT_PIC);
707  }
708
709  PatchOat p(elf.release(), delta, timings);
710  t.NewTiming("Patch Oat file");
711  if (!p.PatchElf()) {
712    return false;
713  }
714
715  t.NewTiming("Writing oat file");
716  if (!p.WriteElf(output_oat)) {
717    return false;
718  }
719  return true;
720}
721
722template <typename ElfFileImpl>
723bool PatchOat::PatchOatHeader(ElfFileImpl* oat_file) {
724  auto rodata_sec = oat_file->FindSectionByName(".rodata");
725  if (rodata_sec == nullptr) {
726    return false;
727  }
728  OatHeader* oat_header = reinterpret_cast<OatHeader*>(oat_file->Begin() + rodata_sec->sh_offset);
729  if (!oat_header->IsValid()) {
730    LOG(ERROR) << "Elf file " << oat_file->GetFile().GetPath() << " has an invalid oat header";
731    return false;
732  }
733  oat_header->RelocateOat(delta_);
734  return true;
735}
736
737bool PatchOat::PatchElf() {
738  if (oat_file_->Is64Bit())
739    return PatchElf<ElfFileImpl64>(oat_file_->GetImpl64());
740  else
741    return PatchElf<ElfFileImpl32>(oat_file_->GetImpl32());
742}
743
744template <typename ElfFileImpl>
745bool PatchOat::PatchElf(ElfFileImpl* oat_file) {
746  TimingLogger::ScopedTiming t("Fixup Elf Text Section", timings_);
747
748  // Fix up absolute references to locations within the boot image.
749  if (!oat_file->ApplyOatPatchesTo(".text", delta_)) {
750    return false;
751  }
752
753  // Update the OatHeader fields referencing the boot image.
754  if (!PatchOatHeader<ElfFileImpl>(oat_file)) {
755    return false;
756  }
757
758  bool need_boot_oat_fixup = true;
759  for (unsigned int i = 0; i < oat_file->GetProgramHeaderNum(); ++i) {
760    auto hdr = oat_file->GetProgramHeader(i);
761    if (hdr->p_type == PT_LOAD && hdr->p_vaddr == 0u) {
762      need_boot_oat_fixup = false;
763      break;
764    }
765  }
766  if (!need_boot_oat_fixup) {
767    // This is an app oat file that can be loaded at an arbitrary address in memory.
768    // Boot image references were patched above and there's nothing else to do.
769    return true;
770  }
771
772  // This is a boot oat file that's loaded at a particular address and we need
773  // to patch all absolute addresses, starting with ELF program headers.
774
775  t.NewTiming("Fixup Elf Headers");
776  // Fixup Phdr's
777  oat_file->FixupProgramHeaders(delta_);
778
779  t.NewTiming("Fixup Section Headers");
780  // Fixup Shdr's
781  oat_file->FixupSectionHeaders(delta_);
782
783  t.NewTiming("Fixup Dynamics");
784  oat_file->FixupDynamic(delta_);
785
786  t.NewTiming("Fixup Elf Symbols");
787  // Fixup dynsym
788  if (!oat_file->FixupSymbols(delta_, true)) {
789    return false;
790  }
791  // Fixup symtab
792  if (!oat_file->FixupSymbols(delta_, false)) {
793    return false;
794  }
795
796  t.NewTiming("Fixup Debug Sections");
797  if (!oat_file->FixupDebugSections(delta_)) {
798    return false;
799  }
800
801  return true;
802}
803
804static int orig_argc;
805static char** orig_argv;
806
807static std::string CommandLine() {
808  std::vector<std::string> command;
809  for (int i = 0; i < orig_argc; ++i) {
810    command.push_back(orig_argv[i]);
811  }
812  return Join(command, ' ');
813}
814
815static void UsageErrorV(const char* fmt, va_list ap) {
816  std::string error;
817  StringAppendV(&error, fmt, ap);
818  LOG(ERROR) << error;
819}
820
821static void UsageError(const char* fmt, ...) {
822  va_list ap;
823  va_start(ap, fmt);
824  UsageErrorV(fmt, ap);
825  va_end(ap);
826}
827
828NO_RETURN static void Usage(const char *fmt, ...) {
829  va_list ap;
830  va_start(ap, fmt);
831  UsageErrorV(fmt, ap);
832  va_end(ap);
833
834  UsageError("Command: %s", CommandLine().c_str());
835  UsageError("Usage: patchoat [options]...");
836  UsageError("");
837  UsageError("  --instruction-set=<isa>: Specifies the instruction set the patched code is");
838  UsageError("      compiled for. Required if you use --input-oat-location");
839  UsageError("");
840  UsageError("  --input-oat-file=<file.oat>: Specifies the exact filename of the oat file to be");
841  UsageError("      patched.");
842  UsageError("");
843  UsageError("  --input-oat-fd=<file-descriptor>: Specifies the file-descriptor of the oat file");
844  UsageError("      to be patched.");
845  UsageError("");
846  UsageError("  --input-oat-location=<file.oat>: Specifies the 'location' to read the patched");
847  UsageError("      oat file from. If used one must also supply the --instruction-set");
848  UsageError("");
849  UsageError("  --input-image-location=<file.art>: Specifies the 'location' of the image file to");
850  UsageError("      be patched. If --instruction-set is not given it will use the instruction set");
851  UsageError("      extracted from the --input-oat-file.");
852  UsageError("");
853  UsageError("  --output-oat-file=<file.oat>: Specifies the exact file to write the patched oat");
854  UsageError("      file to.");
855  UsageError("");
856  UsageError("  --output-oat-fd=<file-descriptor>: Specifies the file-descriptor to write the");
857  UsageError("      the patched oat file to.");
858  UsageError("");
859  UsageError("  --output-image-file=<file.art>: Specifies the exact file to write the patched");
860  UsageError("      image file to.");
861  UsageError("");
862  UsageError("  --output-image-fd=<file-descriptor>: Specifies the file-descriptor to write the");
863  UsageError("      the patched image file to.");
864  UsageError("");
865  UsageError("  --orig-base-offset=<original-base-offset>: Specify the base offset the input file");
866  UsageError("      was compiled with. This is needed if one is specifying a --base-offset");
867  UsageError("");
868  UsageError("  --base-offset=<new-base-offset>: Specify the base offset we will repatch the");
869  UsageError("      given files to use. This requires that --orig-base-offset is also given.");
870  UsageError("");
871  UsageError("  --base-offset-delta=<delta>: Specify the amount to change the old base-offset by.");
872  UsageError("      This value may be negative.");
873  UsageError("");
874  UsageError("  --patched-image-file=<file.art>: Use the same patch delta as was used to patch");
875  UsageError("      the given image file.");
876  UsageError("");
877  UsageError("  --patched-image-location=<file.art>: Use the same patch delta as was used to");
878  UsageError("      patch the given image location. If used one must also specify the");
879  UsageError("      --instruction-set flag. It will search for this image in the same way that");
880  UsageError("      is done when loading one.");
881  UsageError("");
882  UsageError("  --lock-output: Obtain a flock on output oat file before starting.");
883  UsageError("");
884  UsageError("  --no-lock-output: Do not attempt to obtain a flock on output oat file.");
885  UsageError("");
886  UsageError("  --dump-timings: dump out patch timing information");
887  UsageError("");
888  UsageError("  --no-dump-timings: do not dump out patch timing information");
889  UsageError("");
890
891  exit(EXIT_FAILURE);
892}
893
894static bool ReadBaseDelta(const char* name, off_t* delta, std::string* error_msg) {
895  CHECK(name != nullptr);
896  CHECK(delta != nullptr);
897  std::unique_ptr<File> file;
898  if (OS::FileExists(name)) {
899    file.reset(OS::OpenFileForReading(name));
900    if (file.get() == nullptr) {
901      *error_msg = "Failed to open file %s for reading";
902      return false;
903    }
904  } else {
905    *error_msg = "File %s does not exist";
906    return false;
907  }
908  CHECK(file.get() != nullptr);
909  ImageHeader hdr;
910  if (sizeof(hdr) != file->Read(reinterpret_cast<char*>(&hdr), sizeof(hdr), 0)) {
911    *error_msg = "Failed to read file %s";
912    return false;
913  }
914  if (!hdr.IsValid()) {
915    *error_msg = "%s does not contain a valid image header.";
916    return false;
917  }
918  *delta = hdr.GetPatchDelta();
919  return true;
920}
921
922static File* CreateOrOpen(const char* name, bool* created) {
923  if (OS::FileExists(name)) {
924    *created = false;
925    return OS::OpenFileReadWrite(name);
926  } else {
927    *created = true;
928    std::unique_ptr<File> f(OS::CreateEmptyFile(name));
929    if (f.get() != nullptr) {
930      if (fchmod(f->Fd(), 0644) != 0) {
931        PLOG(ERROR) << "Unable to make " << name << " world readable";
932        TEMP_FAILURE_RETRY(unlink(name));
933        return nullptr;
934      }
935    }
936    return f.release();
937  }
938}
939
940// Either try to close the file (close=true), or erase it.
941static bool FinishFile(File* file, bool close) {
942  if (close) {
943    if (file->FlushCloseOrErase() != 0) {
944      PLOG(ERROR) << "Failed to flush and close file.";
945      return false;
946    }
947    return true;
948  } else {
949    file->Erase();
950    return false;
951  }
952}
953
954static int patchoat(int argc, char **argv) {
955  InitLogging(argv);
956  MemMap::Init();
957  const bool debug = kIsDebugBuild;
958  orig_argc = argc;
959  orig_argv = argv;
960  TimingLogger timings("patcher", false, false);
961
962  InitLogging(argv);
963
964  // Skip over the command name.
965  argv++;
966  argc--;
967
968  if (argc == 0) {
969    Usage("No arguments specified");
970  }
971
972  timings.StartTiming("Patchoat");
973
974  // cmd line args
975  bool isa_set = false;
976  InstructionSet isa = kNone;
977  std::string input_oat_filename;
978  std::string input_oat_location;
979  int input_oat_fd = -1;
980  bool have_input_oat = false;
981  std::string input_image_location;
982  std::string output_oat_filename;
983  int output_oat_fd = -1;
984  bool have_output_oat = false;
985  std::string output_image_filename;
986  int output_image_fd = -1;
987  bool have_output_image = false;
988  uintptr_t base_offset = 0;
989  bool base_offset_set = false;
990  uintptr_t orig_base_offset = 0;
991  bool orig_base_offset_set = false;
992  off_t base_delta = 0;
993  bool base_delta_set = false;
994  std::string patched_image_filename;
995  std::string patched_image_location;
996  bool dump_timings = kIsDebugBuild;
997  bool lock_output = true;
998
999  for (int i = 0; i < argc; ++i) {
1000    const StringPiece option(argv[i]);
1001    const bool log_options = false;
1002    if (log_options) {
1003      LOG(INFO) << "patchoat: option[" << i << "]=" << argv[i];
1004    }
1005    if (option.starts_with("--instruction-set=")) {
1006      isa_set = true;
1007      const char* isa_str = option.substr(strlen("--instruction-set=")).data();
1008      isa = GetInstructionSetFromString(isa_str);
1009      if (isa == kNone) {
1010        Usage("Unknown or invalid instruction set %s", isa_str);
1011      }
1012    } else if (option.starts_with("--input-oat-location=")) {
1013      if (have_input_oat) {
1014        Usage("Only one of --input-oat-file, --input-oat-location and --input-oat-fd may be used.");
1015      }
1016      have_input_oat = true;
1017      input_oat_location = option.substr(strlen("--input-oat-location=")).data();
1018    } else if (option.starts_with("--input-oat-file=")) {
1019      if (have_input_oat) {
1020        Usage("Only one of --input-oat-file, --input-oat-location and --input-oat-fd may be used.");
1021      }
1022      have_input_oat = true;
1023      input_oat_filename = option.substr(strlen("--input-oat-file=")).data();
1024    } else if (option.starts_with("--input-oat-fd=")) {
1025      if (have_input_oat) {
1026        Usage("Only one of --input-oat-file, --input-oat-location and --input-oat-fd may be used.");
1027      }
1028      have_input_oat = true;
1029      const char* oat_fd_str = option.substr(strlen("--input-oat-fd=")).data();
1030      if (!ParseInt(oat_fd_str, &input_oat_fd)) {
1031        Usage("Failed to parse --input-oat-fd argument '%s' as an integer", oat_fd_str);
1032      }
1033      if (input_oat_fd < 0) {
1034        Usage("--input-oat-fd pass a negative value %d", input_oat_fd);
1035      }
1036    } else if (option.starts_with("--input-image-location=")) {
1037      input_image_location = option.substr(strlen("--input-image-location=")).data();
1038    } else if (option.starts_with("--output-oat-file=")) {
1039      if (have_output_oat) {
1040        Usage("Only one of --output-oat-file, and --output-oat-fd may be used.");
1041      }
1042      have_output_oat = true;
1043      output_oat_filename = option.substr(strlen("--output-oat-file=")).data();
1044    } else if (option.starts_with("--output-oat-fd=")) {
1045      if (have_output_oat) {
1046        Usage("Only one of --output-oat-file, --output-oat-fd may be used.");
1047      }
1048      have_output_oat = true;
1049      const char* oat_fd_str = option.substr(strlen("--output-oat-fd=")).data();
1050      if (!ParseInt(oat_fd_str, &output_oat_fd)) {
1051        Usage("Failed to parse --output-oat-fd argument '%s' as an integer", oat_fd_str);
1052      }
1053      if (output_oat_fd < 0) {
1054        Usage("--output-oat-fd pass a negative value %d", output_oat_fd);
1055      }
1056    } else if (option.starts_with("--output-image-file=")) {
1057      if (have_output_image) {
1058        Usage("Only one of --output-image-file, and --output-image-fd may be used.");
1059      }
1060      have_output_image = true;
1061      output_image_filename = option.substr(strlen("--output-image-file=")).data();
1062    } else if (option.starts_with("--output-image-fd=")) {
1063      if (have_output_image) {
1064        Usage("Only one of --output-image-file, and --output-image-fd may be used.");
1065      }
1066      have_output_image = true;
1067      const char* image_fd_str = option.substr(strlen("--output-image-fd=")).data();
1068      if (!ParseInt(image_fd_str, &output_image_fd)) {
1069        Usage("Failed to parse --output-image-fd argument '%s' as an integer", image_fd_str);
1070      }
1071      if (output_image_fd < 0) {
1072        Usage("--output-image-fd pass a negative value %d", output_image_fd);
1073      }
1074    } else if (option.starts_with("--orig-base-offset=")) {
1075      const char* orig_base_offset_str = option.substr(strlen("--orig-base-offset=")).data();
1076      orig_base_offset_set = true;
1077      if (!ParseUint(orig_base_offset_str, &orig_base_offset)) {
1078        Usage("Failed to parse --orig-base-offset argument '%s' as an uintptr_t",
1079              orig_base_offset_str);
1080      }
1081    } else if (option.starts_with("--base-offset=")) {
1082      const char* base_offset_str = option.substr(strlen("--base-offset=")).data();
1083      base_offset_set = true;
1084      if (!ParseUint(base_offset_str, &base_offset)) {
1085        Usage("Failed to parse --base-offset argument '%s' as an uintptr_t", base_offset_str);
1086      }
1087    } else if (option.starts_with("--base-offset-delta=")) {
1088      const char* base_delta_str = option.substr(strlen("--base-offset-delta=")).data();
1089      base_delta_set = true;
1090      if (!ParseInt(base_delta_str, &base_delta)) {
1091        Usage("Failed to parse --base-offset-delta argument '%s' as an off_t", base_delta_str);
1092      }
1093    } else if (option.starts_with("--patched-image-location=")) {
1094      patched_image_location = option.substr(strlen("--patched-image-location=")).data();
1095    } else if (option.starts_with("--patched-image-file=")) {
1096      patched_image_filename = option.substr(strlen("--patched-image-file=")).data();
1097    } else if (option == "--lock-output") {
1098      lock_output = true;
1099    } else if (option == "--no-lock-output") {
1100      lock_output = false;
1101    } else if (option == "--dump-timings") {
1102      dump_timings = true;
1103    } else if (option == "--no-dump-timings") {
1104      dump_timings = false;
1105    } else {
1106      Usage("Unknown argument %s", option.data());
1107    }
1108  }
1109
1110  {
1111    // Only 1 of these may be set.
1112    uint32_t cnt = 0;
1113    cnt += (base_delta_set) ? 1 : 0;
1114    cnt += (base_offset_set && orig_base_offset_set) ? 1 : 0;
1115    cnt += (!patched_image_filename.empty()) ? 1 : 0;
1116    cnt += (!patched_image_location.empty()) ? 1 : 0;
1117    if (cnt > 1) {
1118      Usage("Only one of --base-offset/--orig-base-offset, --base-offset-delta, "
1119            "--patched-image-filename or --patched-image-location may be used.");
1120    } else if (cnt == 0) {
1121      Usage("Must specify --base-offset-delta, --base-offset and --orig-base-offset, "
1122            "--patched-image-location or --patched-image-file");
1123    }
1124  }
1125
1126  if (have_input_oat != have_output_oat) {
1127    Usage("Either both input and output oat must be supplied or niether must be.");
1128  }
1129
1130  if ((!input_image_location.empty()) != have_output_image) {
1131    Usage("Either both input and output image must be supplied or niether must be.");
1132  }
1133
1134  // We know we have both the input and output so rename for clarity.
1135  bool have_image_files = have_output_image;
1136  bool have_oat_files = have_output_oat;
1137
1138  if (!have_oat_files && !have_image_files) {
1139    Usage("Must be patching either an oat or an image file or both.");
1140  }
1141
1142  if (!have_oat_files && !isa_set) {
1143    Usage("Must include ISA if patching an image file without an oat file.");
1144  }
1145
1146  if (!input_oat_location.empty()) {
1147    if (!isa_set) {
1148      Usage("specifying a location requires specifying an instruction set");
1149    }
1150    if (!LocationToFilename(input_oat_location, isa, &input_oat_filename)) {
1151      Usage("Unable to find filename for input oat location %s", input_oat_location.c_str());
1152    }
1153    if (debug) {
1154      LOG(INFO) << "Using input-oat-file " << input_oat_filename;
1155    }
1156  }
1157  if (!patched_image_location.empty()) {
1158    if (!isa_set) {
1159      Usage("specifying a location requires specifying an instruction set");
1160    }
1161    std::string system_filename;
1162    bool has_system = false;
1163    std::string cache_filename;
1164    bool has_cache = false;
1165    bool has_android_data_unused = false;
1166    bool is_global_cache = false;
1167    if (!gc::space::ImageSpace::FindImageFilename(patched_image_location.c_str(), isa,
1168                                                  &system_filename, &has_system, &cache_filename,
1169                                                  &has_android_data_unused, &has_cache,
1170                                                  &is_global_cache)) {
1171      Usage("Unable to determine image file for location %s", patched_image_location.c_str());
1172    }
1173    if (has_cache) {
1174      patched_image_filename = cache_filename;
1175    } else if (has_system) {
1176      LOG(WARNING) << "Only image file found was in /system for image location "
1177                   << patched_image_location;
1178      patched_image_filename = system_filename;
1179    } else {
1180      Usage("Unable to determine image file for location %s", patched_image_location.c_str());
1181    }
1182    if (debug) {
1183      LOG(INFO) << "Using patched-image-file " << patched_image_filename;
1184    }
1185  }
1186
1187  if (!base_delta_set) {
1188    if (orig_base_offset_set && base_offset_set) {
1189      base_delta_set = true;
1190      base_delta = base_offset - orig_base_offset;
1191    } else if (!patched_image_filename.empty()) {
1192      base_delta_set = true;
1193      std::string error_msg;
1194      if (!ReadBaseDelta(patched_image_filename.c_str(), &base_delta, &error_msg)) {
1195        Usage(error_msg.c_str(), patched_image_filename.c_str());
1196      }
1197    } else {
1198      if (base_offset_set) {
1199        Usage("Unable to determine original base offset.");
1200      } else {
1201        Usage("Must supply a desired new offset or delta.");
1202      }
1203    }
1204  }
1205
1206  if (!IsAligned<kPageSize>(base_delta)) {
1207    Usage("Base offset/delta must be alligned to a pagesize (0x%08x) boundary.", kPageSize);
1208  }
1209
1210  // Do we need to cleanup output files if we fail?
1211  bool new_image_out = false;
1212  bool new_oat_out = false;
1213
1214  std::unique_ptr<File> input_oat;
1215  std::unique_ptr<File> output_oat;
1216  std::unique_ptr<File> output_image;
1217
1218  if (have_image_files) {
1219    CHECK(!input_image_location.empty());
1220
1221    if (output_image_fd != -1) {
1222      if (output_image_filename.empty()) {
1223        output_image_filename = "output-image-file";
1224      }
1225      output_image.reset(new File(output_image_fd, output_image_filename, true));
1226    } else {
1227      CHECK(!output_image_filename.empty());
1228      output_image.reset(CreateOrOpen(output_image_filename.c_str(), &new_image_out));
1229    }
1230  } else {
1231    CHECK(output_image_filename.empty() && output_image_fd == -1 && input_image_location.empty());
1232  }
1233
1234  if (have_oat_files) {
1235    if (input_oat_fd != -1) {
1236      if (input_oat_filename.empty()) {
1237        input_oat_filename = "input-oat-file";
1238      }
1239      input_oat.reset(new File(input_oat_fd, input_oat_filename, false));
1240      if (input_oat_fd == output_oat_fd) {
1241        input_oat.get()->DisableAutoClose();
1242      }
1243      if (input_oat == nullptr) {
1244        // Unlikely, but ensure exhaustive logging in non-0 exit code case
1245        LOG(ERROR) << "Failed to open input oat file by its FD" << input_oat_fd;
1246      }
1247    } else {
1248      CHECK(!input_oat_filename.empty());
1249      input_oat.reset(OS::OpenFileForReading(input_oat_filename.c_str()));
1250      if (input_oat == nullptr) {
1251        int err = errno;
1252        LOG(ERROR) << "Failed to open input oat file " << input_oat_filename
1253                   << ": " << strerror(err) << "(" << err << ")";
1254      }
1255    }
1256
1257    if (output_oat_fd != -1) {
1258      if (output_oat_filename.empty()) {
1259        output_oat_filename = "output-oat-file";
1260      }
1261      output_oat.reset(new File(output_oat_fd, output_oat_filename, true));
1262      if (output_oat == nullptr) {
1263        // Unlikely, but ensure exhaustive logging in non-0 exit code case
1264        LOG(ERROR) << "Failed to open output oat file by its FD" << output_oat_fd;
1265      }
1266    } else {
1267      CHECK(!output_oat_filename.empty());
1268      output_oat.reset(CreateOrOpen(output_oat_filename.c_str(), &new_oat_out));
1269      if (output_oat == nullptr) {
1270        int err = errno;
1271        LOG(ERROR) << "Failed to open output oat file " << output_oat_filename
1272                   << ": " << strerror(err) << "(" << err << ")";
1273      }
1274    }
1275  }
1276
1277  // TODO: get rid of this.
1278  auto cleanup = [&output_image_filename, &output_oat_filename,
1279                  &new_oat_out, &new_image_out, &timings, &dump_timings](bool success) {
1280    timings.EndTiming();
1281    if (!success) {
1282      if (new_oat_out) {
1283        CHECK(!output_oat_filename.empty());
1284        TEMP_FAILURE_RETRY(unlink(output_oat_filename.c_str()));
1285      }
1286      if (new_image_out) {
1287        CHECK(!output_image_filename.empty());
1288        TEMP_FAILURE_RETRY(unlink(output_image_filename.c_str()));
1289      }
1290    }
1291    if (dump_timings) {
1292      LOG(INFO) << Dumpable<TimingLogger>(timings);
1293    }
1294
1295    if (kIsDebugBuild) {
1296      LOG(INFO) << "Cleaning up.. success? " << success;
1297    }
1298  };
1299
1300  if (have_oat_files && (input_oat.get() == nullptr || output_oat.get() == nullptr)) {
1301    LOG(ERROR) << "Failed to open input/output oat files";
1302    cleanup(false);
1303    return EXIT_FAILURE;
1304  } else if (have_image_files && output_image.get() == nullptr) {
1305    LOG(ERROR) << "Failed to open output image file";
1306    cleanup(false);
1307    return EXIT_FAILURE;
1308  }
1309
1310  if (debug) {
1311    LOG(INFO) << "moving offset by " << base_delta
1312              << " (0x" << std::hex << base_delta << ") bytes or "
1313              << std::dec << (base_delta/kPageSize) << " pages.";
1314  }
1315
1316  // TODO: is it going to be promatic to unlink a file that was flock-ed?
1317  ScopedFlock output_oat_lock;
1318  if (lock_output) {
1319    std::string error_msg;
1320    if (have_oat_files && !output_oat_lock.Init(output_oat.get(), &error_msg)) {
1321      LOG(ERROR) << "Unable to lock output oat " << output_image->GetPath() << ": " << error_msg;
1322      cleanup(false);
1323      return EXIT_FAILURE;
1324    }
1325  }
1326
1327  bool ret;
1328  if (have_image_files && have_oat_files) {
1329    TimingLogger::ScopedTiming pt("patch image and oat", &timings);
1330    ret = PatchOat::Patch(input_oat.get(), input_image_location, base_delta,
1331                          output_oat.get(), output_image.get(), isa, &timings,
1332                          output_oat_fd >= 0,  // was it opened from FD?
1333                          new_oat_out);
1334    // The order here doesn't matter. If the first one is successfully saved and the second one
1335    // erased, ImageSpace will still detect a problem and not use the files.
1336    ret = ret && FinishFile(output_image.get(), ret);
1337    ret = ret && FinishFile(output_oat.get(), ret);
1338  } else if (have_oat_files) {
1339    TimingLogger::ScopedTiming pt("patch oat", &timings);
1340    ret = PatchOat::Patch(input_oat.get(), base_delta, output_oat.get(), &timings,
1341                          output_oat_fd >= 0,  // was it opened from FD?
1342                          new_oat_out);
1343    ret = ret && FinishFile(output_oat.get(), ret);
1344  } else if (have_image_files) {
1345    TimingLogger::ScopedTiming pt("patch image", &timings);
1346    ret = PatchOat::Patch(input_image_location, base_delta, output_image.get(), isa, &timings);
1347    ret = ret && FinishFile(output_image.get(), ret);
1348  } else {
1349    CHECK(false);
1350    ret = true;
1351  }
1352
1353  if (kIsDebugBuild) {
1354    LOG(INFO) << "Exiting with return ... " << ret;
1355  }
1356  cleanup(ret);
1357  return (ret) ? EXIT_SUCCESS : EXIT_FAILURE;
1358}
1359
1360}  // namespace art
1361
1362int main(int argc, char **argv) {
1363  return art::patchoat(argc, argv);
1364}
1365