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