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