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