patchoat.cc revision 05792b98980741111b4d0a24d68cff2a8e070a3a
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* orig_dex_cache = dex_caches->GetWithoutChecks(i);
527    auto* copy_dex_cache = RelocatedCopyOf(orig_dex_cache);
528    const size_t pointer_size = InstructionSetPointerSize(isa_);
529    // Though the DexCache array fields are usually treated as native pointers, we set the full
530    // 64-bit values here, clearing the top 32 bits for 32-bit targets. The zero-extension is
531    // done by casting to the unsigned type uintptr_t before casting to int64_t, i.e.
532    //     static_cast<int64_t>(reinterpret_cast<uintptr_t>(image_begin_ + offset))).
533    GcRoot<mirror::String>* orig_strings = orig_dex_cache->GetStrings();
534    GcRoot<mirror::String>* relocated_strings = RelocatedAddressOfPointer(orig_strings);
535    copy_dex_cache->SetField64<false>(
536        mirror::DexCache::StringsOffset(),
537        static_cast<int64_t>(reinterpret_cast<uintptr_t>(relocated_strings)));
538    if (orig_strings != nullptr) {
539      GcRoot<mirror::String>* copy_strings = RelocatedCopyOf(orig_strings);
540      for (size_t j = 0, num = orig_dex_cache->NumStrings(); j != num; ++j) {
541        copy_strings[j] = GcRoot<mirror::String>(RelocatedAddressOfPointer(orig_strings[j].Read()));
542      }
543    }
544    GcRoot<mirror::Class>* orig_types = orig_dex_cache->GetResolvedTypes();
545    GcRoot<mirror::Class>* relocated_types = RelocatedAddressOfPointer(orig_types);
546    copy_dex_cache->SetField64<false>(
547        mirror::DexCache::ResolvedTypesOffset(),
548        static_cast<int64_t>(reinterpret_cast<uintptr_t>(relocated_types)));
549    if (orig_types != nullptr) {
550      GcRoot<mirror::Class>* copy_types = RelocatedCopyOf(orig_types);
551      for (size_t j = 0, num = orig_dex_cache->NumResolvedTypes(); j != num; ++j) {
552        copy_types[j] = GcRoot<mirror::Class>(RelocatedAddressOfPointer(orig_types[j].Read()));
553      }
554    }
555    ArtMethod** orig_methods = orig_dex_cache->GetResolvedMethods();
556    ArtMethod** relocated_methods = RelocatedAddressOfPointer(orig_methods);
557    copy_dex_cache->SetField64<false>(
558        mirror::DexCache::ResolvedMethodsOffset(),
559        static_cast<int64_t>(reinterpret_cast<uintptr_t>(relocated_methods)));
560    if (orig_methods != nullptr) {
561      ArtMethod** copy_methods = RelocatedCopyOf(orig_methods);
562      for (size_t j = 0, num = orig_dex_cache->NumResolvedMethods(); j != num; ++j) {
563        ArtMethod* orig = mirror::DexCache::GetElementPtrSize(orig_methods, j, pointer_size);
564        ArtMethod* copy = RelocatedAddressOfPointer(orig);
565        mirror::DexCache::SetElementPtrSize(copy_methods, j, copy, pointer_size);
566      }
567    }
568    ArtField** orig_fields = orig_dex_cache->GetResolvedFields();
569    ArtField** relocated_fields = RelocatedAddressOfPointer(orig_fields);
570    copy_dex_cache->SetField64<false>(
571        mirror::DexCache::ResolvedFieldsOffset(),
572        static_cast<int64_t>(reinterpret_cast<uintptr_t>(relocated_fields)));
573    if (orig_fields != nullptr) {
574      ArtField** copy_fields = RelocatedCopyOf(orig_fields);
575      for (size_t j = 0, num = orig_dex_cache->NumResolvedFields(); j != num; ++j) {
576        ArtField* orig = mirror::DexCache::GetElementPtrSize(orig_fields, j, pointer_size);
577        ArtField* copy = RelocatedAddressOfPointer(orig);
578        mirror::DexCache::SetElementPtrSize(copy_fields, j, copy, pointer_size);
579      }
580    }
581  }
582}
583
584void PatchOat::FixupNativePointerArray(mirror::PointerArray* object) {
585  if (object->IsIntArray()) {
586    mirror::IntArray* arr = object->AsIntArray();
587    mirror::IntArray* copy_arr = down_cast<mirror::IntArray*>(RelocatedCopyOf(arr));
588    for (size_t j = 0, count2 = arr->GetLength(); j < count2; ++j) {
589      copy_arr->SetWithoutChecks<false>(
590          j, RelocatedAddressOfIntPointer(arr->GetWithoutChecks(j)));
591    }
592  } else {
593    CHECK(object->IsLongArray());
594    mirror::LongArray* arr = object->AsLongArray();
595    mirror::LongArray* copy_arr = down_cast<mirror::LongArray*>(RelocatedCopyOf(arr));
596    for (size_t j = 0, count2 = arr->GetLength(); j < count2; ++j) {
597      copy_arr->SetWithoutChecks<false>(
598          j, RelocatedAddressOfIntPointer(arr->GetWithoutChecks(j)));
599    }
600  }
601}
602
603bool PatchOat::PatchImage() {
604  ImageHeader* image_header = reinterpret_cast<ImageHeader*>(image_->Begin());
605  CHECK_GT(image_->Size(), sizeof(ImageHeader));
606  // These are the roots from the original file.
607  auto* img_roots = image_header->GetImageRoots();
608  image_header->RelocateImage(delta_);
609
610  PatchArtFields(image_header);
611  PatchArtMethods(image_header);
612  PatchInternedStrings(image_header);
613  // Patch dex file int/long arrays which point to ArtFields.
614  PatchDexFileArrays(img_roots);
615
616  VisitObject(img_roots);
617  if (!image_header->IsValid()) {
618    LOG(ERROR) << "reloction renders image header invalid";
619    return false;
620  }
621
622  {
623    TimingLogger::ScopedTiming t("Walk Bitmap", timings_);
624    // Walk the bitmap.
625    WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
626    bitmap_->Walk(PatchOat::BitmapCallback, this);
627  }
628  return true;
629}
630
631bool PatchOat::InHeap(mirror::Object* o) {
632  uintptr_t begin = reinterpret_cast<uintptr_t>(heap_->Begin());
633  uintptr_t end = reinterpret_cast<uintptr_t>(heap_->End());
634  uintptr_t obj = reinterpret_cast<uintptr_t>(o);
635  return o == nullptr || (begin <= obj && obj < end);
636}
637
638void PatchOat::PatchVisitor::operator() (mirror::Object* obj, MemberOffset off,
639                                         bool is_static_unused ATTRIBUTE_UNUSED) const {
640  mirror::Object* referent = obj->GetFieldObject<mirror::Object, kVerifyNone>(off);
641  DCHECK(patcher_->InHeap(referent)) << "Referent is not in the heap.";
642  mirror::Object* moved_object = patcher_->RelocatedAddressOfPointer(referent);
643  copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(off, moved_object);
644}
645
646void PatchOat::PatchVisitor::operator() (mirror::Class* cls ATTRIBUTE_UNUSED,
647                                         mirror::Reference* ref) const {
648  MemberOffset off = mirror::Reference::ReferentOffset();
649  mirror::Object* referent = ref->GetReferent();
650  DCHECK(patcher_->InHeap(referent)) << "Referent is not in the heap.";
651  mirror::Object* moved_object = patcher_->RelocatedAddressOfPointer(referent);
652  copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(off, moved_object);
653}
654
655// Called by BitmapCallback
656void PatchOat::VisitObject(mirror::Object* object) {
657  mirror::Object* copy = RelocatedCopyOf(object);
658  CHECK(copy != nullptr);
659  if (kUseBakerOrBrooksReadBarrier) {
660    object->AssertReadBarrierPointer();
661    if (kUseBrooksReadBarrier) {
662      mirror::Object* moved_to = RelocatedAddressOfPointer(object);
663      copy->SetReadBarrierPointer(moved_to);
664      DCHECK_EQ(copy->GetReadBarrierPointer(), moved_to);
665    }
666  }
667  PatchOat::PatchVisitor visitor(this, copy);
668  object->VisitReferences<kVerifyNone>(visitor, visitor);
669  if (object->IsClass<kVerifyNone>()) {
670    auto* klass = object->AsClass();
671    auto* copy_klass = down_cast<mirror::Class*>(copy);
672    copy_klass->SetDexCacheStrings(RelocatedAddressOfPointer(klass->GetDexCacheStrings()));
673    copy_klass->SetSFieldsPtrUnchecked(RelocatedAddressOfPointer(klass->GetSFieldsPtr()));
674    copy_klass->SetIFieldsPtrUnchecked(RelocatedAddressOfPointer(klass->GetIFieldsPtr()));
675    copy_klass->SetDirectMethodsPtrUnchecked(
676        RelocatedAddressOfPointer(klass->GetDirectMethodsPtr()));
677    copy_klass->SetVirtualMethodsPtr(RelocatedAddressOfPointer(klass->GetVirtualMethodsPtr()));
678    auto* vtable = klass->GetVTable();
679    if (vtable != nullptr) {
680      FixupNativePointerArray(vtable);
681    }
682    auto* iftable = klass->GetIfTable();
683    if (iftable != nullptr) {
684      for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
685        if (iftable->GetMethodArrayCount(i) > 0) {
686          auto* method_array = iftable->GetMethodArray(i);
687          CHECK(method_array != nullptr);
688          FixupNativePointerArray(method_array);
689        }
690      }
691    }
692    if (klass->ShouldHaveEmbeddedImtAndVTable()) {
693      const size_t pointer_size = InstructionSetPointerSize(isa_);
694      for (int32_t i = 0; i < klass->GetEmbeddedVTableLength(); ++i) {
695        copy_klass->SetEmbeddedVTableEntryUnchecked(i, RelocatedAddressOfPointer(
696            klass->GetEmbeddedVTableEntry(i, pointer_size)), pointer_size);
697      }
698      for (size_t i = 0; i < mirror::Class::kImtSize; ++i) {
699        copy_klass->SetEmbeddedImTableEntry(i, RelocatedAddressOfPointer(
700            klass->GetEmbeddedImTableEntry(i, pointer_size)), pointer_size);
701      }
702    }
703  }
704  if (object->GetClass() == mirror::Method::StaticClass() ||
705      object->GetClass() == mirror::Constructor::StaticClass()) {
706    // Need to go update the ArtMethod.
707    auto* dest = down_cast<mirror::AbstractMethod*>(copy);
708    auto* src = down_cast<mirror::AbstractMethod*>(object);
709    dest->SetArtMethod(RelocatedAddressOfPointer(src->GetArtMethod()));
710  }
711}
712
713void PatchOat::FixupMethod(ArtMethod* object, ArtMethod* copy) {
714  const size_t pointer_size = InstructionSetPointerSize(isa_);
715  copy->CopyFrom(object, pointer_size);
716  // Just update the entry points if it looks like we should.
717  // TODO: sanity check all the pointers' values
718  copy->SetDeclaringClass(RelocatedAddressOfPointer(object->GetDeclaringClass()));
719  copy->SetDexCacheResolvedMethods(
720      RelocatedAddressOfPointer(object->GetDexCacheResolvedMethods(pointer_size)), pointer_size);
721  copy->SetDexCacheResolvedTypes(
722      RelocatedAddressOfPointer(object->GetDexCacheResolvedTypes(pointer_size)), pointer_size);
723  copy->SetEntryPointFromQuickCompiledCodePtrSize(RelocatedAddressOfPointer(
724      object->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size)), pointer_size);
725  copy->SetEntryPointFromJniPtrSize(RelocatedAddressOfPointer(
726      object->GetEntryPointFromJniPtrSize(pointer_size)), pointer_size);
727}
728
729bool PatchOat::Patch(File* input_oat, off_t delta, File* output_oat, TimingLogger* timings,
730                     bool output_oat_opened_from_fd, bool new_oat_out) {
731  CHECK(input_oat != nullptr);
732  CHECK(output_oat != nullptr);
733  CHECK_GE(input_oat->Fd(), 0);
734  CHECK_GE(output_oat->Fd(), 0);
735  TimingLogger::ScopedTiming t("Setup Oat File Patching", timings);
736
737  std::string error_msg;
738  std::unique_ptr<ElfFile> elf(ElfFile::Open(input_oat,
739                                             PROT_READ | PROT_WRITE, MAP_PRIVATE, &error_msg));
740  if (elf.get() == nullptr) {
741    LOG(ERROR) << "unable to open oat file " << input_oat->GetPath() << " : " << error_msg;
742    return false;
743  }
744
745  MaybePic is_oat_pic = IsOatPic(elf.get());
746  if (is_oat_pic >= ERROR_FIRST) {
747    // Error logged by IsOatPic
748    return false;
749  } else if (is_oat_pic == PIC) {
750    // Do not need to do ELF-file patching. Create a symlink and skip the rest.
751    // Any errors will be logged by the function call.
752    return ReplaceOatFileWithSymlink(input_oat->GetPath(),
753                                     output_oat->GetPath(),
754                                     output_oat_opened_from_fd,
755                                     new_oat_out);
756  } else {
757    CHECK(is_oat_pic == NOT_PIC);
758  }
759
760  PatchOat p(elf.release(), delta, timings);
761  t.NewTiming("Patch Oat file");
762  if (!p.PatchElf()) {
763    return false;
764  }
765
766  t.NewTiming("Writing oat file");
767  if (!p.WriteElf(output_oat)) {
768    return false;
769  }
770  return true;
771}
772
773template <typename ElfFileImpl>
774bool PatchOat::PatchOatHeader(ElfFileImpl* oat_file) {
775  auto rodata_sec = oat_file->FindSectionByName(".rodata");
776  if (rodata_sec == nullptr) {
777    return false;
778  }
779  OatHeader* oat_header = reinterpret_cast<OatHeader*>(oat_file->Begin() + rodata_sec->sh_offset);
780  if (!oat_header->IsValid()) {
781    LOG(ERROR) << "Elf file " << oat_file->GetFile().GetPath() << " has an invalid oat header";
782    return false;
783  }
784  oat_header->RelocateOat(delta_);
785  return true;
786}
787
788bool PatchOat::PatchElf() {
789  if (oat_file_->Is64Bit())
790    return PatchElf<ElfFileImpl64>(oat_file_->GetImpl64());
791  else
792    return PatchElf<ElfFileImpl32>(oat_file_->GetImpl32());
793}
794
795template <typename ElfFileImpl>
796bool PatchOat::PatchElf(ElfFileImpl* oat_file) {
797  TimingLogger::ScopedTiming t("Fixup Elf Text Section", timings_);
798
799  // Fix up absolute references to locations within the boot image.
800  if (!oat_file->ApplyOatPatchesTo(".text", delta_)) {
801    return false;
802  }
803
804  // Update the OatHeader fields referencing the boot image.
805  if (!PatchOatHeader<ElfFileImpl>(oat_file)) {
806    return false;
807  }
808
809  bool need_boot_oat_fixup = true;
810  for (unsigned int i = 0; i < oat_file->GetProgramHeaderNum(); ++i) {
811    auto hdr = oat_file->GetProgramHeader(i);
812    if (hdr->p_type == PT_LOAD && hdr->p_vaddr == 0u) {
813      need_boot_oat_fixup = false;
814      break;
815    }
816  }
817  if (!need_boot_oat_fixup) {
818    // This is an app oat file that can be loaded at an arbitrary address in memory.
819    // Boot image references were patched above and there's nothing else to do.
820    return true;
821  }
822
823  // This is a boot oat file that's loaded at a particular address and we need
824  // to patch all absolute addresses, starting with ELF program headers.
825
826  t.NewTiming("Fixup Elf Headers");
827  // Fixup Phdr's
828  oat_file->FixupProgramHeaders(delta_);
829
830  t.NewTiming("Fixup Section Headers");
831  // Fixup Shdr's
832  oat_file->FixupSectionHeaders(delta_);
833
834  t.NewTiming("Fixup Dynamics");
835  oat_file->FixupDynamic(delta_);
836
837  t.NewTiming("Fixup Elf Symbols");
838  // Fixup dynsym
839  if (!oat_file->FixupSymbols(delta_, true)) {
840    return false;
841  }
842  // Fixup symtab
843  if (!oat_file->FixupSymbols(delta_, false)) {
844    return false;
845  }
846
847  t.NewTiming("Fixup Debug Sections");
848  if (!oat_file->FixupDebugSections(delta_)) {
849    return false;
850  }
851
852  return true;
853}
854
855static int orig_argc;
856static char** orig_argv;
857
858static std::string CommandLine() {
859  std::vector<std::string> command;
860  for (int i = 0; i < orig_argc; ++i) {
861    command.push_back(orig_argv[i]);
862  }
863  return Join(command, ' ');
864}
865
866static void UsageErrorV(const char* fmt, va_list ap) {
867  std::string error;
868  StringAppendV(&error, fmt, ap);
869  LOG(ERROR) << error;
870}
871
872static void UsageError(const char* fmt, ...) {
873  va_list ap;
874  va_start(ap, fmt);
875  UsageErrorV(fmt, ap);
876  va_end(ap);
877}
878
879NO_RETURN static void Usage(const char *fmt, ...) {
880  va_list ap;
881  va_start(ap, fmt);
882  UsageErrorV(fmt, ap);
883  va_end(ap);
884
885  UsageError("Command: %s", CommandLine().c_str());
886  UsageError("Usage: patchoat [options]...");
887  UsageError("");
888  UsageError("  --instruction-set=<isa>: Specifies the instruction set the patched code is");
889  UsageError("      compiled for. Required if you use --input-oat-location");
890  UsageError("");
891  UsageError("  --input-oat-file=<file.oat>: Specifies the exact filename of the oat file to be");
892  UsageError("      patched.");
893  UsageError("");
894  UsageError("  --input-oat-fd=<file-descriptor>: Specifies the file-descriptor of the oat file");
895  UsageError("      to be patched.");
896  UsageError("");
897  UsageError("  --input-oat-location=<file.oat>: Specifies the 'location' to read the patched");
898  UsageError("      oat file from. If used one must also supply the --instruction-set");
899  UsageError("");
900  UsageError("  --input-image-location=<file.art>: Specifies the 'location' of the image file to");
901  UsageError("      be patched. If --instruction-set is not given it will use the instruction set");
902  UsageError("      extracted from the --input-oat-file.");
903  UsageError("");
904  UsageError("  --output-oat-file=<file.oat>: Specifies the exact file to write the patched oat");
905  UsageError("      file to.");
906  UsageError("");
907  UsageError("  --output-oat-fd=<file-descriptor>: Specifies the file-descriptor to write the");
908  UsageError("      the patched oat file to.");
909  UsageError("");
910  UsageError("  --output-image-file=<file.art>: Specifies the exact file to write the patched");
911  UsageError("      image file to.");
912  UsageError("");
913  UsageError("  --output-image-fd=<file-descriptor>: Specifies the file-descriptor to write the");
914  UsageError("      the patched image file to.");
915  UsageError("");
916  UsageError("  --orig-base-offset=<original-base-offset>: Specify the base offset the input file");
917  UsageError("      was compiled with. This is needed if one is specifying a --base-offset");
918  UsageError("");
919  UsageError("  --base-offset=<new-base-offset>: Specify the base offset we will repatch the");
920  UsageError("      given files to use. This requires that --orig-base-offset is also given.");
921  UsageError("");
922  UsageError("  --base-offset-delta=<delta>: Specify the amount to change the old base-offset by.");
923  UsageError("      This value may be negative.");
924  UsageError("");
925  UsageError("  --patched-image-file=<file.art>: Relocate the oat file to be the same as the");
926  UsageError("      given image file.");
927  UsageError("");
928  UsageError("  --patched-image-location=<file.art>: Relocate the oat file to be the same as the");
929  UsageError("      image at the given location. If used one must also specify the");
930  UsageError("      --instruction-set flag. It will search for this image in the same way that");
931  UsageError("      is done when loading one.");
932  UsageError("");
933  UsageError("  --lock-output: Obtain a flock on output oat file before starting.");
934  UsageError("");
935  UsageError("  --no-lock-output: Do not attempt to obtain a flock on output oat file.");
936  UsageError("");
937  UsageError("  --dump-timings: dump out patch timing information");
938  UsageError("");
939  UsageError("  --no-dump-timings: do not dump out patch timing information");
940  UsageError("");
941
942  exit(EXIT_FAILURE);
943}
944
945static bool ReadBaseDelta(const char* name, off_t* delta, std::string* error_msg) {
946  CHECK(name != nullptr);
947  CHECK(delta != nullptr);
948  std::unique_ptr<File> file;
949  if (OS::FileExists(name)) {
950    file.reset(OS::OpenFileForReading(name));
951    if (file.get() == nullptr) {
952      *error_msg = "Failed to open file %s for reading";
953      return false;
954    }
955  } else {
956    *error_msg = "File %s does not exist";
957    return false;
958  }
959  CHECK(file.get() != nullptr);
960  ImageHeader hdr;
961  if (sizeof(hdr) != file->Read(reinterpret_cast<char*>(&hdr), sizeof(hdr), 0)) {
962    *error_msg = "Failed to read file %s";
963    return false;
964  }
965  if (!hdr.IsValid()) {
966    *error_msg = "%s does not contain a valid image header.";
967    return false;
968  }
969  *delta = hdr.GetPatchDelta();
970  return true;
971}
972
973static File* CreateOrOpen(const char* name, bool* created) {
974  if (OS::FileExists(name)) {
975    *created = false;
976    return OS::OpenFileReadWrite(name);
977  } else {
978    *created = true;
979    std::unique_ptr<File> f(OS::CreateEmptyFile(name));
980    if (f.get() != nullptr) {
981      if (fchmod(f->Fd(), 0644) != 0) {
982        PLOG(ERROR) << "Unable to make " << name << " world readable";
983        TEMP_FAILURE_RETRY(unlink(name));
984        return nullptr;
985      }
986    }
987    return f.release();
988  }
989}
990
991// Either try to close the file (close=true), or erase it.
992static bool FinishFile(File* file, bool close) {
993  if (close) {
994    if (file->FlushCloseOrErase() != 0) {
995      PLOG(ERROR) << "Failed to flush and close file.";
996      return false;
997    }
998    return true;
999  } else {
1000    file->Erase();
1001    return false;
1002  }
1003}
1004
1005static int patchoat(int argc, char **argv) {
1006  InitLogging(argv);
1007  MemMap::Init();
1008  const bool debug = kIsDebugBuild;
1009  orig_argc = argc;
1010  orig_argv = argv;
1011  TimingLogger timings("patcher", false, false);
1012
1013  InitLogging(argv);
1014
1015  // Skip over the command name.
1016  argv++;
1017  argc--;
1018
1019  if (argc == 0) {
1020    Usage("No arguments specified");
1021  }
1022
1023  timings.StartTiming("Patchoat");
1024
1025  // cmd line args
1026  bool isa_set = false;
1027  InstructionSet isa = kNone;
1028  std::string input_oat_filename;
1029  std::string input_oat_location;
1030  int input_oat_fd = -1;
1031  bool have_input_oat = false;
1032  std::string input_image_location;
1033  std::string output_oat_filename;
1034  int output_oat_fd = -1;
1035  bool have_output_oat = false;
1036  std::string output_image_filename;
1037  int output_image_fd = -1;
1038  bool have_output_image = false;
1039  uintptr_t base_offset = 0;
1040  bool base_offset_set = false;
1041  uintptr_t orig_base_offset = 0;
1042  bool orig_base_offset_set = false;
1043  off_t base_delta = 0;
1044  bool base_delta_set = false;
1045  bool match_delta = false;
1046  std::string patched_image_filename;
1047  std::string patched_image_location;
1048  bool dump_timings = kIsDebugBuild;
1049  bool lock_output = true;
1050
1051  for (int i = 0; i < argc; ++i) {
1052    const StringPiece option(argv[i]);
1053    const bool log_options = false;
1054    if (log_options) {
1055      LOG(INFO) << "patchoat: option[" << i << "]=" << argv[i];
1056    }
1057    if (option.starts_with("--instruction-set=")) {
1058      isa_set = true;
1059      const char* isa_str = option.substr(strlen("--instruction-set=")).data();
1060      isa = GetInstructionSetFromString(isa_str);
1061      if (isa == kNone) {
1062        Usage("Unknown or invalid instruction set %s", isa_str);
1063      }
1064    } else if (option.starts_with("--input-oat-location=")) {
1065      if (have_input_oat) {
1066        Usage("Only one of --input-oat-file, --input-oat-location and --input-oat-fd may be used.");
1067      }
1068      have_input_oat = true;
1069      input_oat_location = option.substr(strlen("--input-oat-location=")).data();
1070    } else if (option.starts_with("--input-oat-file=")) {
1071      if (have_input_oat) {
1072        Usage("Only one of --input-oat-file, --input-oat-location and --input-oat-fd may be used.");
1073      }
1074      have_input_oat = true;
1075      input_oat_filename = option.substr(strlen("--input-oat-file=")).data();
1076    } else if (option.starts_with("--input-oat-fd=")) {
1077      if (have_input_oat) {
1078        Usage("Only one of --input-oat-file, --input-oat-location and --input-oat-fd may be used.");
1079      }
1080      have_input_oat = true;
1081      const char* oat_fd_str = option.substr(strlen("--input-oat-fd=")).data();
1082      if (!ParseInt(oat_fd_str, &input_oat_fd)) {
1083        Usage("Failed to parse --input-oat-fd argument '%s' as an integer", oat_fd_str);
1084      }
1085      if (input_oat_fd < 0) {
1086        Usage("--input-oat-fd pass a negative value %d", input_oat_fd);
1087      }
1088    } else if (option.starts_with("--input-image-location=")) {
1089      input_image_location = option.substr(strlen("--input-image-location=")).data();
1090    } else if (option.starts_with("--output-oat-file=")) {
1091      if (have_output_oat) {
1092        Usage("Only one of --output-oat-file, and --output-oat-fd may be used.");
1093      }
1094      have_output_oat = true;
1095      output_oat_filename = option.substr(strlen("--output-oat-file=")).data();
1096    } else if (option.starts_with("--output-oat-fd=")) {
1097      if (have_output_oat) {
1098        Usage("Only one of --output-oat-file, --output-oat-fd may be used.");
1099      }
1100      have_output_oat = true;
1101      const char* oat_fd_str = option.substr(strlen("--output-oat-fd=")).data();
1102      if (!ParseInt(oat_fd_str, &output_oat_fd)) {
1103        Usage("Failed to parse --output-oat-fd argument '%s' as an integer", oat_fd_str);
1104      }
1105      if (output_oat_fd < 0) {
1106        Usage("--output-oat-fd pass a negative value %d", output_oat_fd);
1107      }
1108    } else if (option.starts_with("--output-image-file=")) {
1109      if (have_output_image) {
1110        Usage("Only one of --output-image-file, and --output-image-fd may be used.");
1111      }
1112      have_output_image = true;
1113      output_image_filename = option.substr(strlen("--output-image-file=")).data();
1114    } else if (option.starts_with("--output-image-fd=")) {
1115      if (have_output_image) {
1116        Usage("Only one of --output-image-file, and --output-image-fd may be used.");
1117      }
1118      have_output_image = true;
1119      const char* image_fd_str = option.substr(strlen("--output-image-fd=")).data();
1120      if (!ParseInt(image_fd_str, &output_image_fd)) {
1121        Usage("Failed to parse --output-image-fd argument '%s' as an integer", image_fd_str);
1122      }
1123      if (output_image_fd < 0) {
1124        Usage("--output-image-fd pass a negative value %d", output_image_fd);
1125      }
1126    } else if (option.starts_with("--orig-base-offset=")) {
1127      const char* orig_base_offset_str = option.substr(strlen("--orig-base-offset=")).data();
1128      orig_base_offset_set = true;
1129      if (!ParseUint(orig_base_offset_str, &orig_base_offset)) {
1130        Usage("Failed to parse --orig-base-offset argument '%s' as an uintptr_t",
1131              orig_base_offset_str);
1132      }
1133    } else if (option.starts_with("--base-offset=")) {
1134      const char* base_offset_str = option.substr(strlen("--base-offset=")).data();
1135      base_offset_set = true;
1136      if (!ParseUint(base_offset_str, &base_offset)) {
1137        Usage("Failed to parse --base-offset argument '%s' as an uintptr_t", base_offset_str);
1138      }
1139    } else if (option.starts_with("--base-offset-delta=")) {
1140      const char* base_delta_str = option.substr(strlen("--base-offset-delta=")).data();
1141      base_delta_set = true;
1142      if (!ParseInt(base_delta_str, &base_delta)) {
1143        Usage("Failed to parse --base-offset-delta argument '%s' as an off_t", base_delta_str);
1144      }
1145    } else if (option.starts_with("--patched-image-location=")) {
1146      patched_image_location = option.substr(strlen("--patched-image-location=")).data();
1147    } else if (option.starts_with("--patched-image-file=")) {
1148      patched_image_filename = option.substr(strlen("--patched-image-file=")).data();
1149    } else if (option == "--lock-output") {
1150      lock_output = true;
1151    } else if (option == "--no-lock-output") {
1152      lock_output = false;
1153    } else if (option == "--dump-timings") {
1154      dump_timings = true;
1155    } else if (option == "--no-dump-timings") {
1156      dump_timings = false;
1157    } else {
1158      Usage("Unknown argument %s", option.data());
1159    }
1160  }
1161
1162  {
1163    // Only 1 of these may be set.
1164    uint32_t cnt = 0;
1165    cnt += (base_delta_set) ? 1 : 0;
1166    cnt += (base_offset_set && orig_base_offset_set) ? 1 : 0;
1167    cnt += (!patched_image_filename.empty()) ? 1 : 0;
1168    cnt += (!patched_image_location.empty()) ? 1 : 0;
1169    if (cnt > 1) {
1170      Usage("Only one of --base-offset/--orig-base-offset, --base-offset-delta, "
1171            "--patched-image-filename or --patched-image-location may be used.");
1172    } else if (cnt == 0) {
1173      Usage("Must specify --base-offset-delta, --base-offset and --orig-base-offset, "
1174            "--patched-image-location or --patched-image-file");
1175    }
1176  }
1177
1178  if (have_input_oat != have_output_oat) {
1179    Usage("Either both input and output oat must be supplied or niether must be.");
1180  }
1181
1182  if ((!input_image_location.empty()) != have_output_image) {
1183    Usage("Either both input and output image must be supplied or niether must be.");
1184  }
1185
1186  // We know we have both the input and output so rename for clarity.
1187  bool have_image_files = have_output_image;
1188  bool have_oat_files = have_output_oat;
1189
1190  if (!have_oat_files && !have_image_files) {
1191    Usage("Must be patching either an oat or an image file or both.");
1192  }
1193
1194  if (!have_oat_files && !isa_set) {
1195    Usage("Must include ISA if patching an image file without an oat file.");
1196  }
1197
1198  if (!input_oat_location.empty()) {
1199    if (!isa_set) {
1200      Usage("specifying a location requires specifying an instruction set");
1201    }
1202    if (!LocationToFilename(input_oat_location, isa, &input_oat_filename)) {
1203      Usage("Unable to find filename for input oat location %s", input_oat_location.c_str());
1204    }
1205    if (debug) {
1206      LOG(INFO) << "Using input-oat-file " << input_oat_filename;
1207    }
1208  }
1209  if (!patched_image_location.empty()) {
1210    if (!isa_set) {
1211      Usage("specifying a location requires specifying an instruction set");
1212    }
1213    std::string system_filename;
1214    bool has_system = false;
1215    std::string cache_filename;
1216    bool has_cache = false;
1217    bool has_android_data_unused = false;
1218    bool is_global_cache = false;
1219    if (!gc::space::ImageSpace::FindImageFilename(patched_image_location.c_str(), isa,
1220                                                  &system_filename, &has_system, &cache_filename,
1221                                                  &has_android_data_unused, &has_cache,
1222                                                  &is_global_cache)) {
1223      Usage("Unable to determine image file for location %s", patched_image_location.c_str());
1224    }
1225    if (has_cache) {
1226      patched_image_filename = cache_filename;
1227    } else if (has_system) {
1228      LOG(WARNING) << "Only image file found was in /system for image location "
1229                   << patched_image_location;
1230      patched_image_filename = system_filename;
1231    } else {
1232      Usage("Unable to determine image file for location %s", patched_image_location.c_str());
1233    }
1234    if (debug) {
1235      LOG(INFO) << "Using patched-image-file " << patched_image_filename;
1236    }
1237  }
1238
1239  if (!base_delta_set) {
1240    if (orig_base_offset_set && base_offset_set) {
1241      base_delta_set = true;
1242      base_delta = base_offset - orig_base_offset;
1243    } else if (!patched_image_filename.empty()) {
1244      if (have_image_files) {
1245        Usage("--patched-image-location should not be used when patching other images");
1246      }
1247      base_delta_set = true;
1248      match_delta = true;
1249      std::string error_msg;
1250      if (!ReadBaseDelta(patched_image_filename.c_str(), &base_delta, &error_msg)) {
1251        Usage(error_msg.c_str(), patched_image_filename.c_str());
1252      }
1253    } else {
1254      if (base_offset_set) {
1255        Usage("Unable to determine original base offset.");
1256      } else {
1257        Usage("Must supply a desired new offset or delta.");
1258      }
1259    }
1260  }
1261
1262  if (!IsAligned<kPageSize>(base_delta)) {
1263    Usage("Base offset/delta must be alligned to a pagesize (0x%08x) boundary.", kPageSize);
1264  }
1265
1266  // Do we need to cleanup output files if we fail?
1267  bool new_image_out = false;
1268  bool new_oat_out = false;
1269
1270  std::unique_ptr<File> input_oat;
1271  std::unique_ptr<File> output_oat;
1272  std::unique_ptr<File> output_image;
1273
1274  if (have_image_files) {
1275    CHECK(!input_image_location.empty());
1276
1277    if (output_image_fd != -1) {
1278      if (output_image_filename.empty()) {
1279        output_image_filename = "output-image-file";
1280      }
1281      output_image.reset(new File(output_image_fd, output_image_filename, true));
1282    } else {
1283      CHECK(!output_image_filename.empty());
1284      output_image.reset(CreateOrOpen(output_image_filename.c_str(), &new_image_out));
1285    }
1286  } else {
1287    CHECK(output_image_filename.empty() && output_image_fd == -1 && input_image_location.empty());
1288  }
1289
1290  if (have_oat_files) {
1291    if (input_oat_fd != -1) {
1292      if (input_oat_filename.empty()) {
1293        input_oat_filename = "input-oat-file";
1294      }
1295      input_oat.reset(new File(input_oat_fd, input_oat_filename, false));
1296      if (input_oat_fd == output_oat_fd) {
1297        input_oat.get()->DisableAutoClose();
1298      }
1299      if (input_oat == nullptr) {
1300        // Unlikely, but ensure exhaustive logging in non-0 exit code case
1301        LOG(ERROR) << "Failed to open input oat file by its FD" << input_oat_fd;
1302      }
1303    } else {
1304      CHECK(!input_oat_filename.empty());
1305      input_oat.reset(OS::OpenFileForReading(input_oat_filename.c_str()));
1306      if (input_oat == nullptr) {
1307        int err = errno;
1308        LOG(ERROR) << "Failed to open input oat file " << input_oat_filename
1309                   << ": " << strerror(err) << "(" << err << ")";
1310      }
1311    }
1312
1313    if (output_oat_fd != -1) {
1314      if (output_oat_filename.empty()) {
1315        output_oat_filename = "output-oat-file";
1316      }
1317      output_oat.reset(new File(output_oat_fd, output_oat_filename, true));
1318      if (output_oat == nullptr) {
1319        // Unlikely, but ensure exhaustive logging in non-0 exit code case
1320        LOG(ERROR) << "Failed to open output oat file by its FD" << output_oat_fd;
1321      }
1322    } else {
1323      CHECK(!output_oat_filename.empty());
1324      output_oat.reset(CreateOrOpen(output_oat_filename.c_str(), &new_oat_out));
1325      if (output_oat == nullptr) {
1326        int err = errno;
1327        LOG(ERROR) << "Failed to open output oat file " << output_oat_filename
1328                   << ": " << strerror(err) << "(" << err << ")";
1329      }
1330    }
1331  }
1332
1333  // TODO: get rid of this.
1334  auto cleanup = [&output_image_filename, &output_oat_filename,
1335                  &new_oat_out, &new_image_out, &timings, &dump_timings](bool success) {
1336    timings.EndTiming();
1337    if (!success) {
1338      if (new_oat_out) {
1339        CHECK(!output_oat_filename.empty());
1340        TEMP_FAILURE_RETRY(unlink(output_oat_filename.c_str()));
1341      }
1342      if (new_image_out) {
1343        CHECK(!output_image_filename.empty());
1344        TEMP_FAILURE_RETRY(unlink(output_image_filename.c_str()));
1345      }
1346    }
1347    if (dump_timings) {
1348      LOG(INFO) << Dumpable<TimingLogger>(timings);
1349    }
1350
1351    if (kIsDebugBuild) {
1352      LOG(INFO) << "Cleaning up.. success? " << success;
1353    }
1354  };
1355
1356  if (have_oat_files && (input_oat.get() == nullptr || output_oat.get() == nullptr)) {
1357    LOG(ERROR) << "Failed to open input/output oat files";
1358    cleanup(false);
1359    return EXIT_FAILURE;
1360  } else if (have_image_files && output_image.get() == nullptr) {
1361    LOG(ERROR) << "Failed to open output image file";
1362    cleanup(false);
1363    return EXIT_FAILURE;
1364  }
1365
1366  if (match_delta) {
1367    CHECK(!have_image_files);  // We will not do this with images.
1368    std::string error_msg;
1369    // Figure out what the current delta is so we can match it to the desired delta.
1370    std::unique_ptr<ElfFile> elf(ElfFile::Open(input_oat.get(), PROT_READ, MAP_PRIVATE,
1371                                               &error_msg));
1372    off_t current_delta = 0;
1373    if (elf.get() == nullptr) {
1374      LOG(ERROR) << "unable to open oat file " << input_oat->GetPath() << " : " << error_msg;
1375      cleanup(false);
1376      return EXIT_FAILURE;
1377    } else if (!ReadOatPatchDelta(elf.get(), &current_delta, &error_msg)) {
1378      LOG(ERROR) << "Unable to get current delta: " << error_msg;
1379      cleanup(false);
1380      return EXIT_FAILURE;
1381    }
1382    // Before this line base_delta is the desired final delta. We need it to be the actual amount to
1383    // change everything by. We subtract the current delta from it to make it this.
1384    base_delta -= current_delta;
1385    if (!IsAligned<kPageSize>(base_delta)) {
1386      LOG(ERROR) << "Given image file was relocated by an illegal delta";
1387      cleanup(false);
1388      return false;
1389    }
1390  }
1391
1392  if (debug) {
1393    LOG(INFO) << "moving offset by " << base_delta
1394              << " (0x" << std::hex << base_delta << ") bytes or "
1395              << std::dec << (base_delta/kPageSize) << " pages.";
1396  }
1397
1398  // TODO: is it going to be promatic to unlink a file that was flock-ed?
1399  ScopedFlock output_oat_lock;
1400  if (lock_output) {
1401    std::string error_msg;
1402    if (have_oat_files && !output_oat_lock.Init(output_oat.get(), &error_msg)) {
1403      LOG(ERROR) << "Unable to lock output oat " << output_image->GetPath() << ": " << error_msg;
1404      cleanup(false);
1405      return EXIT_FAILURE;
1406    }
1407  }
1408
1409  bool ret;
1410  if (have_image_files && have_oat_files) {
1411    TimingLogger::ScopedTiming pt("patch image and oat", &timings);
1412    ret = PatchOat::Patch(input_oat.get(), input_image_location, base_delta,
1413                          output_oat.get(), output_image.get(), isa, &timings,
1414                          output_oat_fd >= 0,  // was it opened from FD?
1415                          new_oat_out);
1416    // The order here doesn't matter. If the first one is successfully saved and the second one
1417    // erased, ImageSpace will still detect a problem and not use the files.
1418    ret = FinishFile(output_image.get(), ret);
1419    ret = FinishFile(output_oat.get(), ret);
1420  } else if (have_oat_files) {
1421    TimingLogger::ScopedTiming pt("patch oat", &timings);
1422    ret = PatchOat::Patch(input_oat.get(), base_delta, output_oat.get(), &timings,
1423                          output_oat_fd >= 0,  // was it opened from FD?
1424                          new_oat_out);
1425    ret = FinishFile(output_oat.get(), ret);
1426  } else if (have_image_files) {
1427    TimingLogger::ScopedTiming pt("patch image", &timings);
1428    ret = PatchOat::Patch(input_image_location, base_delta, output_image.get(), isa, &timings);
1429    ret = FinishFile(output_image.get(), ret);
1430  } else {
1431    CHECK(false);
1432    ret = true;
1433  }
1434
1435  if (kIsDebugBuild) {
1436    LOG(INFO) << "Exiting with return ... " << ret;
1437  }
1438  cleanup(ret);
1439  return (ret) ? EXIT_SUCCESS : EXIT_FAILURE;
1440}
1441
1442}  // namespace art
1443
1444int main(int argc, char **argv) {
1445  return art::patchoat(argc, argv);
1446}
1447