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