patchoat.cc revision 4303ba97313458491e038d78efa041d41cf7bb43
1b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato/*
2b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato * Copyright (C) 2014 The Android Open Source Project
3b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato *
4b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato * Licensed under the Apache License, Version 2.0 (the "License");
52270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom * you may not use this file except in compliance with the License.
6b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato * You may obtain a copy of the License at
7b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato *
8b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato *      http://www.apache.org/licenses/LICENSE-2.0
9b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato *
10b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato * Unless required by applicable law or agreed to in writing, software
11b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato * distributed under the License is distributed on an "AS IS" BASIS,
12b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato * See the License for the specific language governing permissions and
14b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato * limitations under the License.
15b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato */
16b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato#include "patchoat.h"
17b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato
18b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato#include <stdio.h>
19b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato#include <stdlib.h>
20b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato#include <sys/file.h>
21b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato#include <sys/stat.h>
22b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato#include <unistd.h>
23b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato
242270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom#include <string>
25b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato#include <vector>
26b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato
27b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato#include "base/dumpable.h"
282270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom#include "base/scoped_flock.h"
29b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato#include "base/stringpiece.h"
30b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato#include "base/stringprintf.h"
31b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato#include "base/unix_file/fd_file.h"
32b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato#include "elf_utils.h"
33b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato#include "elf_file.h"
342270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom#include "elf_file_impl.h"
352270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom#include "gc/space/image_space.h"
362270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom#include "image.h"
372270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom#include "mirror/art_field-inl.h"
382270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom#include "mirror/art_method-inl.h"
392270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom#include "mirror/object-inl.h"
402270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom#include "mirror/reference.h"
412270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom#include "noop_compiler_callbacks.h"
422270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom#include "offsets.h"
432270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom#include "os.h"
442270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom#include "runtime.h"
452270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom#include "scoped_thread_state_change.h"
462270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom#include "thread.h"
472270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom#include "utils.h"
482270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom
492270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstromnamespace art {
50b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato
512270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstromstatic InstructionSet ElfISAToInstructionSet(Elf32_Word isa) {
522270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  switch (isa) {
532270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom    case EM_ARM:
542270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom      return kArm;
552270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom    case EM_AARCH64:
562270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom      return kArm64;
572270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom    case EM_386:
582270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom      return kX86;
59b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato    case EM_X86_64:
602270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom      return kX86_64;
612270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom    case EM_MIPS:
622270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom      return kMips;
632270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom    default:
642270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom      return kNone;
652270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  }
662270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom}
672270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom
682270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstromstatic bool LocationToFilename(const std::string& location, InstructionSet isa,
692270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom                               std::string* filename) {
702270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  bool has_system = false;
712270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  bool has_cache = false;
722270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  // image_location = /system/framework/boot.art
732270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  // system_image_filename = /system/framework/<image_isa>/boot.art
742270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  std::string system_filename(GetSystemImageFilename(location.c_str(), isa));
752270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  if (OS::FileExists(system_filename.c_str())) {
762270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom    has_system = true;
772270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  }
782270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom
79b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato  bool have_android_data = false;
802270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  bool dalvik_cache_exists = false;
812270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  bool is_global_cache = false;
822270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  std::string dalvik_cache;
832270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  GetDalvikCache(GetInstructionSetString(isa), false, &dalvik_cache,
842270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom                 &have_android_data, &dalvik_cache_exists, &is_global_cache);
852270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom
862270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  std::string cache_filename;
872270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  if (have_android_data && dalvik_cache_exists) {
882270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom    // Always set output location even if it does not exist,
892270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom    // so that the caller knows where to create the image.
902270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom    //
912270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom    // image_location = /system/framework/boot.art
922270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom    // *image_filename = /data/dalvik-cache/<image_isa>/boot.art
932270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom    std::string error_msg;
942270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom    if (GetDalvikCacheFilename(location.c_str(), dalvik_cache.c_str(),
952270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom                               &cache_filename, &error_msg)) {
962270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom      has_cache = true;
972270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom    }
982270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  }
992270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  if (has_system) {
1002270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom    *filename = system_filename;
1012270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom    return true;
1022270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  } else if (has_cache) {
1032270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom    *filename = cache_filename;
1042270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom    return true;
1052270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  } else {
1062270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom    return false;
1072270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  }
1082270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom}
1092270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom
1102270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrombool PatchOat::Patch(const std::string& image_location, off_t delta,
1112270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom                     File* output_image, InstructionSet isa,
112b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato                     TimingLogger* timings) {
113b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato  CHECK(Runtime::Current() == nullptr);
114b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato  CHECK(output_image != nullptr);
115b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato  CHECK_GE(output_image->Fd(), 0);
116b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato  CHECK(!image_location.empty()) << "image file must have a filename.";
117b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato  CHECK_NE(isa, kNone);
118b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato
119b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato  TimingLogger::ScopedTiming t("Runtime Setup", timings);
120b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato  const char *isa_name = GetInstructionSetString(isa);
121b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato  std::string image_filename;
122b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato  if (!LocationToFilename(image_location, isa, &image_filename)) {
123b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato    LOG(ERROR) << "Unable to find image at location " << image_location;
124b9cc48a43ed984587c939d02fba5316bf5c0df6eYing Wang    return false;
125b9cc48a43ed984587c939d02fba5316bf5c0df6eYing Wang  }
126b9cc48a43ed984587c939d02fba5316bf5c0df6eYing Wang  std::unique_ptr<File> input_image(OS::OpenFileForReading(image_filename.c_str()));
127b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato  if (input_image.get() == nullptr) {
128b9cc48a43ed984587c939d02fba5316bf5c0df6eYing Wang    LOG(ERROR) << "unable to open input image file at " << image_filename
129b9cc48a43ed984587c939d02fba5316bf5c0df6eYing Wang               << " for location " << image_location;
130b9cc48a43ed984587c939d02fba5316bf5c0df6eYing Wang    return false;
131b9cc48a43ed984587c939d02fba5316bf5c0df6eYing Wang  }
132b9cc48a43ed984587c939d02fba5316bf5c0df6eYing Wang
133b9cc48a43ed984587c939d02fba5316bf5c0df6eYing Wang  int64_t image_len = input_image->GetLength();
134b9cc48a43ed984587c939d02fba5316bf5c0df6eYing Wang  if (image_len < 0) {
135b9cc48a43ed984587c939d02fba5316bf5c0df6eYing Wang    LOG(ERROR) << "Error while getting image length";
136b9cc48a43ed984587c939d02fba5316bf5c0df6eYing Wang    return false;
137b9cc48a43ed984587c939d02fba5316bf5c0df6eYing Wang  }
138b9cc48a43ed984587c939d02fba5316bf5c0df6eYing Wang  ImageHeader image_header;
139b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato  if (sizeof(image_header) != input_image->Read(reinterpret_cast<char*>(&image_header),
140b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato                                              sizeof(image_header), 0)) {
141b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato    LOG(ERROR) << "Unable to read image header from image file " << input_image->GetPath();
142b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato    return false;
143b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato  }
144b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato
145b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato  /*bool is_image_pic = */IsImagePic(image_header, input_image->GetPath());
146b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato  // Nothing special to do right now since the image always needs to get patched.
1472270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  // Perhaps in some far-off future we may have images with relative addresses that are true-PIC.
148b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato
149b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato  // Set up the runtime
150b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato  RuntimeOptions options;
151b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato  NoopCompilerCallbacks callbacks;
152b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato  options.push_back(std::make_pair("compilercallbacks", &callbacks));
153b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato  std::string img = "-Ximage:" + image_location;
154b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato  options.push_back(std::make_pair(img.c_str(), nullptr));
155b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato  options.push_back(std::make_pair("imageinstructionset", reinterpret_cast<const void*>(isa_name)));
156b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato  if (!Runtime::Create(options, false)) {
157b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato    LOG(ERROR) << "Unable to initialize runtime";
158b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato    return false;
1592270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  }
1602270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  // Runtime::Create acquired the mutator_lock_ that is normally given away when we Runtime::Start,
161b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato  // give it away now and then switch to a more manageable ScopedObjectAccess.
162b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato  Thread::Current()->TransitionFromRunnableToSuspended(kNative);
1632270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  ScopedObjectAccess soa(Thread::Current());
1642270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom
1652270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  t.NewTiming("Image and oat Patching setup");
1662270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  // Create the map where we will write the image patches to.
1672270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  std::string error_msg;
1682270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  std::unique_ptr<MemMap> image(MemMap::MapFile(image_len, PROT_READ | PROT_WRITE, MAP_PRIVATE,
1692270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom                                                input_image->Fd(), 0,
1702270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom                                                input_image->GetPath().c_str(),
1712270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom                                                &error_msg));
1722270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  if (image.get() == nullptr) {
1732270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom    LOG(ERROR) << "unable to map image file " << input_image->GetPath() << " : " << error_msg;
1742270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom    return false;
1752270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  }
1762270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  gc::space::ImageSpace* ispc = Runtime::Current()->GetHeap()->GetImageSpace();
1772270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom
1782270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  PatchOat p(isa, image.release(), ispc->GetLiveBitmap(), ispc->GetMemMap(),
1792270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom             delta, timings);
1802270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  t.NewTiming("Patching files");
1812270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  if (!p.PatchImage()) {
1822270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom    LOG(ERROR) << "Failed to patch image file " << input_image->GetPath();
1832270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom    return false;
1842270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  }
1852270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom
186b9cc48a43ed984587c939d02fba5316bf5c0df6eYing Wang  t.NewTiming("Writing files");
187b9cc48a43ed984587c939d02fba5316bf5c0df6eYing Wang  if (!p.WriteImage(output_image)) {
188b9cc48a43ed984587c939d02fba5316bf5c0df6eYing Wang    return false;
189b9cc48a43ed984587c939d02fba5316bf5c0df6eYing Wang  }
190b9cc48a43ed984587c939d02fba5316bf5c0df6eYing Wang  return true;
191b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato}
1922270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom
1932270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrombool PatchOat::Patch(File* input_oat, const std::string& image_location, off_t delta,
1942270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom                     File* output_oat, File* output_image, InstructionSet isa,
1952270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom                     TimingLogger* timings,
196b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato                     bool output_oat_opened_from_fd,
1972270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom                     bool new_oat_out) {
1982270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  CHECK(Runtime::Current() == nullptr);
199b9cc48a43ed984587c939d02fba5316bf5c0df6eYing Wang  CHECK(output_image != nullptr);
2002270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  CHECK_GE(output_image->Fd(), 0);
2012270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  CHECK(input_oat != nullptr);
2022270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  CHECK(output_oat != nullptr);
2032270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  CHECK_GE(input_oat->Fd(), 0);
2042270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  CHECK_GE(output_oat->Fd(), 0);
2052270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  CHECK(!image_location.empty()) << "image file must have a filename.";
2062270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom
2072270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  TimingLogger::ScopedTiming t("Runtime Setup", timings);
2082270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom
2092270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  if (isa == kNone) {
2102270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom    Elf32_Ehdr elf_hdr;
2112270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom    if (sizeof(elf_hdr) != input_oat->Read(reinterpret_cast<char*>(&elf_hdr), sizeof(elf_hdr), 0)) {
2122270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom      LOG(ERROR) << "unable to read elf header";
2132270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom      return false;
2142270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom    }
2152270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom    isa = ElfISAToInstructionSet(elf_hdr.e_machine);
2162270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  }
2172270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  const char* isa_name = GetInstructionSetString(isa);
2182270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  std::string image_filename;
2192270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  if (!LocationToFilename(image_location, isa, &image_filename)) {
2202270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom    LOG(ERROR) << "Unable to find image at location " << image_location;
2212270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom    return false;
2222270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  }
2232270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  std::unique_ptr<File> input_image(OS::OpenFileForReading(image_filename.c_str()));
2242270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  if (input_image.get() == nullptr) {
2252270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom    LOG(ERROR) << "unable to open input image file at " << image_filename
2262270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom               << " for location " << image_location;
2272270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom    return false;
2282270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  }
229b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato  int64_t image_len = input_image->GetLength();
2302270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  if (image_len < 0) {
2312270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom    LOG(ERROR) << "Error while getting image length";
2322270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom    return false;
233b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato  }
2342270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  ImageHeader image_header;
2352270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  if (sizeof(image_header) != input_image->Read(reinterpret_cast<char*>(&image_header),
2362270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom                                              sizeof(image_header), 0)) {
2372270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom    LOG(ERROR) << "Unable to read image header from image file " << input_image->GetPath();
238b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato  }
2392270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom
2402270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  /*bool is_image_pic = */IsImagePic(image_header, input_image->GetPath());
2412270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  // Nothing special to do right now since the image always needs to get patched.
2422270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  // Perhaps in some far-off future we may have images with relative addresses that are true-PIC.
2432270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom
2442270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  // Set up the runtime
2452270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  RuntimeOptions options;
2462270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  NoopCompilerCallbacks callbacks;
2472270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  options.push_back(std::make_pair("compilercallbacks", &callbacks));
2482270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  std::string img = "-Ximage:" + image_location;
2492270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  options.push_back(std::make_pair(img.c_str(), nullptr));
2502270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  options.push_back(std::make_pair("imageinstructionset", reinterpret_cast<const void*>(isa_name)));
2512270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  if (!Runtime::Create(options, false)) {
2522270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom    LOG(ERROR) << "Unable to initialize runtime";
2532270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom    return false;
2542270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  }
2552270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  // Runtime::Create acquired the mutator_lock_ that is normally given away when we Runtime::Start,
2562270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  // give it away now and then switch to a more manageable ScopedObjectAccess.
2572270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  Thread::Current()->TransitionFromRunnableToSuspended(kNative);
2582270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  ScopedObjectAccess soa(Thread::Current());
2592270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom
2602270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  t.NewTiming("Image and oat Patching setup");
2612270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  // Create the map where we will write the image patches to.
2622270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  std::string error_msg;
2632270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  std::unique_ptr<MemMap> image(MemMap::MapFile(image_len, PROT_READ | PROT_WRITE, MAP_PRIVATE,
2642270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom                                                input_image->Fd(), 0,
2652270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom                                                input_image->GetPath().c_str(),
2662270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom                                                &error_msg));
2672270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  if (image.get() == nullptr) {
2682270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom    LOG(ERROR) << "unable to map image file " << input_image->GetPath() << " : " << error_msg;
269b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato    return false;
2702270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  }
2712270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  gc::space::ImageSpace* ispc = Runtime::Current()->GetHeap()->GetImageSpace();
2722270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom
2732270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  std::unique_ptr<ElfFile> elf(ElfFile::Open(input_oat,
274b9cc48a43ed984587c939d02fba5316bf5c0df6eYing Wang                                             PROT_READ | PROT_WRITE, MAP_PRIVATE, &error_msg));
2752270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  if (elf.get() == nullptr) {
276b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato    LOG(ERROR) << "unable to open oat file " << input_oat->GetPath() << " : " << error_msg;
2772270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom    return false;
2782270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  }
279b9cc48a43ed984587c939d02fba5316bf5c0df6eYing Wang
2802270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  bool skip_patching_oat = false;
2812270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  MaybePic is_oat_pic = IsOatPic(elf.get());
2822270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  if (is_oat_pic >= ERROR_FIRST) {
2832270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom    // Error logged by IsOatPic
2842270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom    return false;
2852270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  } else if (is_oat_pic == PIC) {
2862270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom    // Do not need to do ELF-file patching. Create a symlink and skip the ELF patching.
2872270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom    if (!ReplaceOatFileWithSymlink(input_oat->GetPath(),
2882270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom                                   output_oat->GetPath(),
2892270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom                                   output_oat_opened_from_fd,
2902270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom                                   new_oat_out)) {
291b9cc48a43ed984587c939d02fba5316bf5c0df6eYing Wang      // Errors already logged by above call.
2922270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom      return false;
2932270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom    }
2942270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom    // Don't patch the OAT, since we just symlinked it. Image still needs patching.
2952270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom    skip_patching_oat = true;
2962270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  } else {
2972270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom    CHECK(is_oat_pic == NOT_PIC);
2982270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  }
2992270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom
3002270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  PatchOat p(isa, elf.release(), image.release(), ispc->GetLiveBitmap(), ispc->GetMemMap(),
3012270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom             delta, timings);
3022270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  t.NewTiming("Patching files");
3032270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  if (!skip_patching_oat && !p.PatchElf()) {
3042270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom    LOG(ERROR) << "Failed to patch oat file " << input_oat->GetPath();
3052270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom    return false;
3062270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  }
3072270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  if (!p.PatchImage()) {
3082270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom    LOG(ERROR) << "Failed to patch image file " << input_image->GetPath();
3092270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom    return false;
3102270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  }
3112270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom
3122270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  t.NewTiming("Writing files");
3132270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  if (!skip_patching_oat && !p.WriteElf(output_oat)) {
3142270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom    LOG(ERROR) << "Failed to write oat file " << input_oat->GetPath();
315b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato    return false;
3162270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  }
3172270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  if (!p.WriteImage(output_image)) {
3182270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom    LOG(ERROR) << "Failed to write image file " << input_image->GetPath();
319b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato    return false;
3202270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  }
3212270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  return true;
3222270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom}
3232270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom
3242270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrombool PatchOat::WriteElf(File* out) {
3252270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  TimingLogger::ScopedTiming t("Writing Elf File", timings_);
3262270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom
3272270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  CHECK(oat_file_.get() != nullptr);
3282270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  CHECK(out != nullptr);
3292270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  size_t expect = oat_file_->Size();
3302270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  if (out->WriteFully(reinterpret_cast<char*>(oat_file_->Begin()), expect) &&
3312270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom      out->SetLength(expect) == 0) {
3322270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom    return true;
3332270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom  } else {
3342270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom    LOG(ERROR) << "Writing to oat file " << out->GetPath() << " failed.";
3352270795fbe0b277bfd49f40950ecaa78583175ccBrian Carlstrom    return false;
336b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato  }
337b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato}
338b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato
339b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onoratobool PatchOat::WriteImage(File* out) {
340b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato  TimingLogger::ScopedTiming t("Writing image File", timings_);
341b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato  std::string error_msg;
342b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato
343b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato  ScopedFlock img_flock;
344b72c5c2e5482cf10117b2b25f642f7616b2326c3Joe Onorato  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(down_cast<mirror::ArtMethod*>(object), down_cast<mirror::ArtMethod*>(copy));
536  }
537}
538
539void PatchOat::FixupMethod(mirror::ArtMethod* object, mirror::ArtMethod* copy) {
540  const size_t pointer_size = InstructionSetPointerSize(isa_);
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->GetEntryPointFromPortableCompiledCodePtrSize<kVerifyNone>(pointer_size));
545  if (portable != 0) {
546    copy->SetEntryPointFromPortableCompiledCodePtrSize(reinterpret_cast<void*>(portable + delta_),
547                                                       pointer_size);
548  }
549  uintptr_t quick= reinterpret_cast<uintptr_t>(
550      object->GetEntryPointFromQuickCompiledCodePtrSize<kVerifyNone>(pointer_size));
551  if (quick != 0) {
552    copy->SetEntryPointFromQuickCompiledCodePtrSize(reinterpret_cast<void*>(quick + delta_),
553                                                    pointer_size);
554  }
555  uintptr_t interpreter = reinterpret_cast<uintptr_t>(
556      object->GetEntryPointFromInterpreterPtrSize<kVerifyNone>(pointer_size));
557  if (interpreter != 0) {
558    copy->SetEntryPointFromInterpreterPtrSize(
559        reinterpret_cast<mirror::EntryPointFromInterpreter*>(interpreter + delta_), pointer_size);
560  }
561
562  uintptr_t native_method = reinterpret_cast<uintptr_t>(
563      object->GetEntryPointFromJniPtrSize(pointer_size));
564  if (native_method != 0) {
565    copy->SetEntryPointFromJniPtrSize(reinterpret_cast<void*>(native_method + delta_),
566                                      pointer_size);
567  }
568
569  uintptr_t native_gc_map = reinterpret_cast<uintptr_t>(
570      object->GetNativeGcMapPtrSize(pointer_size));
571  if (native_gc_map != 0) {
572    copy->SetNativeGcMapPtrSize(reinterpret_cast<uint8_t*>(native_gc_map + delta_), pointer_size);
573  }
574}
575
576bool PatchOat::Patch(File* input_oat, off_t delta, File* output_oat, TimingLogger* timings,
577                     bool output_oat_opened_from_fd, bool new_oat_out) {
578  CHECK(input_oat != nullptr);
579  CHECK(output_oat != nullptr);
580  CHECK_GE(input_oat->Fd(), 0);
581  CHECK_GE(output_oat->Fd(), 0);
582  TimingLogger::ScopedTiming t("Setup Oat File Patching", timings);
583
584  std::string error_msg;
585  std::unique_ptr<ElfFile> elf(ElfFile::Open(input_oat,
586                                             PROT_READ | PROT_WRITE, MAP_PRIVATE, &error_msg));
587  if (elf.get() == nullptr) {
588    LOG(ERROR) << "unable to open oat file " << input_oat->GetPath() << " : " << error_msg;
589    return false;
590  }
591
592  MaybePic is_oat_pic = IsOatPic(elf.get());
593  if (is_oat_pic >= ERROR_FIRST) {
594    // Error logged by IsOatPic
595    return false;
596  } else if (is_oat_pic == PIC) {
597    // Do not need to do ELF-file patching. Create a symlink and skip the rest.
598    // Any errors will be logged by the function call.
599    return ReplaceOatFileWithSymlink(input_oat->GetPath(),
600                                     output_oat->GetPath(),
601                                     output_oat_opened_from_fd,
602                                     new_oat_out);
603  } else {
604    CHECK(is_oat_pic == NOT_PIC);
605  }
606
607  PatchOat p(elf.release(), delta, timings);
608  t.NewTiming("Patch Oat file");
609  if (!p.PatchElf()) {
610    return false;
611  }
612
613  t.NewTiming("Writing oat file");
614  if (!p.WriteElf(output_oat)) {
615    return false;
616  }
617  return true;
618}
619
620template <typename ElfFileImpl, typename ptr_t>
621bool PatchOat::CheckOatFile(ElfFileImpl* oat_file) {
622  auto patches_sec = oat_file->FindSectionByName(".oat_patches");
623  if (patches_sec->sh_type != SHT_OAT_PATCH) {
624    return false;
625  }
626  ptr_t* patches = reinterpret_cast<ptr_t*>(oat_file->Begin() + patches_sec->sh_offset);
627  ptr_t* patches_end = patches + (patches_sec->sh_size / sizeof(ptr_t));
628  auto oat_data_sec = oat_file->FindSectionByName(".rodata");
629  auto oat_text_sec = oat_file->FindSectionByName(".text");
630  if (oat_data_sec == nullptr) {
631    return false;
632  }
633  if (oat_text_sec == nullptr) {
634    return false;
635  }
636  if (oat_text_sec->sh_offset <= oat_data_sec->sh_offset) {
637    return false;
638  }
639
640  for (; patches < patches_end; patches++) {
641    if (oat_text_sec->sh_size <= *patches) {
642      return false;
643    }
644  }
645
646  return true;
647}
648
649template <typename ElfFileImpl>
650bool PatchOat::PatchOatHeader(ElfFileImpl* oat_file) {
651  auto rodata_sec = oat_file->FindSectionByName(".rodata");
652  if (rodata_sec == nullptr) {
653    return false;
654  }
655  OatHeader* oat_header = reinterpret_cast<OatHeader*>(oat_file->Begin() + rodata_sec->sh_offset);
656  if (!oat_header->IsValid()) {
657    LOG(ERROR) << "Elf file " << oat_file->GetFile().GetPath() << " has an invalid oat header";
658    return false;
659  }
660  oat_header->RelocateOat(delta_);
661  return true;
662}
663
664bool PatchOat::PatchElf() {
665  if (oat_file_->Is64Bit())
666    return PatchElf<ElfFileImpl64>(oat_file_->GetImpl64());
667  else
668    return PatchElf<ElfFileImpl32>(oat_file_->GetImpl32());
669}
670
671template <typename ElfFileImpl>
672bool PatchOat::PatchElf(ElfFileImpl* oat_file) {
673  TimingLogger::ScopedTiming t("Fixup Elf Text Section", timings_);
674  if (!PatchTextSection<ElfFileImpl>(oat_file)) {
675    return false;
676  }
677
678  if (!PatchOatHeader<ElfFileImpl>(oat_file)) {
679    return false;
680  }
681
682  bool need_fixup = false;
683  for (unsigned int i = 0; i < oat_file->GetProgramHeaderNum(); ++i) {
684    auto hdr = oat_file->GetProgramHeader(i);
685    if ((hdr->p_vaddr != 0 && hdr->p_vaddr != hdr->p_offset) ||
686        (hdr->p_paddr != 0 && hdr->p_paddr != hdr->p_offset)) {
687      need_fixup = true;
688      break;
689    }
690  }
691  if (!need_fixup) {
692    // This was never passed through ElfFixup so all headers/symbols just have their offset as
693    // their addr. Therefore we do not need to update these parts.
694    return true;
695  }
696
697  t.NewTiming("Fixup Elf Headers");
698  // Fixup Phdr's
699  oat_file->FixupProgramHeaders(delta_);
700
701  t.NewTiming("Fixup Section Headers");
702  // Fixup Shdr's
703  oat_file->FixupSectionHeaders(delta_);
704
705  t.NewTiming("Fixup Dynamics");
706  oat_file->FixupDynamic(delta_);
707
708  t.NewTiming("Fixup Elf Symbols");
709  // Fixup dynsym
710  if (!oat_file->FixupSymbols(delta_, true)) {
711    return false;
712  }
713  // Fixup symtab
714  if (!oat_file->FixupSymbols(delta_, false)) {
715    return false;
716  }
717
718  t.NewTiming("Fixup Debug Sections");
719  if (!oat_file->FixupDebugSections(delta_)) {
720    return false;
721  }
722
723  return true;
724}
725
726template <typename ElfFileImpl>
727bool PatchOat::PatchTextSection(ElfFileImpl* oat_file) {
728  auto patches_sec = oat_file->FindSectionByName(".oat_patches");
729  if (patches_sec == nullptr) {
730    LOG(ERROR) << ".oat_patches section not found. Aborting patch";
731    return false;
732  }
733  if (patches_sec->sh_type != SHT_OAT_PATCH) {
734    LOG(ERROR) << "Unexpected type of .oat_patches";
735    return false;
736  }
737
738  switch (patches_sec->sh_entsize) {
739    case sizeof(uint32_t):
740      return PatchTextSection<ElfFileImpl, uint32_t>(oat_file);
741    case sizeof(uint64_t):
742      return PatchTextSection<ElfFileImpl, uint64_t>(oat_file);
743    default:
744      LOG(ERROR) << ".oat_patches Entsize of " << patches_sec->sh_entsize << "bits "
745                 << "is not valid";
746      return false;
747  }
748}
749
750template <typename ElfFileImpl, typename patch_loc_t>
751bool PatchOat::PatchTextSection(ElfFileImpl* oat_file) {
752  bool oat_file_valid = CheckOatFile<ElfFileImpl, patch_loc_t>(oat_file);
753  CHECK(oat_file_valid) << "Oat file invalid";
754  auto patches_sec = oat_file->FindSectionByName(".oat_patches");
755  patch_loc_t* patches = reinterpret_cast<patch_loc_t*>(oat_file->Begin() + patches_sec->sh_offset);
756  patch_loc_t* patches_end = patches + (patches_sec->sh_size / sizeof(patch_loc_t));
757  auto oat_text_sec = oat_file->FindSectionByName(".text");
758  CHECK(oat_text_sec != nullptr);
759  uint8_t* to_patch = oat_file->Begin() + oat_text_sec->sh_offset;
760  uintptr_t to_patch_end = reinterpret_cast<uintptr_t>(to_patch) + oat_text_sec->sh_size;
761
762  for (; patches < patches_end; patches++) {
763    CHECK_LT(*patches, oat_text_sec->sh_size) << "Bad Patch";
764    uint32_t* patch_loc = reinterpret_cast<uint32_t*>(to_patch + *patches);
765    CHECK_LT(reinterpret_cast<uintptr_t>(patch_loc), to_patch_end);
766    *patch_loc += delta_;
767  }
768  return true;
769}
770
771static int orig_argc;
772static char** orig_argv;
773
774static std::string CommandLine() {
775  std::vector<std::string> command;
776  for (int i = 0; i < orig_argc; ++i) {
777    command.push_back(orig_argv[i]);
778  }
779  return Join(command, ' ');
780}
781
782static void UsageErrorV(const char* fmt, va_list ap) {
783  std::string error;
784  StringAppendV(&error, fmt, ap);
785  LOG(ERROR) << error;
786}
787
788static void UsageError(const char* fmt, ...) {
789  va_list ap;
790  va_start(ap, fmt);
791  UsageErrorV(fmt, ap);
792  va_end(ap);
793}
794
795[[noreturn]] static void Usage(const char *fmt, ...) {
796  va_list ap;
797  va_start(ap, fmt);
798  UsageErrorV(fmt, ap);
799  va_end(ap);
800
801  UsageError("Command: %s", CommandLine().c_str());
802  UsageError("Usage: patchoat [options]...");
803  UsageError("");
804  UsageError("  --instruction-set=<isa>: Specifies the instruction set the patched code is");
805  UsageError("      compiled for. Required if you use --input-oat-location");
806  UsageError("");
807  UsageError("  --input-oat-file=<file.oat>: Specifies the exact filename of the oat file to be");
808  UsageError("      patched.");
809  UsageError("");
810  UsageError("  --input-oat-fd=<file-descriptor>: Specifies the file-descriptor of the oat file");
811  UsageError("      to be patched.");
812  UsageError("");
813  UsageError("  --input-oat-location=<file.oat>: Specifies the 'location' to read the patched");
814  UsageError("      oat file from. If used one must also supply the --instruction-set");
815  UsageError("");
816  UsageError("  --input-image-location=<file.art>: Specifies the 'location' of the image file to");
817  UsageError("      be patched. If --instruction-set is not given it will use the instruction set");
818  UsageError("      extracted from the --input-oat-file.");
819  UsageError("");
820  UsageError("  --output-oat-file=<file.oat>: Specifies the exact file to write the patched oat");
821  UsageError("      file to.");
822  UsageError("");
823  UsageError("  --output-oat-fd=<file-descriptor>: Specifies the file-descriptor to write the");
824  UsageError("      the patched oat file to.");
825  UsageError("");
826  UsageError("  --output-image-file=<file.art>: Specifies the exact file to write the patched");
827  UsageError("      image file to.");
828  UsageError("");
829  UsageError("  --output-image-fd=<file-descriptor>: Specifies the file-descriptor to write the");
830  UsageError("      the patched image file to.");
831  UsageError("");
832  UsageError("  --orig-base-offset=<original-base-offset>: Specify the base offset the input file");
833  UsageError("      was compiled with. This is needed if one is specifying a --base-offset");
834  UsageError("");
835  UsageError("  --base-offset=<new-base-offset>: Specify the base offset we will repatch the");
836  UsageError("      given files to use. This requires that --orig-base-offset is also given.");
837  UsageError("");
838  UsageError("  --base-offset-delta=<delta>: Specify the amount to change the old base-offset by.");
839  UsageError("      This value may be negative.");
840  UsageError("");
841  UsageError("  --patched-image-file=<file.art>: Use the same patch delta as was used to patch");
842  UsageError("      the given image file.");
843  UsageError("");
844  UsageError("  --patched-image-location=<file.art>: Use the same patch delta as was used to");
845  UsageError("      patch the given image location. If used one must also specify the");
846  UsageError("      --instruction-set flag. It will search for this image in the same way that");
847  UsageError("      is done when loading one.");
848  UsageError("");
849  UsageError("  --lock-output: Obtain a flock on output oat file before starting.");
850  UsageError("");
851  UsageError("  --no-lock-output: Do not attempt to obtain a flock on output oat file.");
852  UsageError("");
853  UsageError("  --dump-timings: dump out patch timing information");
854  UsageError("");
855  UsageError("  --no-dump-timings: do not dump out patch timing information");
856  UsageError("");
857
858  exit(EXIT_FAILURE);
859}
860
861static bool ReadBaseDelta(const char* name, off_t* delta, std::string* error_msg) {
862  CHECK(name != nullptr);
863  CHECK(delta != nullptr);
864  std::unique_ptr<File> file;
865  if (OS::FileExists(name)) {
866    file.reset(OS::OpenFileForReading(name));
867    if (file.get() == nullptr) {
868      *error_msg = "Failed to open file %s for reading";
869      return false;
870    }
871  } else {
872    *error_msg = "File %s does not exist";
873    return false;
874  }
875  CHECK(file.get() != nullptr);
876  ImageHeader hdr;
877  if (sizeof(hdr) != file->Read(reinterpret_cast<char*>(&hdr), sizeof(hdr), 0)) {
878    *error_msg = "Failed to read file %s";
879    return false;
880  }
881  if (!hdr.IsValid()) {
882    *error_msg = "%s does not contain a valid image header.";
883    return false;
884  }
885  *delta = hdr.GetPatchDelta();
886  return true;
887}
888
889static File* CreateOrOpen(const char* name, bool* created) {
890  if (OS::FileExists(name)) {
891    *created = false;
892    return OS::OpenFileReadWrite(name);
893  } else {
894    *created = true;
895    std::unique_ptr<File> f(OS::CreateEmptyFile(name));
896    if (f.get() != nullptr) {
897      if (fchmod(f->Fd(), 0644) != 0) {
898        PLOG(ERROR) << "Unable to make " << name << " world readable";
899        TEMP_FAILURE_RETRY(unlink(name));
900        return nullptr;
901      }
902    }
903    return f.release();
904  }
905}
906
907// Either try to close the file (close=true), or erase it.
908static bool FinishFile(File* file, bool close) {
909  if (close) {
910    if (file->FlushCloseOrErase() != 0) {
911      PLOG(ERROR) << "Failed to flush and close file.";
912      return false;
913    }
914    return true;
915  } else {
916    file->Erase();
917    return false;
918  }
919}
920
921static int patchoat(int argc, char **argv) {
922  InitLogging(argv);
923  MemMap::Init();
924  const bool debug = kIsDebugBuild;
925  orig_argc = argc;
926  orig_argv = argv;
927  TimingLogger timings("patcher", false, false);
928
929  InitLogging(argv);
930
931  // Skip over the command name.
932  argv++;
933  argc--;
934
935  if (argc == 0) {
936    Usage("No arguments specified");
937  }
938
939  timings.StartTiming("Patchoat");
940
941  // cmd line args
942  bool isa_set = false;
943  InstructionSet isa = kNone;
944  std::string input_oat_filename;
945  std::string input_oat_location;
946  int input_oat_fd = -1;
947  bool have_input_oat = false;
948  std::string input_image_location;
949  std::string output_oat_filename;
950  int output_oat_fd = -1;
951  bool have_output_oat = false;
952  std::string output_image_filename;
953  int output_image_fd = -1;
954  bool have_output_image = false;
955  uintptr_t base_offset = 0;
956  bool base_offset_set = false;
957  uintptr_t orig_base_offset = 0;
958  bool orig_base_offset_set = false;
959  off_t base_delta = 0;
960  bool base_delta_set = false;
961  std::string patched_image_filename;
962  std::string patched_image_location;
963  bool dump_timings = kIsDebugBuild;
964  bool lock_output = true;
965
966  for (int i = 0; i < argc; ++i) {
967    const StringPiece option(argv[i]);
968    const bool log_options = false;
969    if (log_options) {
970      LOG(INFO) << "patchoat: option[" << i << "]=" << argv[i];
971    }
972    if (option.starts_with("--instruction-set=")) {
973      isa_set = true;
974      const char* isa_str = option.substr(strlen("--instruction-set=")).data();
975      isa = GetInstructionSetFromString(isa_str);
976      if (isa == kNone) {
977        Usage("Unknown or invalid instruction set %s", isa_str);
978      }
979    } else if (option.starts_with("--input-oat-location=")) {
980      if (have_input_oat) {
981        Usage("Only one of --input-oat-file, --input-oat-location and --input-oat-fd may be used.");
982      }
983      have_input_oat = true;
984      input_oat_location = option.substr(strlen("--input-oat-location=")).data();
985    } else if (option.starts_with("--input-oat-file=")) {
986      if (have_input_oat) {
987        Usage("Only one of --input-oat-file, --input-oat-location and --input-oat-fd may be used.");
988      }
989      have_input_oat = true;
990      input_oat_filename = option.substr(strlen("--input-oat-file=")).data();
991    } else if (option.starts_with("--input-oat-fd=")) {
992      if (have_input_oat) {
993        Usage("Only one of --input-oat-file, --input-oat-location and --input-oat-fd may be used.");
994      }
995      have_input_oat = true;
996      const char* oat_fd_str = option.substr(strlen("--input-oat-fd=")).data();
997      if (!ParseInt(oat_fd_str, &input_oat_fd)) {
998        Usage("Failed to parse --input-oat-fd argument '%s' as an integer", oat_fd_str);
999      }
1000      if (input_oat_fd < 0) {
1001        Usage("--input-oat-fd pass a negative value %d", input_oat_fd);
1002      }
1003    } else if (option.starts_with("--input-image-location=")) {
1004      input_image_location = option.substr(strlen("--input-image-location=")).data();
1005    } else if (option.starts_with("--output-oat-file=")) {
1006      if (have_output_oat) {
1007        Usage("Only one of --output-oat-file, and --output-oat-fd may be used.");
1008      }
1009      have_output_oat = true;
1010      output_oat_filename = option.substr(strlen("--output-oat-file=")).data();
1011    } else if (option.starts_with("--output-oat-fd=")) {
1012      if (have_output_oat) {
1013        Usage("Only one of --output-oat-file, --output-oat-fd may be used.");
1014      }
1015      have_output_oat = true;
1016      const char* oat_fd_str = option.substr(strlen("--output-oat-fd=")).data();
1017      if (!ParseInt(oat_fd_str, &output_oat_fd)) {
1018        Usage("Failed to parse --output-oat-fd argument '%s' as an integer", oat_fd_str);
1019      }
1020      if (output_oat_fd < 0) {
1021        Usage("--output-oat-fd pass a negative value %d", output_oat_fd);
1022      }
1023    } else if (option.starts_with("--output-image-file=")) {
1024      if (have_output_image) {
1025        Usage("Only one of --output-image-file, and --output-image-fd may be used.");
1026      }
1027      have_output_image = true;
1028      output_image_filename = option.substr(strlen("--output-image-file=")).data();
1029    } else if (option.starts_with("--output-image-fd=")) {
1030      if (have_output_image) {
1031        Usage("Only one of --output-image-file, and --output-image-fd may be used.");
1032      }
1033      have_output_image = true;
1034      const char* image_fd_str = option.substr(strlen("--output-image-fd=")).data();
1035      if (!ParseInt(image_fd_str, &output_image_fd)) {
1036        Usage("Failed to parse --output-image-fd argument '%s' as an integer", image_fd_str);
1037      }
1038      if (output_image_fd < 0) {
1039        Usage("--output-image-fd pass a negative value %d", output_image_fd);
1040      }
1041    } else if (option.starts_with("--orig-base-offset=")) {
1042      const char* orig_base_offset_str = option.substr(strlen("--orig-base-offset=")).data();
1043      orig_base_offset_set = true;
1044      if (!ParseUint(orig_base_offset_str, &orig_base_offset)) {
1045        Usage("Failed to parse --orig-base-offset argument '%s' as an uintptr_t",
1046              orig_base_offset_str);
1047      }
1048    } else if (option.starts_with("--base-offset=")) {
1049      const char* base_offset_str = option.substr(strlen("--base-offset=")).data();
1050      base_offset_set = true;
1051      if (!ParseUint(base_offset_str, &base_offset)) {
1052        Usage("Failed to parse --base-offset argument '%s' as an uintptr_t", base_offset_str);
1053      }
1054    } else if (option.starts_with("--base-offset-delta=")) {
1055      const char* base_delta_str = option.substr(strlen("--base-offset-delta=")).data();
1056      base_delta_set = true;
1057      if (!ParseInt(base_delta_str, &base_delta)) {
1058        Usage("Failed to parse --base-offset-delta argument '%s' as an off_t", base_delta_str);
1059      }
1060    } else if (option.starts_with("--patched-image-location=")) {
1061      patched_image_location = option.substr(strlen("--patched-image-location=")).data();
1062    } else if (option.starts_with("--patched-image-file=")) {
1063      patched_image_filename = option.substr(strlen("--patched-image-file=")).data();
1064    } else if (option == "--lock-output") {
1065      lock_output = true;
1066    } else if (option == "--no-lock-output") {
1067      lock_output = false;
1068    } else if (option == "--dump-timings") {
1069      dump_timings = true;
1070    } else if (option == "--no-dump-timings") {
1071      dump_timings = false;
1072    } else {
1073      Usage("Unknown argument %s", option.data());
1074    }
1075  }
1076
1077  {
1078    // Only 1 of these may be set.
1079    uint32_t cnt = 0;
1080    cnt += (base_delta_set) ? 1 : 0;
1081    cnt += (base_offset_set && orig_base_offset_set) ? 1 : 0;
1082    cnt += (!patched_image_filename.empty()) ? 1 : 0;
1083    cnt += (!patched_image_location.empty()) ? 1 : 0;
1084    if (cnt > 1) {
1085      Usage("Only one of --base-offset/--orig-base-offset, --base-offset-delta, "
1086            "--patched-image-filename or --patched-image-location may be used.");
1087    } else if (cnt == 0) {
1088      Usage("Must specify --base-offset-delta, --base-offset and --orig-base-offset, "
1089            "--patched-image-location or --patched-image-file");
1090    }
1091  }
1092
1093  if (have_input_oat != have_output_oat) {
1094    Usage("Either both input and output oat must be supplied or niether must be.");
1095  }
1096
1097  if ((!input_image_location.empty()) != have_output_image) {
1098    Usage("Either both input and output image must be supplied or niether must be.");
1099  }
1100
1101  // We know we have both the input and output so rename for clarity.
1102  bool have_image_files = have_output_image;
1103  bool have_oat_files = have_output_oat;
1104
1105  if (!have_oat_files && !have_image_files) {
1106    Usage("Must be patching either an oat or an image file or both.");
1107  }
1108
1109  if (!have_oat_files && !isa_set) {
1110    Usage("Must include ISA if patching an image file without an oat file.");
1111  }
1112
1113  if (!input_oat_location.empty()) {
1114    if (!isa_set) {
1115      Usage("specifying a location requires specifying an instruction set");
1116    }
1117    if (!LocationToFilename(input_oat_location, isa, &input_oat_filename)) {
1118      Usage("Unable to find filename for input oat location %s", input_oat_location.c_str());
1119    }
1120    if (debug) {
1121      LOG(INFO) << "Using input-oat-file " << input_oat_filename;
1122    }
1123  }
1124  if (!patched_image_location.empty()) {
1125    if (!isa_set) {
1126      Usage("specifying a location requires specifying an instruction set");
1127    }
1128    std::string system_filename;
1129    bool has_system = false;
1130    std::string cache_filename;
1131    bool has_cache = false;
1132    bool has_android_data_unused = false;
1133    bool is_global_cache = false;
1134    if (!gc::space::ImageSpace::FindImageFilename(patched_image_location.c_str(), isa,
1135                                                  &system_filename, &has_system, &cache_filename,
1136                                                  &has_android_data_unused, &has_cache,
1137                                                  &is_global_cache)) {
1138      Usage("Unable to determine image file for location %s", patched_image_location.c_str());
1139    }
1140    if (has_cache) {
1141      patched_image_filename = cache_filename;
1142    } else if (has_system) {
1143      LOG(WARNING) << "Only image file found was in /system for image location "
1144                   << patched_image_location;
1145      patched_image_filename = system_filename;
1146    } else {
1147      Usage("Unable to determine image file for location %s", patched_image_location.c_str());
1148    }
1149    if (debug) {
1150      LOG(INFO) << "Using patched-image-file " << patched_image_filename;
1151    }
1152  }
1153
1154  if (!base_delta_set) {
1155    if (orig_base_offset_set && base_offset_set) {
1156      base_delta_set = true;
1157      base_delta = base_offset - orig_base_offset;
1158    } else if (!patched_image_filename.empty()) {
1159      base_delta_set = true;
1160      std::string error_msg;
1161      if (!ReadBaseDelta(patched_image_filename.c_str(), &base_delta, &error_msg)) {
1162        Usage(error_msg.c_str(), patched_image_filename.c_str());
1163      }
1164    } else {
1165      if (base_offset_set) {
1166        Usage("Unable to determine original base offset.");
1167      } else {
1168        Usage("Must supply a desired new offset or delta.");
1169      }
1170    }
1171  }
1172
1173  if (!IsAligned<kPageSize>(base_delta)) {
1174    Usage("Base offset/delta must be alligned to a pagesize (0x%08x) boundary.", kPageSize);
1175  }
1176
1177  // Do we need to cleanup output files if we fail?
1178  bool new_image_out = false;
1179  bool new_oat_out = false;
1180
1181  std::unique_ptr<File> input_oat;
1182  std::unique_ptr<File> output_oat;
1183  std::unique_ptr<File> output_image;
1184
1185  if (have_image_files) {
1186    CHECK(!input_image_location.empty());
1187
1188    if (output_image_fd != -1) {
1189      if (output_image_filename.empty()) {
1190        output_image_filename = "output-image-file";
1191      }
1192      output_image.reset(new File(output_image_fd, output_image_filename, true));
1193    } else {
1194      CHECK(!output_image_filename.empty());
1195      output_image.reset(CreateOrOpen(output_image_filename.c_str(), &new_image_out));
1196    }
1197  } else {
1198    CHECK(output_image_filename.empty() && output_image_fd == -1 && input_image_location.empty());
1199  }
1200
1201  if (have_oat_files) {
1202    if (input_oat_fd != -1) {
1203      if (input_oat_filename.empty()) {
1204        input_oat_filename = "input-oat-file";
1205      }
1206      input_oat.reset(new File(input_oat_fd, input_oat_filename, false));
1207      if (input_oat == nullptr) {
1208        // Unlikely, but ensure exhaustive logging in non-0 exit code case
1209        LOG(ERROR) << "Failed to open input oat file by its FD" << input_oat_fd;
1210      }
1211    } else {
1212      CHECK(!input_oat_filename.empty());
1213      input_oat.reset(OS::OpenFileForReading(input_oat_filename.c_str()));
1214      if (input_oat == nullptr) {
1215        int err = errno;
1216        LOG(ERROR) << "Failed to open input oat file " << input_oat_filename
1217                   << ": " << strerror(err) << "(" << err << ")";
1218      }
1219    }
1220
1221    if (output_oat_fd != -1) {
1222      if (output_oat_filename.empty()) {
1223        output_oat_filename = "output-oat-file";
1224      }
1225      output_oat.reset(new File(output_oat_fd, output_oat_filename, true));
1226      if (output_oat == nullptr) {
1227        // Unlikely, but ensure exhaustive logging in non-0 exit code case
1228        LOG(ERROR) << "Failed to open output oat file by its FD" << output_oat_fd;
1229      }
1230    } else {
1231      CHECK(!output_oat_filename.empty());
1232      output_oat.reset(CreateOrOpen(output_oat_filename.c_str(), &new_oat_out));
1233      if (output_oat == nullptr) {
1234        int err = errno;
1235        LOG(ERROR) << "Failed to open output oat file " << output_oat_filename
1236                   << ": " << strerror(err) << "(" << err << ")";
1237      }
1238    }
1239  }
1240
1241  // TODO: get rid of this.
1242  auto cleanup = [&output_image_filename, &output_oat_filename,
1243                  &new_oat_out, &new_image_out, &timings, &dump_timings](bool success) {
1244    timings.EndTiming();
1245    if (!success) {
1246      if (new_oat_out) {
1247        CHECK(!output_oat_filename.empty());
1248        TEMP_FAILURE_RETRY(unlink(output_oat_filename.c_str()));
1249      }
1250      if (new_image_out) {
1251        CHECK(!output_image_filename.empty());
1252        TEMP_FAILURE_RETRY(unlink(output_image_filename.c_str()));
1253      }
1254    }
1255    if (dump_timings) {
1256      LOG(INFO) << Dumpable<TimingLogger>(timings);
1257    }
1258
1259    if (kIsDebugBuild) {
1260      LOG(INFO) << "Cleaning up.. success? " << success;
1261    }
1262  };
1263
1264  if (have_oat_files && (input_oat.get() == nullptr || output_oat.get() == nullptr)) {
1265    LOG(ERROR) << "Failed to open input/output oat files";
1266    cleanup(false);
1267    return EXIT_FAILURE;
1268  } else if (have_image_files && output_image.get() == nullptr) {
1269    LOG(ERROR) << "Failed to open output image file";
1270    cleanup(false);
1271    return EXIT_FAILURE;
1272  }
1273
1274  if (debug) {
1275    LOG(INFO) << "moving offset by " << base_delta
1276              << " (0x" << std::hex << base_delta << ") bytes or "
1277              << std::dec << (base_delta/kPageSize) << " pages.";
1278  }
1279
1280  // TODO: is it going to be promatic to unlink a file that was flock-ed?
1281  ScopedFlock output_oat_lock;
1282  if (lock_output) {
1283    std::string error_msg;
1284    if (have_oat_files && !output_oat_lock.Init(output_oat.get(), &error_msg)) {
1285      LOG(ERROR) << "Unable to lock output oat " << output_image->GetPath() << ": " << error_msg;
1286      cleanup(false);
1287      return EXIT_FAILURE;
1288    }
1289  }
1290
1291  bool ret;
1292  if (have_image_files && have_oat_files) {
1293    TimingLogger::ScopedTiming pt("patch image and oat", &timings);
1294    ret = PatchOat::Patch(input_oat.get(), input_image_location, base_delta,
1295                          output_oat.get(), output_image.get(), isa, &timings,
1296                          output_oat_fd >= 0,  // was it opened from FD?
1297                          new_oat_out);
1298    // The order here doesn't matter. If the first one is successfully saved and the second one
1299    // erased, ImageSpace will still detect a problem and not use the files.
1300    ret = ret && FinishFile(output_image.get(), ret);
1301    ret = ret && FinishFile(output_oat.get(), ret);
1302  } else if (have_oat_files) {
1303    TimingLogger::ScopedTiming pt("patch oat", &timings);
1304    ret = PatchOat::Patch(input_oat.get(), base_delta, output_oat.get(), &timings,
1305                          output_oat_fd >= 0,  // was it opened from FD?
1306                          new_oat_out);
1307    ret = ret && FinishFile(output_oat.get(), ret);
1308  } else if (have_image_files) {
1309    TimingLogger::ScopedTiming pt("patch image", &timings);
1310    ret = PatchOat::Patch(input_image_location, base_delta, output_image.get(), isa, &timings);
1311    ret = ret && FinishFile(output_image.get(), ret);
1312  } else {
1313    CHECK(false);
1314    ret = true;
1315  }
1316
1317  if (kIsDebugBuild) {
1318    LOG(INFO) << "Exiting with return ... " << ret;
1319  }
1320  cleanup(ret);
1321  return (ret) ? EXIT_SUCCESS : EXIT_FAILURE;
1322}
1323
1324}  // namespace art
1325
1326int main(int argc, char **argv) {
1327  return art::patchoat(argc, argv);
1328}
1329