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