153cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light/*
253cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light * Copyright (C) 2014 The Android Open Source Project
353cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light *
453cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light * Licensed under the Apache License, Version 2.0 (the "License");
553cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light * you may not use this file except in compliance with the License.
653cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light * You may obtain a copy of the License at
753cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light *
853cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light *      http://www.apache.org/licenses/LICENSE-2.0
953cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light *
1053cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light * Unless required by applicable law or agreed to in writing, software
1153cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light * distributed under the License is distributed on an "AS IS" BASIS,
1253cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1353cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light * See the License for the specific language governing permissions and
1453cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light * limitations under the License.
1553cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light */
1653cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light#include "patchoat.h"
1753cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light
1853cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light#include <stdio.h>
1953cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light#include <stdlib.h>
20a59dd80f9f48cb750d329d4d4af2d99d72b484d1Alex Light#include <sys/file.h>
2153cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light#include <sys/stat.h>
22a59dd80f9f48cb750d329d4d4af2d99d72b484d1Alex Light#include <unistd.h>
2353cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light
2453cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light#include <string>
2553cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light#include <vector>
2653cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light
27c785344b87221f5e4e6473e5b762e4e61fe65dcfMathieu Chartier#include "art_field-inl.h"
283d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier#include "art_method-inl.h"
29c7dd295a4e0cc1d15c0c96088e55a85389bade74Ian Rogers#include "base/dumpable.h"
30a59dd80f9f48cb750d329d4d4af2d99d72b484d1Alex Light#include "base/scoped_flock.h"
3153cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light#include "base/stringpiece.h"
3253cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light#include "base/stringprintf.h"
33d4c4d953035d4418126d36517e402f411d6a87f3Ian Rogers#include "base/unix_file/fd_file.h"
3453cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light#include "elf_utils.h"
3553cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light#include "elf_file.h"
3662d1ca3182a6cbb921799825f43ad36821233fd7Tong Shen#include "elf_file_impl.h"
37e63db27db913f1a88e2095a1ee8239b2bb9124e8Ian Rogers#include "gc/space/image_space.h"
3853cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light#include "image.h"
393d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier#include "mirror/abstract_method.h"
4053cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light#include "mirror/object-inl.h"
413d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier#include "mirror/method.h"
4253cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light#include "mirror/reference.h"
4353cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light#include "noop_compiler_callbacks.h"
4453cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light#include "offsets.h"
4553cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light#include "os.h"
4653cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light#include "runtime.h"
4753cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light#include "scoped_thread_state_change.h"
4853cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light#include "thread.h"
4953cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light#include "utils.h"
5053cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light
5153cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Lightnamespace art {
5253cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light
53cf4bf386ef3f527825c70e01130b9276da4f786aAlex Lightstatic bool LocationToFilename(const std::string& location, InstructionSet isa,
54cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light                               std::string* filename) {
55cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light  bool has_system = false;
56cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light  bool has_cache = false;
57cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light  // image_location = /system/framework/boot.art
5846774767fcf7780d1455e755729198648d08742eIgor Murashkin  // system_image_filename = /system/framework/<image_isa>/boot.art
59cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light  std::string system_filename(GetSystemImageFilename(location.c_str(), isa));
60cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light  if (OS::FileExists(system_filename.c_str())) {
61cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light    has_system = true;
62cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light  }
63cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light
64cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light  bool have_android_data = false;
65cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light  bool dalvik_cache_exists = false;
663c13a794845e0cf7887e33b2ec20de7e6ba85f8fAndreas Gampe  bool is_global_cache = false;
67cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light  std::string dalvik_cache;
68cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light  GetDalvikCache(GetInstructionSetString(isa), false, &dalvik_cache,
693c13a794845e0cf7887e33b2ec20de7e6ba85f8fAndreas Gampe                 &have_android_data, &dalvik_cache_exists, &is_global_cache);
70cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light
71cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light  std::string cache_filename;
72cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light  if (have_android_data && dalvik_cache_exists) {
73cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light    // Always set output location even if it does not exist,
74cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light    // so that the caller knows where to create the image.
75cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light    //
76cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light    // image_location = /system/framework/boot.art
77cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light    // *image_filename = /data/dalvik-cache/<image_isa>/boot.art
78cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light    std::string error_msg;
79cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light    if (GetDalvikCacheFilename(location.c_str(), dalvik_cache.c_str(),
80cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light                               &cache_filename, &error_msg)) {
81cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light      has_cache = true;
82cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light    }
83cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light  }
84cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light  if (has_system) {
85cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light    *filename = system_filename;
86cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light    return true;
87cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light  } else if (has_cache) {
88cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light    *filename = cache_filename;
89cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light    return true;
90cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light  } else {
91cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light    return false;
92cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light  }
93cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light}
94cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light
9553cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Lightbool PatchOat::Patch(const std::string& image_location, off_t delta,
9653cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light                     File* output_image, InstructionSet isa,
97eefbe39799126afdf7d315a79359b9da23d1cef5Alex Light                     TimingLogger* timings) {
9853cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  CHECK(Runtime::Current() == nullptr);
9953cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  CHECK(output_image != nullptr);
10053cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  CHECK_GE(output_image->Fd(), 0);
10153cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  CHECK(!image_location.empty()) << "image file must have a filename.";
10253cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  CHECK_NE(isa, kNone);
10353cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light
104eefbe39799126afdf7d315a79359b9da23d1cef5Alex Light  TimingLogger::ScopedTiming t("Runtime Setup", timings);
10553cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  const char *isa_name = GetInstructionSetString(isa);
106cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light  std::string image_filename;
107cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light  if (!LocationToFilename(image_location, isa, &image_filename)) {
108cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light    LOG(ERROR) << "Unable to find image at location " << image_location;
109cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light    return false;
110cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light  }
11153cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  std::unique_ptr<File> input_image(OS::OpenFileForReading(image_filename.c_str()));
11253cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  if (input_image.get() == nullptr) {
113cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light    LOG(ERROR) << "unable to open input image file at " << image_filename
114cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light               << " for location " << image_location;
11553cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    return false;
11653cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  }
11746774767fcf7780d1455e755729198648d08742eIgor Murashkin
11853cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  int64_t image_len = input_image->GetLength();
11953cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  if (image_len < 0) {
12053cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    LOG(ERROR) << "Error while getting image length";
12153cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    return false;
12253cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  }
12353cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  ImageHeader image_header;
12453cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  if (sizeof(image_header) != input_image->Read(reinterpret_cast<char*>(&image_header),
1253d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier                                                sizeof(image_header), 0)) {
12653cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    LOG(ERROR) << "Unable to read image header from image file " << input_image->GetPath();
12753cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    return false;
12853cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  }
12953cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light
13046774767fcf7780d1455e755729198648d08742eIgor Murashkin  /*bool is_image_pic = */IsImagePic(image_header, input_image->GetPath());
13146774767fcf7780d1455e755729198648d08742eIgor Murashkin  // Nothing special to do right now since the image always needs to get patched.
13246774767fcf7780d1455e755729198648d08742eIgor Murashkin  // Perhaps in some far-off future we may have images with relative addresses that are true-PIC.
13346774767fcf7780d1455e755729198648d08742eIgor Murashkin
13453cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  // Set up the runtime
135e63db27db913f1a88e2095a1ee8239b2bb9124e8Ian Rogers  RuntimeOptions options;
13653cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  NoopCompilerCallbacks callbacks;
13753cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  options.push_back(std::make_pair("compilercallbacks", &callbacks));
13853cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  std::string img = "-Ximage:" + image_location;
13953cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  options.push_back(std::make_pair(img.c_str(), nullptr));
14053cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  options.push_back(std::make_pair("imageinstructionset", reinterpret_cast<const void*>(isa_name)));
14153cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  if (!Runtime::Create(options, false)) {
14253cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    LOG(ERROR) << "Unable to initialize runtime";
14353cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    return false;
14453cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  }
14553cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  // Runtime::Create acquired the mutator_lock_ that is normally given away when we Runtime::Start,
14653cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  // give it away now and then switch to a more manageable ScopedObjectAccess.
14753cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  Thread::Current()->TransitionFromRunnableToSuspended(kNative);
14853cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  ScopedObjectAccess soa(Thread::Current());
14953cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light
15053cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  t.NewTiming("Image and oat Patching setup");
15153cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  // Create the map where we will write the image patches to.
152eefbe39799126afdf7d315a79359b9da23d1cef5Alex Light  std::string error_msg;
15353cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  std::unique_ptr<MemMap> image(MemMap::MapFile(image_len, PROT_READ | PROT_WRITE, MAP_PRIVATE,
15453cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light                                                input_image->Fd(), 0,
15553cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light                                                input_image->GetPath().c_str(),
15653cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light                                                &error_msg));
15753cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  if (image.get() == nullptr) {
15853cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    LOG(ERROR) << "unable to map image file " << input_image->GetPath() << " : " << error_msg;
15953cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    return false;
16053cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  }
16153cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  gc::space::ImageSpace* ispc = Runtime::Current()->GetHeap()->GetImageSpace();
16253cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light
1632d7210188805292e463be4bcf7a133b654d7e0eaMathieu Chartier  PatchOat p(isa, image.release(), ispc->GetLiveBitmap(), ispc->GetMemMap(),
16453cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light             delta, timings);
16553cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  t.NewTiming("Patching files");
16653cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  if (!p.PatchImage()) {
167a59dd80f9f48cb750d329d4d4af2d99d72b484d1Alex Light    LOG(ERROR) << "Failed to patch image file " << input_image->GetPath();
16853cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    return false;
16953cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  }
17053cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light
17153cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  t.NewTiming("Writing files");
17253cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  if (!p.WriteImage(output_image)) {
17353cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    return false;
17453cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  }
17553cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  return true;
17653cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light}
17753cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light
17846774767fcf7780d1455e755729198648d08742eIgor Murashkinbool PatchOat::Patch(File* input_oat, const std::string& image_location, off_t delta,
17953cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light                     File* output_oat, File* output_image, InstructionSet isa,
18046774767fcf7780d1455e755729198648d08742eIgor Murashkin                     TimingLogger* timings,
18146774767fcf7780d1455e755729198648d08742eIgor Murashkin                     bool output_oat_opened_from_fd,
18246774767fcf7780d1455e755729198648d08742eIgor Murashkin                     bool new_oat_out) {
18353cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  CHECK(Runtime::Current() == nullptr);
18453cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  CHECK(output_image != nullptr);
18553cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  CHECK_GE(output_image->Fd(), 0);
18653cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  CHECK(input_oat != nullptr);
18753cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  CHECK(output_oat != nullptr);
18853cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  CHECK_GE(input_oat->Fd(), 0);
18953cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  CHECK_GE(output_oat->Fd(), 0);
19053cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  CHECK(!image_location.empty()) << "image file must have a filename.";
19153cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light
192eefbe39799126afdf7d315a79359b9da23d1cef5Alex Light  TimingLogger::ScopedTiming t("Runtime Setup", timings);
19353cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light
19453cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  if (isa == kNone) {
19553cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    Elf32_Ehdr elf_hdr;
19653cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    if (sizeof(elf_hdr) != input_oat->Read(reinterpret_cast<char*>(&elf_hdr), sizeof(elf_hdr), 0)) {
19753cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      LOG(ERROR) << "unable to read elf header";
19853cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      return false;
19953cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    }
2006f6114140fbc09c5c7bec441922412635a7f7ff1Andreas Gampe    isa = GetInstructionSetFromELF(elf_hdr.e_machine, elf_hdr.e_flags);
20153cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  }
20253cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  const char* isa_name = GetInstructionSetString(isa);
203cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light  std::string image_filename;
204cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light  if (!LocationToFilename(image_location, isa, &image_filename)) {
205cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light    LOG(ERROR) << "Unable to find image at location " << image_location;
206cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light    return false;
207cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light  }
20853cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  std::unique_ptr<File> input_image(OS::OpenFileForReading(image_filename.c_str()));
20953cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  if (input_image.get() == nullptr) {
210cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light    LOG(ERROR) << "unable to open input image file at " << image_filename
211cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light               << " for location " << image_location;
21253cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    return false;
21353cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  }
21453cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  int64_t image_len = input_image->GetLength();
21553cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  if (image_len < 0) {
21653cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    LOG(ERROR) << "Error while getting image length";
21753cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    return false;
21853cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  }
21953cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  ImageHeader image_header;
22053cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  if (sizeof(image_header) != input_image->Read(reinterpret_cast<char*>(&image_header),
22153cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light                                              sizeof(image_header), 0)) {
22253cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    LOG(ERROR) << "Unable to read image header from image file " << input_image->GetPath();
22353cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  }
22453cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light
22546774767fcf7780d1455e755729198648d08742eIgor Murashkin  /*bool is_image_pic = */IsImagePic(image_header, input_image->GetPath());
22646774767fcf7780d1455e755729198648d08742eIgor Murashkin  // Nothing special to do right now since the image always needs to get patched.
22746774767fcf7780d1455e755729198648d08742eIgor Murashkin  // Perhaps in some far-off future we may have images with relative addresses that are true-PIC.
22846774767fcf7780d1455e755729198648d08742eIgor Murashkin
22953cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  // Set up the runtime
230e63db27db913f1a88e2095a1ee8239b2bb9124e8Ian Rogers  RuntimeOptions options;
23153cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  NoopCompilerCallbacks callbacks;
23253cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  options.push_back(std::make_pair("compilercallbacks", &callbacks));
23353cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  std::string img = "-Ximage:" + image_location;
23453cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  options.push_back(std::make_pair(img.c_str(), nullptr));
23553cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  options.push_back(std::make_pair("imageinstructionset", reinterpret_cast<const void*>(isa_name)));
23653cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  if (!Runtime::Create(options, false)) {
23753cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    LOG(ERROR) << "Unable to initialize runtime";
23853cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    return false;
23953cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  }
24053cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  // Runtime::Create acquired the mutator_lock_ that is normally given away when we Runtime::Start,
24153cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  // give it away now and then switch to a more manageable ScopedObjectAccess.
24253cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  Thread::Current()->TransitionFromRunnableToSuspended(kNative);
24353cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  ScopedObjectAccess soa(Thread::Current());
24453cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light
24553cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  t.NewTiming("Image and oat Patching setup");
24653cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  // Create the map where we will write the image patches to.
247eefbe39799126afdf7d315a79359b9da23d1cef5Alex Light  std::string error_msg;
24853cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  std::unique_ptr<MemMap> image(MemMap::MapFile(image_len, PROT_READ | PROT_WRITE, MAP_PRIVATE,
24953cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light                                                input_image->Fd(), 0,
25053cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light                                                input_image->GetPath().c_str(),
25153cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light                                                &error_msg));
25253cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  if (image.get() == nullptr) {
25353cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    LOG(ERROR) << "unable to map image file " << input_image->GetPath() << " : " << error_msg;
25453cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    return false;
25553cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  }
25653cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  gc::space::ImageSpace* ispc = Runtime::Current()->GetHeap()->GetImageSpace();
25753cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light
25846774767fcf7780d1455e755729198648d08742eIgor Murashkin  std::unique_ptr<ElfFile> elf(ElfFile::Open(input_oat,
25953cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light                                             PROT_READ | PROT_WRITE, MAP_PRIVATE, &error_msg));
26053cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  if (elf.get() == nullptr) {
26153cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    LOG(ERROR) << "unable to open oat file " << input_oat->GetPath() << " : " << error_msg;
26253cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    return false;
26353cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  }
26453cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light
26546774767fcf7780d1455e755729198648d08742eIgor Murashkin  bool skip_patching_oat = false;
26646774767fcf7780d1455e755729198648d08742eIgor Murashkin  MaybePic is_oat_pic = IsOatPic(elf.get());
26746774767fcf7780d1455e755729198648d08742eIgor Murashkin  if (is_oat_pic >= ERROR_FIRST) {
26846774767fcf7780d1455e755729198648d08742eIgor Murashkin    // Error logged by IsOatPic
26946774767fcf7780d1455e755729198648d08742eIgor Murashkin    return false;
27046774767fcf7780d1455e755729198648d08742eIgor Murashkin  } else if (is_oat_pic == PIC) {
27146774767fcf7780d1455e755729198648d08742eIgor Murashkin    // Do not need to do ELF-file patching. Create a symlink and skip the ELF patching.
27246774767fcf7780d1455e755729198648d08742eIgor Murashkin    if (!ReplaceOatFileWithSymlink(input_oat->GetPath(),
27346774767fcf7780d1455e755729198648d08742eIgor Murashkin                                   output_oat->GetPath(),
27446774767fcf7780d1455e755729198648d08742eIgor Murashkin                                   output_oat_opened_from_fd,
27546774767fcf7780d1455e755729198648d08742eIgor Murashkin                                   new_oat_out)) {
27646774767fcf7780d1455e755729198648d08742eIgor Murashkin      // Errors already logged by above call.
27746774767fcf7780d1455e755729198648d08742eIgor Murashkin      return false;
27846774767fcf7780d1455e755729198648d08742eIgor Murashkin    }
27946774767fcf7780d1455e755729198648d08742eIgor Murashkin    // Don't patch the OAT, since we just symlinked it. Image still needs patching.
28046774767fcf7780d1455e755729198648d08742eIgor Murashkin    skip_patching_oat = true;
28146774767fcf7780d1455e755729198648d08742eIgor Murashkin  } else {
28246774767fcf7780d1455e755729198648d08742eIgor Murashkin    CHECK(is_oat_pic == NOT_PIC);
28346774767fcf7780d1455e755729198648d08742eIgor Murashkin  }
28446774767fcf7780d1455e755729198648d08742eIgor Murashkin
2852d7210188805292e463be4bcf7a133b654d7e0eaMathieu Chartier  PatchOat p(isa, elf.release(), image.release(), ispc->GetLiveBitmap(), ispc->GetMemMap(),
28653cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light             delta, timings);
28753cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  t.NewTiming("Patching files");
28846774767fcf7780d1455e755729198648d08742eIgor Murashkin  if (!skip_patching_oat && !p.PatchElf()) {
289a59dd80f9f48cb750d329d4d4af2d99d72b484d1Alex Light    LOG(ERROR) << "Failed to patch oat file " << input_oat->GetPath();
29053cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    return false;
29153cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  }
29253cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  if (!p.PatchImage()) {
293a59dd80f9f48cb750d329d4d4af2d99d72b484d1Alex Light    LOG(ERROR) << "Failed to patch image file " << input_image->GetPath();
29453cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    return false;
29553cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  }
29653cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light
29753cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  t.NewTiming("Writing files");
29846774767fcf7780d1455e755729198648d08742eIgor Murashkin  if (!skip_patching_oat && !p.WriteElf(output_oat)) {
29946774767fcf7780d1455e755729198648d08742eIgor Murashkin    LOG(ERROR) << "Failed to write oat file " << input_oat->GetPath();
30053cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    return false;
30153cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  }
30253cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  if (!p.WriteImage(output_image)) {
30346774767fcf7780d1455e755729198648d08742eIgor Murashkin    LOG(ERROR) << "Failed to write image file " << input_image->GetPath();
30453cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    return false;
30553cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  }
30653cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  return true;
30753cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light}
30853cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light
30953cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Lightbool PatchOat::WriteElf(File* out) {
310eefbe39799126afdf7d315a79359b9da23d1cef5Alex Light  TimingLogger::ScopedTiming t("Writing Elf File", timings_);
311a59dd80f9f48cb750d329d4d4af2d99d72b484d1Alex Light
31253cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  CHECK(oat_file_.get() != nullptr);
31353cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  CHECK(out != nullptr);
31453cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  size_t expect = oat_file_->Size();
31553cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  if (out->WriteFully(reinterpret_cast<char*>(oat_file_->Begin()), expect) &&
31653cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      out->SetLength(expect) == 0) {
31753cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    return true;
31853cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  } else {
31953cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    LOG(ERROR) << "Writing to oat file " << out->GetPath() << " failed.";
32053cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    return false;
32153cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  }
32253cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light}
32353cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light
32453cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Lightbool PatchOat::WriteImage(File* out) {
325eefbe39799126afdf7d315a79359b9da23d1cef5Alex Light  TimingLogger::ScopedTiming t("Writing image File", timings_);
326a59dd80f9f48cb750d329d4d4af2d99d72b484d1Alex Light  std::string error_msg;
327a59dd80f9f48cb750d329d4d4af2d99d72b484d1Alex Light
328cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light  ScopedFlock img_flock;
329cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light  img_flock.Init(out, &error_msg);
330a59dd80f9f48cb750d329d4d4af2d99d72b484d1Alex Light
33153cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  CHECK(image_ != nullptr);
33253cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  CHECK(out != nullptr);
33353cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  size_t expect = image_->Size();
33453cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  if (out->WriteFully(reinterpret_cast<char*>(image_->Begin()), expect) &&
33553cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      out->SetLength(expect) == 0) {
33653cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    return true;
33753cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  } else {
33853cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    LOG(ERROR) << "Writing to image file " << out->GetPath() << " failed.";
33953cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    return false;
34053cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  }
34153cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light}
34253cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light
34346774767fcf7780d1455e755729198648d08742eIgor Murashkinbool PatchOat::IsImagePic(const ImageHeader& image_header, const std::string& image_path) {
34446774767fcf7780d1455e755729198648d08742eIgor Murashkin  if (!image_header.CompilePic()) {
34546774767fcf7780d1455e755729198648d08742eIgor Murashkin    if (kIsDebugBuild) {
34646774767fcf7780d1455e755729198648d08742eIgor Murashkin      LOG(INFO) << "image at location " << image_path << " was *not* compiled pic";
34746774767fcf7780d1455e755729198648d08742eIgor Murashkin    }
34846774767fcf7780d1455e755729198648d08742eIgor Murashkin    return false;
34946774767fcf7780d1455e755729198648d08742eIgor Murashkin  }
35046774767fcf7780d1455e755729198648d08742eIgor Murashkin
35146774767fcf7780d1455e755729198648d08742eIgor Murashkin  if (kIsDebugBuild) {
35246774767fcf7780d1455e755729198648d08742eIgor Murashkin    LOG(INFO) << "image at location " << image_path << " was compiled PIC";
35346774767fcf7780d1455e755729198648d08742eIgor Murashkin  }
35446774767fcf7780d1455e755729198648d08742eIgor Murashkin
35546774767fcf7780d1455e755729198648d08742eIgor Murashkin  return true;
35646774767fcf7780d1455e755729198648d08742eIgor Murashkin}
35746774767fcf7780d1455e755729198648d08742eIgor Murashkin
35846774767fcf7780d1455e755729198648d08742eIgor MurashkinPatchOat::MaybePic PatchOat::IsOatPic(const ElfFile* oat_in) {
35946774767fcf7780d1455e755729198648d08742eIgor Murashkin  if (oat_in == nullptr) {
36046774767fcf7780d1455e755729198648d08742eIgor Murashkin    LOG(ERROR) << "No ELF input oat fie available";
36146774767fcf7780d1455e755729198648d08742eIgor Murashkin    return ERROR_OAT_FILE;
36246774767fcf7780d1455e755729198648d08742eIgor Murashkin  }
36346774767fcf7780d1455e755729198648d08742eIgor Murashkin
36446774767fcf7780d1455e755729198648d08742eIgor Murashkin  const std::string& file_path = oat_in->GetFile().GetPath();
36546774767fcf7780d1455e755729198648d08742eIgor Murashkin
36646774767fcf7780d1455e755729198648d08742eIgor Murashkin  const OatHeader* oat_header = GetOatHeader(oat_in);
36746774767fcf7780d1455e755729198648d08742eIgor Murashkin  if (oat_header == nullptr) {
36846774767fcf7780d1455e755729198648d08742eIgor Murashkin    LOG(ERROR) << "Failed to find oat header in oat file " << file_path;
36946774767fcf7780d1455e755729198648d08742eIgor Murashkin    return ERROR_OAT_FILE;
37046774767fcf7780d1455e755729198648d08742eIgor Murashkin  }
37146774767fcf7780d1455e755729198648d08742eIgor Murashkin
37246774767fcf7780d1455e755729198648d08742eIgor Murashkin  if (!oat_header->IsValid()) {
37346774767fcf7780d1455e755729198648d08742eIgor Murashkin    LOG(ERROR) << "Elf file " << file_path << " has an invalid oat header";
37446774767fcf7780d1455e755729198648d08742eIgor Murashkin    return ERROR_OAT_FILE;
37546774767fcf7780d1455e755729198648d08742eIgor Murashkin  }
37646774767fcf7780d1455e755729198648d08742eIgor Murashkin
37746774767fcf7780d1455e755729198648d08742eIgor Murashkin  bool is_pic = oat_header->IsPic();
37846774767fcf7780d1455e755729198648d08742eIgor Murashkin  if (kIsDebugBuild) {
37946774767fcf7780d1455e755729198648d08742eIgor Murashkin    LOG(INFO) << "Oat file at " << file_path << " is " << (is_pic ? "PIC" : "not pic");
38046774767fcf7780d1455e755729198648d08742eIgor Murashkin  }
38146774767fcf7780d1455e755729198648d08742eIgor Murashkin
38246774767fcf7780d1455e755729198648d08742eIgor Murashkin  return is_pic ? PIC : NOT_PIC;
38346774767fcf7780d1455e755729198648d08742eIgor Murashkin}
38446774767fcf7780d1455e755729198648d08742eIgor Murashkin
38546774767fcf7780d1455e755729198648d08742eIgor Murashkinbool PatchOat::ReplaceOatFileWithSymlink(const std::string& input_oat_filename,
38646774767fcf7780d1455e755729198648d08742eIgor Murashkin                                         const std::string& output_oat_filename,
38746774767fcf7780d1455e755729198648d08742eIgor Murashkin                                         bool output_oat_opened_from_fd,
38846774767fcf7780d1455e755729198648d08742eIgor Murashkin                                         bool new_oat_out) {
38946774767fcf7780d1455e755729198648d08742eIgor Murashkin  // Need a file when we are PIC, since we symlink over it. Refusing to symlink into FD.
39046774767fcf7780d1455e755729198648d08742eIgor Murashkin  if (output_oat_opened_from_fd) {
39146774767fcf7780d1455e755729198648d08742eIgor Murashkin    // TODO: installd uses --output-oat-fd. Should we change class linking logic for PIC?
39246774767fcf7780d1455e755729198648d08742eIgor Murashkin    LOG(ERROR) << "No output oat filename specified, needs filename for when we are PIC";
39346774767fcf7780d1455e755729198648d08742eIgor Murashkin    return false;
39446774767fcf7780d1455e755729198648d08742eIgor Murashkin  }
39546774767fcf7780d1455e755729198648d08742eIgor Murashkin
39646774767fcf7780d1455e755729198648d08742eIgor Murashkin  // Image was PIC. Create symlink where the oat is supposed to go.
39746774767fcf7780d1455e755729198648d08742eIgor Murashkin  if (!new_oat_out) {
39846774767fcf7780d1455e755729198648d08742eIgor Murashkin    LOG(ERROR) << "Oat file " << output_oat_filename << " already exists, refusing to overwrite";
39946774767fcf7780d1455e755729198648d08742eIgor Murashkin    return false;
40046774767fcf7780d1455e755729198648d08742eIgor Murashkin  }
40146774767fcf7780d1455e755729198648d08742eIgor Murashkin
40246774767fcf7780d1455e755729198648d08742eIgor Murashkin  // Delete the original file, since we won't need it.
40346774767fcf7780d1455e755729198648d08742eIgor Murashkin  TEMP_FAILURE_RETRY(unlink(output_oat_filename.c_str()));
40446774767fcf7780d1455e755729198648d08742eIgor Murashkin
40546774767fcf7780d1455e755729198648d08742eIgor Murashkin  // Create a symlink from the old oat to the new oat
40646774767fcf7780d1455e755729198648d08742eIgor Murashkin  if (symlink(input_oat_filename.c_str(), output_oat_filename.c_str()) < 0) {
40746774767fcf7780d1455e755729198648d08742eIgor Murashkin    int err = errno;
40846774767fcf7780d1455e755729198648d08742eIgor Murashkin    LOG(ERROR) << "Failed to create symlink at " << output_oat_filename
40946774767fcf7780d1455e755729198648d08742eIgor Murashkin               << " error(" << err << "): " << strerror(err);
41046774767fcf7780d1455e755729198648d08742eIgor Murashkin    return false;
41146774767fcf7780d1455e755729198648d08742eIgor Murashkin  }
41246774767fcf7780d1455e755729198648d08742eIgor Murashkin
41346774767fcf7780d1455e755729198648d08742eIgor Murashkin  if (kIsDebugBuild) {
41446774767fcf7780d1455e755729198648d08742eIgor Murashkin    LOG(INFO) << "Created symlink " << output_oat_filename << " -> " << input_oat_filename;
41546774767fcf7780d1455e755729198648d08742eIgor Murashkin  }
41646774767fcf7780d1455e755729198648d08742eIgor Murashkin
41746774767fcf7780d1455e755729198648d08742eIgor Murashkin  return true;
41846774767fcf7780d1455e755729198648d08742eIgor Murashkin}
41946774767fcf7780d1455e755729198648d08742eIgor Murashkin
420c785344b87221f5e4e6473e5b762e4e61fe65dcfMathieu Chartiervoid PatchOat::PatchArtFields(const ImageHeader* image_header) {
4213d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier  const auto& section = image_header->GetImageSection(ImageHeader::kSectionArtFields);
4223d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier  for (size_t pos = 0; pos < section.Size(); pos += sizeof(ArtField)) {
4233d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier    auto* src = reinterpret_cast<ArtField*>(heap_->Begin() + section.Offset() + pos);
4243d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier    auto* dest = RelocatedCopyOf(src);
4253d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier    dest->SetDeclaringClass(RelocatedAddressOfPointer(src->GetDeclaringClass()));
4263d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier  }
4273d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier}
4283d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier
4293d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartiervoid PatchOat::PatchArtMethods(const ImageHeader* image_header) {
4303d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier  const auto& section = image_header->GetMethodsSection();
4313d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier  const size_t pointer_size = InstructionSetPointerSize(isa_);
4323d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier  size_t method_size = ArtMethod::ObjectSize(pointer_size);
4333d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier  for (size_t pos = 0; pos < section.Size(); pos += method_size) {
4343d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier    auto* src = reinterpret_cast<ArtMethod*>(heap_->Begin() + section.Offset() + pos);
4353d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier    auto* dest = RelocatedCopyOf(src);
4363d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier    FixupMethod(src, dest);
437c785344b87221f5e4e6473e5b762e4e61fe65dcfMathieu Chartier  }
438c785344b87221f5e4e6473e5b762e4e61fe65dcfMathieu Chartier}
439c785344b87221f5e4e6473e5b762e4e61fe65dcfMathieu Chartier
440fac3a390a247fe33d4873773d742aad4cc100118Mathieu Chartierclass FixupRootVisitor : public RootVisitor {
441fac3a390a247fe33d4873773d742aad4cc100118Mathieu Chartier public:
442fac3a390a247fe33d4873773d742aad4cc100118Mathieu Chartier  explicit FixupRootVisitor(const PatchOat* patch_oat) : patch_oat_(patch_oat) {
443fac3a390a247fe33d4873773d742aad4cc100118Mathieu Chartier  }
444fac3a390a247fe33d4873773d742aad4cc100118Mathieu Chartier
445fac3a390a247fe33d4873773d742aad4cc100118Mathieu Chartier  void VisitRoots(mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED)
446fac3a390a247fe33d4873773d742aad4cc100118Mathieu Chartier      OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
447fac3a390a247fe33d4873773d742aad4cc100118Mathieu Chartier    for (size_t i = 0; i < count; ++i) {
448fac3a390a247fe33d4873773d742aad4cc100118Mathieu Chartier      *roots[i] = patch_oat_->RelocatedAddressOfPointer(*roots[i]);
449fac3a390a247fe33d4873773d742aad4cc100118Mathieu Chartier    }
450fac3a390a247fe33d4873773d742aad4cc100118Mathieu Chartier  }
451fac3a390a247fe33d4873773d742aad4cc100118Mathieu Chartier
452fac3a390a247fe33d4873773d742aad4cc100118Mathieu Chartier  void VisitRoots(mirror::CompressedReference<mirror::Object>** roots, size_t count,
453fac3a390a247fe33d4873773d742aad4cc100118Mathieu Chartier                  const RootInfo& info ATTRIBUTE_UNUSED)
454fac3a390a247fe33d4873773d742aad4cc100118Mathieu Chartier      OVERRIDE SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
455fac3a390a247fe33d4873773d742aad4cc100118Mathieu Chartier    for (size_t i = 0; i < count; ++i) {
456fac3a390a247fe33d4873773d742aad4cc100118Mathieu Chartier      roots[i]->Assign(patch_oat_->RelocatedAddressOfPointer(roots[i]->AsMirrorPtr()));
457fac3a390a247fe33d4873773d742aad4cc100118Mathieu Chartier    }
458fac3a390a247fe33d4873773d742aad4cc100118Mathieu Chartier  }
459fac3a390a247fe33d4873773d742aad4cc100118Mathieu Chartier
460fac3a390a247fe33d4873773d742aad4cc100118Mathieu Chartier private:
461fac3a390a247fe33d4873773d742aad4cc100118Mathieu Chartier  const PatchOat* const patch_oat_;
462fac3a390a247fe33d4873773d742aad4cc100118Mathieu Chartier};
463fac3a390a247fe33d4873773d742aad4cc100118Mathieu Chartier
464fac3a390a247fe33d4873773d742aad4cc100118Mathieu Chartiervoid PatchOat::PatchInternedStrings(const ImageHeader* image_header) {
465fac3a390a247fe33d4873773d742aad4cc100118Mathieu Chartier  const auto& section = image_header->GetImageSection(ImageHeader::kSectionInternedStrings);
466fac3a390a247fe33d4873773d742aad4cc100118Mathieu Chartier  InternTable temp_table;
467fac3a390a247fe33d4873773d742aad4cc100118Mathieu Chartier  // Note that we require that ReadFromMemory does not make an internal copy of the elements.
468fac3a390a247fe33d4873773d742aad4cc100118Mathieu Chartier  // This also relies on visit roots not doing any verification which could fail after we update
469fac3a390a247fe33d4873773d742aad4cc100118Mathieu Chartier  // the roots to be the image addresses.
470fac3a390a247fe33d4873773d742aad4cc100118Mathieu Chartier  temp_table.ReadFromMemory(image_->Begin() + section.Offset());
471fac3a390a247fe33d4873773d742aad4cc100118Mathieu Chartier  FixupRootVisitor visitor(this);
472fac3a390a247fe33d4873773d742aad4cc100118Mathieu Chartier  temp_table.VisitRoots(&visitor, kVisitRootFlagAllRoots);
473fac3a390a247fe33d4873773d742aad4cc100118Mathieu Chartier}
474fac3a390a247fe33d4873773d742aad4cc100118Mathieu Chartier
475c785344b87221f5e4e6473e5b762e4e61fe65dcfMathieu Chartiervoid PatchOat::PatchDexFileArrays(mirror::ObjectArray<mirror::Object>* img_roots) {
476c785344b87221f5e4e6473e5b762e4e61fe65dcfMathieu Chartier  auto* dex_caches = down_cast<mirror::ObjectArray<mirror::DexCache>*>(
477c785344b87221f5e4e6473e5b762e4e61fe65dcfMathieu Chartier      img_roots->Get(ImageHeader::kDexCaches));
478c785344b87221f5e4e6473e5b762e4e61fe65dcfMathieu Chartier  for (size_t i = 0, count = dex_caches->GetLength(); i < count; ++i) {
479c785344b87221f5e4e6473e5b762e4e61fe65dcfMathieu Chartier    auto* dex_cache = dex_caches->GetWithoutChecks(i);
480c785344b87221f5e4e6473e5b762e4e61fe65dcfMathieu Chartier    auto* fields = dex_cache->GetResolvedFields();
4813d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier    if (fields != nullptr) {
4823d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier      CHECK(!fields->IsObjectArray());
4833d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier      CHECK(fields->IsArrayInstance());
4843d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier      FixupNativePointerArray(fields);
485c785344b87221f5e4e6473e5b762e4e61fe65dcfMathieu Chartier    }
4863d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier    auto* methods = dex_cache->GetResolvedMethods();
4873d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier    if (methods != nullptr) {
4883d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier      CHECK(!methods->IsObjectArray());
4893d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier      CHECK(methods->IsArrayInstance());
4903d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier      FixupNativePointerArray(methods);
4913d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier    }
4923d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier  }
4933d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier}
4943d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier
4953d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartiervoid PatchOat::FixupNativePointerArray(mirror::PointerArray* object) {
4963d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier  if (object->IsIntArray()) {
4973d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier    mirror::IntArray* arr = object->AsIntArray();
4983d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier    mirror::IntArray* copy_arr = down_cast<mirror::IntArray*>(RelocatedCopyOf(arr));
4993d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier    for (size_t j = 0, count2 = arr->GetLength(); j < count2; ++j) {
5003d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier      copy_arr->SetWithoutChecks<false>(
5013d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier          j, RelocatedAddressOfIntPointer(arr->GetWithoutChecks(j)));
5023d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier    }
5033d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier  } else {
5043d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier    CHECK(object->IsLongArray());
5053d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier    mirror::LongArray* arr = object->AsLongArray();
5063d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier    mirror::LongArray* copy_arr = down_cast<mirror::LongArray*>(RelocatedCopyOf(arr));
5073d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier    for (size_t j = 0, count2 = arr->GetLength(); j < count2; ++j) {
5083d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier      copy_arr->SetWithoutChecks<false>(
5093d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier          j, RelocatedAddressOfIntPointer(arr->GetWithoutChecks(j)));
510c785344b87221f5e4e6473e5b762e4e61fe65dcfMathieu Chartier    }
511c785344b87221f5e4e6473e5b762e4e61fe65dcfMathieu Chartier  }
512c785344b87221f5e4e6473e5b762e4e61fe65dcfMathieu Chartier}
513c785344b87221f5e4e6473e5b762e4e61fe65dcfMathieu Chartier
51453cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Lightbool PatchOat::PatchImage() {
51553cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  ImageHeader* image_header = reinterpret_cast<ImageHeader*>(image_->Begin());
51653cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  CHECK_GT(image_->Size(), sizeof(ImageHeader));
51753cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  // These are the roots from the original file.
518c785344b87221f5e4e6473e5b762e4e61fe65dcfMathieu Chartier  auto* img_roots = image_header->GetImageRoots();
51953cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  image_header->RelocateImage(delta_);
52053cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light
521c785344b87221f5e4e6473e5b762e4e61fe65dcfMathieu Chartier  PatchArtFields(image_header);
5223d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier  PatchArtMethods(image_header);
523fac3a390a247fe33d4873773d742aad4cc100118Mathieu Chartier  PatchInternedStrings(image_header);
524c785344b87221f5e4e6473e5b762e4e61fe65dcfMathieu Chartier  // Patch dex file int/long arrays which point to ArtFields.
525c785344b87221f5e4e6473e5b762e4e61fe65dcfMathieu Chartier  PatchDexFileArrays(img_roots);
526c785344b87221f5e4e6473e5b762e4e61fe65dcfMathieu Chartier
52753cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  VisitObject(img_roots);
52853cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  if (!image_header->IsValid()) {
52953cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    LOG(ERROR) << "reloction renders image header invalid";
53053cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    return false;
53153cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  }
53253cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light
53353cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  {
534eefbe39799126afdf7d315a79359b9da23d1cef5Alex Light    TimingLogger::ScopedTiming t("Walk Bitmap", timings_);
53553cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    // Walk the bitmap.
53653cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
53753cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    bitmap_->Walk(PatchOat::BitmapCallback, this);
53853cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  }
53953cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  return true;
54053cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light}
54153cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light
54253cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Lightbool PatchOat::InHeap(mirror::Object* o) {
54353cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  uintptr_t begin = reinterpret_cast<uintptr_t>(heap_->Begin());
54453cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  uintptr_t end = reinterpret_cast<uintptr_t>(heap_->End());
54553cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  uintptr_t obj = reinterpret_cast<uintptr_t>(o);
54653cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  return o == nullptr || (begin <= obj && obj < end);
54753cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light}
54853cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light
54953cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Lightvoid PatchOat::PatchVisitor::operator() (mirror::Object* obj, MemberOffset off,
5506a3c1fcb4ba42ad4d5d142c17a3712a6ddd3866fIan Rogers                                         bool is_static_unused ATTRIBUTE_UNUSED) const {
55153cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  mirror::Object* referent = obj->GetFieldObject<mirror::Object, kVerifyNone>(off);
55253cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  DCHECK(patcher_->InHeap(referent)) << "Referent is not in the heap.";
553c785344b87221f5e4e6473e5b762e4e61fe65dcfMathieu Chartier  mirror::Object* moved_object = patcher_->RelocatedAddressOfPointer(referent);
55453cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(off, moved_object);
55553cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light}
55653cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light
5576a3c1fcb4ba42ad4d5d142c17a3712a6ddd3866fIan Rogersvoid PatchOat::PatchVisitor::operator() (mirror::Class* cls ATTRIBUTE_UNUSED,
5586a3c1fcb4ba42ad4d5d142c17a3712a6ddd3866fIan Rogers                                         mirror::Reference* ref) const {
55953cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  MemberOffset off = mirror::Reference::ReferentOffset();
56053cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  mirror::Object* referent = ref->GetReferent();
56153cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  DCHECK(patcher_->InHeap(referent)) << "Referent is not in the heap.";
562c785344b87221f5e4e6473e5b762e4e61fe65dcfMathieu Chartier  mirror::Object* moved_object = patcher_->RelocatedAddressOfPointer(referent);
56353cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(off, moved_object);
56453cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light}
56553cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light
56646774767fcf7780d1455e755729198648d08742eIgor Murashkinconst OatHeader* PatchOat::GetOatHeader(const ElfFile* elf_file) {
56746774767fcf7780d1455e755729198648d08742eIgor Murashkin  if (elf_file->Is64Bit()) {
56846774767fcf7780d1455e755729198648d08742eIgor Murashkin    return GetOatHeader<ElfFileImpl64>(elf_file->GetImpl64());
56946774767fcf7780d1455e755729198648d08742eIgor Murashkin  } else {
57046774767fcf7780d1455e755729198648d08742eIgor Murashkin    return GetOatHeader<ElfFileImpl32>(elf_file->GetImpl32());
57146774767fcf7780d1455e755729198648d08742eIgor Murashkin  }
57246774767fcf7780d1455e755729198648d08742eIgor Murashkin}
57346774767fcf7780d1455e755729198648d08742eIgor Murashkin
57446774767fcf7780d1455e755729198648d08742eIgor Murashkintemplate <typename ElfFileImpl>
57546774767fcf7780d1455e755729198648d08742eIgor Murashkinconst OatHeader* PatchOat::GetOatHeader(const ElfFileImpl* elf_file) {
57646774767fcf7780d1455e755729198648d08742eIgor Murashkin  auto rodata_sec = elf_file->FindSectionByName(".rodata");
57746774767fcf7780d1455e755729198648d08742eIgor Murashkin  if (rodata_sec == nullptr) {
57846774767fcf7780d1455e755729198648d08742eIgor Murashkin    return nullptr;
57946774767fcf7780d1455e755729198648d08742eIgor Murashkin  }
58046774767fcf7780d1455e755729198648d08742eIgor Murashkin
58146774767fcf7780d1455e755729198648d08742eIgor Murashkin  OatHeader* oat_header = reinterpret_cast<OatHeader*>(elf_file->Begin() + rodata_sec->sh_offset);
58246774767fcf7780d1455e755729198648d08742eIgor Murashkin  return oat_header;
58346774767fcf7780d1455e755729198648d08742eIgor Murashkin}
58446774767fcf7780d1455e755729198648d08742eIgor Murashkin
58553cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light// Called by BitmapCallback
58653cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Lightvoid PatchOat::VisitObject(mirror::Object* object) {
58753cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  mirror::Object* copy = RelocatedCopyOf(object);
58853cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  CHECK(copy != nullptr);
58953cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  if (kUseBakerOrBrooksReadBarrier) {
59053cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    object->AssertReadBarrierPointer();
59153cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    if (kUseBrooksReadBarrier) {
592c785344b87221f5e4e6473e5b762e4e61fe65dcfMathieu Chartier      mirror::Object* moved_to = RelocatedAddressOfPointer(object);
59353cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      copy->SetReadBarrierPointer(moved_to);
59453cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      DCHECK_EQ(copy->GetReadBarrierPointer(), moved_to);
59553cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    }
59653cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  }
59753cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  PatchOat::PatchVisitor visitor(this, copy);
59853cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  object->VisitReferences<true, kVerifyNone>(visitor, visitor);
5993d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier  if (object->IsClass<kVerifyNone>()) {
6003d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier    auto* klass = object->AsClass();
6013d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier    auto* copy_klass = down_cast<mirror::Class*>(copy);
6023d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier    copy_klass->SetSFieldsUnchecked(RelocatedAddressOfPointer(klass->GetSFields()));
6033d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier    copy_klass->SetIFieldsUnchecked(RelocatedAddressOfPointer(klass->GetIFields()));
6043d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier    copy_klass->SetDirectMethodsPtrUnchecked(
6053d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier        RelocatedAddressOfPointer(klass->GetDirectMethodsPtr()));
6063d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier    copy_klass->SetVirtualMethodsPtr(RelocatedAddressOfPointer(klass->GetVirtualMethodsPtr()));
6073d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier    auto* vtable = klass->GetVTable();
6083d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier    if (vtable != nullptr) {
6093d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier      FixupNativePointerArray(vtable);
6103d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier    }
6113d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier    auto* iftable = klass->GetIfTable();
6123d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier    if (iftable != nullptr) {
6133d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier      for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
6143d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier        if (iftable->GetMethodArrayCount(i) > 0) {
6153d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier          auto* method_array = iftable->GetMethodArray(i);
6163d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier          CHECK(method_array != nullptr);
6173d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier          FixupNativePointerArray(method_array);
6183d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier        }
6193d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier      }
6203d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier    }
6213d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier    if (klass->ShouldHaveEmbeddedImtAndVTable()) {
6223d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier      const size_t pointer_size = InstructionSetPointerSize(isa_);
6233d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier      for (int32_t i = 0; i < klass->GetEmbeddedVTableLength(); ++i) {
6243d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier        copy_klass->SetEmbeddedVTableEntryUnchecked(i, RelocatedAddressOfPointer(
6253d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier            klass->GetEmbeddedVTableEntry(i, pointer_size)), pointer_size);
6263d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier      }
6273d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier      for (size_t i = 0; i < mirror::Class::kImtSize; ++i) {
6283d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier        copy_klass->SetEmbeddedImTableEntry(i, RelocatedAddressOfPointer(
6293d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier            klass->GetEmbeddedImTableEntry(i, pointer_size)), pointer_size);
6303d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier      }
6313d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier    }
6323d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier  }
6333d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier  if (object->GetClass() == mirror::Method::StaticClass() ||
6343d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier      object->GetClass() == mirror::Constructor::StaticClass()) {
6353d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier    // Need to go update the ArtMethod.
6363d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier    auto* dest = down_cast<mirror::AbstractMethod*>(copy);
6373d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier    auto* src = down_cast<mirror::AbstractMethod*>(object);
6383d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier    dest->SetArtMethod(RelocatedAddressOfPointer(src->GetArtMethod()));
63953cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  }
64053cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light}
64153cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light
6423d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartiervoid PatchOat::FixupMethod(ArtMethod* object, ArtMethod* copy) {
6432d7210188805292e463be4bcf7a133b654d7e0eaMathieu Chartier  const size_t pointer_size = InstructionSetPointerSize(isa_);
6443d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier  copy->CopyFrom(object, pointer_size);
64553cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  // Just update the entry points if it looks like we should.
646eefbe39799126afdf7d315a79359b9da23d1cef5Alex Light  // TODO: sanity check all the pointers' values
6473d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier  copy->SetDeclaringClass(RelocatedAddressOfPointer(object->GetDeclaringClass()));
6483d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier  copy->SetDexCacheResolvedMethods(RelocatedAddressOfPointer(object->GetDexCacheResolvedMethods()));
6493d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier  copy->SetDexCacheResolvedTypes(RelocatedAddressOfPointer(object->GetDexCacheResolvedTypes()));
6503d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier  copy->SetEntryPointFromQuickCompiledCodePtrSize(RelocatedAddressOfPointer(
6513d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier      object->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size)), pointer_size);
6523d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier  copy->SetEntryPointFromInterpreterPtrSize(RelocatedAddressOfPointer(
6533d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier      object->GetEntryPointFromInterpreterPtrSize(pointer_size)), pointer_size);
6543d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier  copy->SetEntryPointFromJniPtrSize(RelocatedAddressOfPointer(
6553d21bdf8894e780d349c481e5c9e29fe1556051cMathieu Chartier      object->GetEntryPointFromJniPtrSize(pointer_size)), pointer_size);
65653cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light}
65753cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light
65846774767fcf7780d1455e755729198648d08742eIgor Murashkinbool PatchOat::Patch(File* input_oat, off_t delta, File* output_oat, TimingLogger* timings,
65946774767fcf7780d1455e755729198648d08742eIgor Murashkin                     bool output_oat_opened_from_fd, bool new_oat_out) {
66053cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  CHECK(input_oat != nullptr);
66153cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  CHECK(output_oat != nullptr);
66253cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  CHECK_GE(input_oat->Fd(), 0);
66353cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  CHECK_GE(output_oat->Fd(), 0);
664eefbe39799126afdf7d315a79359b9da23d1cef5Alex Light  TimingLogger::ScopedTiming t("Setup Oat File Patching", timings);
66553cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light
66653cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  std::string error_msg;
66746774767fcf7780d1455e755729198648d08742eIgor Murashkin  std::unique_ptr<ElfFile> elf(ElfFile::Open(input_oat,
66853cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light                                             PROT_READ | PROT_WRITE, MAP_PRIVATE, &error_msg));
66953cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  if (elf.get() == nullptr) {
67053cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    LOG(ERROR) << "unable to open oat file " << input_oat->GetPath() << " : " << error_msg;
67153cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    return false;
67253cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  }
67353cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light
67446774767fcf7780d1455e755729198648d08742eIgor Murashkin  MaybePic is_oat_pic = IsOatPic(elf.get());
67546774767fcf7780d1455e755729198648d08742eIgor Murashkin  if (is_oat_pic >= ERROR_FIRST) {
67646774767fcf7780d1455e755729198648d08742eIgor Murashkin    // Error logged by IsOatPic
67746774767fcf7780d1455e755729198648d08742eIgor Murashkin    return false;
67846774767fcf7780d1455e755729198648d08742eIgor Murashkin  } else if (is_oat_pic == PIC) {
67946774767fcf7780d1455e755729198648d08742eIgor Murashkin    // Do not need to do ELF-file patching. Create a symlink and skip the rest.
68046774767fcf7780d1455e755729198648d08742eIgor Murashkin    // Any errors will be logged by the function call.
68146774767fcf7780d1455e755729198648d08742eIgor Murashkin    return ReplaceOatFileWithSymlink(input_oat->GetPath(),
68246774767fcf7780d1455e755729198648d08742eIgor Murashkin                                     output_oat->GetPath(),
68346774767fcf7780d1455e755729198648d08742eIgor Murashkin                                     output_oat_opened_from_fd,
68446774767fcf7780d1455e755729198648d08742eIgor Murashkin                                     new_oat_out);
68546774767fcf7780d1455e755729198648d08742eIgor Murashkin  } else {
68646774767fcf7780d1455e755729198648d08742eIgor Murashkin    CHECK(is_oat_pic == NOT_PIC);
68746774767fcf7780d1455e755729198648d08742eIgor Murashkin  }
68846774767fcf7780d1455e755729198648d08742eIgor Murashkin
68953cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  PatchOat p(elf.release(), delta, timings);
69053cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  t.NewTiming("Patch Oat file");
69153cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  if (!p.PatchElf()) {
69253cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    return false;
69353cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  }
69453cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light
69553cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  t.NewTiming("Writing oat file");
69653cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  if (!p.WriteElf(output_oat)) {
69753cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    return false;
69853cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  }
69953cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  return true;
70053cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light}
70153cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light
70262d1ca3182a6cbb921799825f43ad36821233fd7Tong Shentemplate <typename ElfFileImpl>
70362d1ca3182a6cbb921799825f43ad36821233fd7Tong Shenbool PatchOat::PatchOatHeader(ElfFileImpl* oat_file) {
70462d1ca3182a6cbb921799825f43ad36821233fd7Tong Shen  auto rodata_sec = oat_file->FindSectionByName(".rodata");
705a59dd80f9f48cb750d329d4d4af2d99d72b484d1Alex Light  if (rodata_sec == nullptr) {
706a59dd80f9f48cb750d329d4d4af2d99d72b484d1Alex Light    return false;
707a59dd80f9f48cb750d329d4d4af2d99d72b484d1Alex Light  }
70862d1ca3182a6cbb921799825f43ad36821233fd7Tong Shen  OatHeader* oat_header = reinterpret_cast<OatHeader*>(oat_file->Begin() + rodata_sec->sh_offset);
709a59dd80f9f48cb750d329d4d4af2d99d72b484d1Alex Light  if (!oat_header->IsValid()) {
71062d1ca3182a6cbb921799825f43ad36821233fd7Tong Shen    LOG(ERROR) << "Elf file " << oat_file->GetFile().GetPath() << " has an invalid oat header";
711a59dd80f9f48cb750d329d4d4af2d99d72b484d1Alex Light    return false;
712a59dd80f9f48cb750d329d4d4af2d99d72b484d1Alex Light  }
713a59dd80f9f48cb750d329d4d4af2d99d72b484d1Alex Light  oat_header->RelocateOat(delta_);
714a59dd80f9f48cb750d329d4d4af2d99d72b484d1Alex Light  return true;
715a59dd80f9f48cb750d329d4d4af2d99d72b484d1Alex Light}
716a59dd80f9f48cb750d329d4d4af2d99d72b484d1Alex Light
71753cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Lightbool PatchOat::PatchElf() {
718d4c4d953035d4418126d36517e402f411d6a87f3Ian Rogers  if (oat_file_->Is64Bit())
71962d1ca3182a6cbb921799825f43ad36821233fd7Tong Shen    return PatchElf<ElfFileImpl64>(oat_file_->GetImpl64());
72062d1ca3182a6cbb921799825f43ad36821233fd7Tong Shen  else
72162d1ca3182a6cbb921799825f43ad36821233fd7Tong Shen    return PatchElf<ElfFileImpl32>(oat_file_->GetImpl32());
72262d1ca3182a6cbb921799825f43ad36821233fd7Tong Shen}
72362d1ca3182a6cbb921799825f43ad36821233fd7Tong Shen
72462d1ca3182a6cbb921799825f43ad36821233fd7Tong Shentemplate <typename ElfFileImpl>
72562d1ca3182a6cbb921799825f43ad36821233fd7Tong Shenbool PatchOat::PatchElf(ElfFileImpl* oat_file) {
726a59dd80f9f48cb750d329d4d4af2d99d72b484d1Alex Light  TimingLogger::ScopedTiming t("Fixup Elf Text Section", timings_);
727a36098b3717e14baf6a173e72082f6ef3b7bcefdVladimir Marko
728a36098b3717e14baf6a173e72082f6ef3b7bcefdVladimir Marko  // Fix up absolute references to locations within the boot image.
7292f6cdb01f74772c1c521a125776ef57ea3c73d43David Srbecky  if (!oat_file->ApplyOatPatchesTo(".text", delta_)) {
730a59dd80f9f48cb750d329d4d4af2d99d72b484d1Alex Light    return false;
731a59dd80f9f48cb750d329d4d4af2d99d72b484d1Alex Light  }
732a59dd80f9f48cb750d329d4d4af2d99d72b484d1Alex Light
733a36098b3717e14baf6a173e72082f6ef3b7bcefdVladimir Marko  // Update the OatHeader fields referencing the boot image.
73462d1ca3182a6cbb921799825f43ad36821233fd7Tong Shen  if (!PatchOatHeader<ElfFileImpl>(oat_file)) {
735a59dd80f9f48cb750d329d4d4af2d99d72b484d1Alex Light    return false;
736a59dd80f9f48cb750d329d4d4af2d99d72b484d1Alex Light  }
737a59dd80f9f48cb750d329d4d4af2d99d72b484d1Alex Light
738a36098b3717e14baf6a173e72082f6ef3b7bcefdVladimir Marko  bool need_boot_oat_fixup = true;
739d4c4d953035d4418126d36517e402f411d6a87f3Ian Rogers  for (unsigned int i = 0; i < oat_file->GetProgramHeaderNum(); ++i) {
74062d1ca3182a6cbb921799825f43ad36821233fd7Tong Shen    auto hdr = oat_file->GetProgramHeader(i);
741a36098b3717e14baf6a173e72082f6ef3b7bcefdVladimir Marko    if (hdr->p_type == PT_LOAD && hdr->p_vaddr == 0u) {
742a36098b3717e14baf6a173e72082f6ef3b7bcefdVladimir Marko      need_boot_oat_fixup = false;
743d4c4d953035d4418126d36517e402f411d6a87f3Ian Rogers      break;
74453cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    }
74553cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  }
746a36098b3717e14baf6a173e72082f6ef3b7bcefdVladimir Marko  if (!need_boot_oat_fixup) {
747a36098b3717e14baf6a173e72082f6ef3b7bcefdVladimir Marko    // This is an app oat file that can be loaded at an arbitrary address in memory.
748a36098b3717e14baf6a173e72082f6ef3b7bcefdVladimir Marko    // Boot image references were patched above and there's nothing else to do.
749a59dd80f9f48cb750d329d4d4af2d99d72b484d1Alex Light    return true;
750a59dd80f9f48cb750d329d4d4af2d99d72b484d1Alex Light  }
75162d1ca3182a6cbb921799825f43ad36821233fd7Tong Shen
752a36098b3717e14baf6a173e72082f6ef3b7bcefdVladimir Marko  // This is a boot oat file that's loaded at a particular address and we need
753a36098b3717e14baf6a173e72082f6ef3b7bcefdVladimir Marko  // to patch all absolute addresses, starting with ELF program headers.
754a36098b3717e14baf6a173e72082f6ef3b7bcefdVladimir Marko
75562d1ca3182a6cbb921799825f43ad36821233fd7Tong Shen  t.NewTiming("Fixup Elf Headers");
75662d1ca3182a6cbb921799825f43ad36821233fd7Tong Shen  // Fixup Phdr's
75762d1ca3182a6cbb921799825f43ad36821233fd7Tong Shen  oat_file->FixupProgramHeaders(delta_);
75862d1ca3182a6cbb921799825f43ad36821233fd7Tong Shen
759a59dd80f9f48cb750d329d4d4af2d99d72b484d1Alex Light  t.NewTiming("Fixup Section Headers");
76062d1ca3182a6cbb921799825f43ad36821233fd7Tong Shen  // Fixup Shdr's
76162d1ca3182a6cbb921799825f43ad36821233fd7Tong Shen  oat_file->FixupSectionHeaders(delta_);
76253cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light
763a59dd80f9f48cb750d329d4d4af2d99d72b484d1Alex Light  t.NewTiming("Fixup Dynamics");
76462d1ca3182a6cbb921799825f43ad36821233fd7Tong Shen  oat_file->FixupDynamic(delta_);
76553cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light
76653cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  t.NewTiming("Fixup Elf Symbols");
76753cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  // Fixup dynsym
76862d1ca3182a6cbb921799825f43ad36821233fd7Tong Shen  if (!oat_file->FixupSymbols(delta_, true)) {
76953cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    return false;
77053cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  }
77153cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  // Fixup symtab
77262d1ca3182a6cbb921799825f43ad36821233fd7Tong Shen  if (!oat_file->FixupSymbols(delta_, false)) {
77362d1ca3182a6cbb921799825f43ad36821233fd7Tong Shen    return false;
77453cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  }
77553cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light
776e3ea83811d47152c00abea24a9b420651a33b496Yevgeny Rouban  t.NewTiming("Fixup Debug Sections");
77762d1ca3182a6cbb921799825f43ad36821233fd7Tong Shen  if (!oat_file->FixupDebugSections(delta_)) {
778e3ea83811d47152c00abea24a9b420651a33b496Yevgeny Rouban    return false;
779e3ea83811d47152c00abea24a9b420651a33b496Yevgeny Rouban  }
780e3ea83811d47152c00abea24a9b420651a33b496Yevgeny Rouban
78153cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  return true;
78253cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light}
78353cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light
78453cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Lightstatic int orig_argc;
78553cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Lightstatic char** orig_argv;
78653cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light
78753cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Lightstatic std::string CommandLine() {
78853cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  std::vector<std::string> command;
78953cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  for (int i = 0; i < orig_argc; ++i) {
79053cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    command.push_back(orig_argv[i]);
79153cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  }
79253cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  return Join(command, ' ');
79353cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light}
79453cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light
79553cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Lightstatic void UsageErrorV(const char* fmt, va_list ap) {
79653cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  std::string error;
79753cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  StringAppendV(&error, fmt, ap);
79853cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  LOG(ERROR) << error;
79953cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light}
80053cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light
80153cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Lightstatic void UsageError(const char* fmt, ...) {
80253cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  va_list ap;
80353cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  va_start(ap, fmt);
80453cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  UsageErrorV(fmt, ap);
80553cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  va_end(ap);
80653cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light}
80753cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light
808794ad76e8d5b5b9132819d5b08a0570e27615644Andreas GampeNO_RETURN static void Usage(const char *fmt, ...) {
80953cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  va_list ap;
81053cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  va_start(ap, fmt);
81153cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  UsageErrorV(fmt, ap);
81253cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  va_end(ap);
81353cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light
81453cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  UsageError("Command: %s", CommandLine().c_str());
81553cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  UsageError("Usage: patchoat [options]...");
81653cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  UsageError("");
81753cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  UsageError("  --instruction-set=<isa>: Specifies the instruction set the patched code is");
81853cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  UsageError("      compiled for. Required if you use --input-oat-location");
81953cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  UsageError("");
82053cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  UsageError("  --input-oat-file=<file.oat>: Specifies the exact filename of the oat file to be");
82153cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  UsageError("      patched.");
82253cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  UsageError("");
82353cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  UsageError("  --input-oat-fd=<file-descriptor>: Specifies the file-descriptor of the oat file");
82453cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  UsageError("      to be patched.");
82553cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  UsageError("");
82653cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  UsageError("  --input-oat-location=<file.oat>: Specifies the 'location' to read the patched");
82753cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  UsageError("      oat file from. If used one must also supply the --instruction-set");
82853cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  UsageError("");
82953cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  UsageError("  --input-image-location=<file.art>: Specifies the 'location' of the image file to");
83053cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  UsageError("      be patched. If --instruction-set is not given it will use the instruction set");
83153cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  UsageError("      extracted from the --input-oat-file.");
83253cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  UsageError("");
83353cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  UsageError("  --output-oat-file=<file.oat>: Specifies the exact file to write the patched oat");
83453cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  UsageError("      file to.");
83553cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  UsageError("");
83653cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  UsageError("  --output-oat-fd=<file-descriptor>: Specifies the file-descriptor to write the");
83753cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  UsageError("      the patched oat file to.");
83853cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  UsageError("");
83953cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  UsageError("  --output-image-file=<file.art>: Specifies the exact file to write the patched");
84053cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  UsageError("      image file to.");
84153cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  UsageError("");
84253cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  UsageError("  --output-image-fd=<file-descriptor>: Specifies the file-descriptor to write the");
84353cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  UsageError("      the patched image file to.");
84453cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  UsageError("");
84553cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  UsageError("  --orig-base-offset=<original-base-offset>: Specify the base offset the input file");
84653cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  UsageError("      was compiled with. This is needed if one is specifying a --base-offset");
84753cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  UsageError("");
84853cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  UsageError("  --base-offset=<new-base-offset>: Specify the base offset we will repatch the");
84953cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  UsageError("      given files to use. This requires that --orig-base-offset is also given.");
85053cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  UsageError("");
85153cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  UsageError("  --base-offset-delta=<delta>: Specify the amount to change the old base-offset by.");
85253cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  UsageError("      This value may be negative.");
85353cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  UsageError("");
85453cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  UsageError("  --patched-image-file=<file.art>: Use the same patch delta as was used to patch");
85553cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  UsageError("      the given image file.");
85653cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  UsageError("");
85753cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  UsageError("  --patched-image-location=<file.art>: Use the same patch delta as was used to");
85853cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  UsageError("      patch the given image location. If used one must also specify the");
859a59dd80f9f48cb750d329d4d4af2d99d72b484d1Alex Light  UsageError("      --instruction-set flag. It will search for this image in the same way that");
860a59dd80f9f48cb750d329d4d4af2d99d72b484d1Alex Light  UsageError("      is done when loading one.");
86153cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  UsageError("");
862cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light  UsageError("  --lock-output: Obtain a flock on output oat file before starting.");
863cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light  UsageError("");
864cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light  UsageError("  --no-lock-output: Do not attempt to obtain a flock on output oat file.");
865cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light  UsageError("");
86653cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  UsageError("  --dump-timings: dump out patch timing information");
86753cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  UsageError("");
86853cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  UsageError("  --no-dump-timings: do not dump out patch timing information");
86953cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  UsageError("");
87053cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light
87153cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  exit(EXIT_FAILURE);
87253cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light}
87353cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light
874eefbe39799126afdf7d315a79359b9da23d1cef5Alex Lightstatic bool ReadBaseDelta(const char* name, off_t* delta, std::string* error_msg) {
87553cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  CHECK(name != nullptr);
87653cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  CHECK(delta != nullptr);
87753cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  std::unique_ptr<File> file;
87853cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  if (OS::FileExists(name)) {
87953cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    file.reset(OS::OpenFileForReading(name));
88053cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    if (file.get() == nullptr) {
881eefbe39799126afdf7d315a79359b9da23d1cef5Alex Light      *error_msg = "Failed to open file %s for reading";
88253cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      return false;
88353cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    }
88453cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  } else {
885eefbe39799126afdf7d315a79359b9da23d1cef5Alex Light    *error_msg = "File %s does not exist";
88653cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    return false;
88753cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  }
88853cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  CHECK(file.get() != nullptr);
88953cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  ImageHeader hdr;
89053cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  if (sizeof(hdr) != file->Read(reinterpret_cast<char*>(&hdr), sizeof(hdr), 0)) {
891eefbe39799126afdf7d315a79359b9da23d1cef5Alex Light    *error_msg = "Failed to read file %s";
89253cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    return false;
89353cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  }
89453cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  if (!hdr.IsValid()) {
895eefbe39799126afdf7d315a79359b9da23d1cef5Alex Light    *error_msg = "%s does not contain a valid image header.";
89653cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    return false;
89753cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  }
89853cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  *delta = hdr.GetPatchDelta();
89953cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  return true;
90053cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light}
90153cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light
90253cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Lightstatic File* CreateOrOpen(const char* name, bool* created) {
90353cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  if (OS::FileExists(name)) {
90453cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    *created = false;
90553cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    return OS::OpenFileReadWrite(name);
90653cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  } else {
90753cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    *created = true;
908cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light    std::unique_ptr<File> f(OS::CreateEmptyFile(name));
909cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light    if (f.get() != nullptr) {
910cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light      if (fchmod(f->Fd(), 0644) != 0) {
911cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light        PLOG(ERROR) << "Unable to make " << name << " world readable";
9128c52a3f534c49580688239549fca937b36fc0aedBrian Carlstrom        TEMP_FAILURE_RETRY(unlink(name));
913cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light        return nullptr;
914cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light      }
915cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light    }
916cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light    return f.release();
91753cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  }
91853cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light}
91953cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light
9204303ba97313458491e038d78efa041d41cf7bb43Andreas Gampe// Either try to close the file (close=true), or erase it.
9214303ba97313458491e038d78efa041d41cf7bb43Andreas Gampestatic bool FinishFile(File* file, bool close) {
9224303ba97313458491e038d78efa041d41cf7bb43Andreas Gampe  if (close) {
9234303ba97313458491e038d78efa041d41cf7bb43Andreas Gampe    if (file->FlushCloseOrErase() != 0) {
9244303ba97313458491e038d78efa041d41cf7bb43Andreas Gampe      PLOG(ERROR) << "Failed to flush and close file.";
9254303ba97313458491e038d78efa041d41cf7bb43Andreas Gampe      return false;
9264303ba97313458491e038d78efa041d41cf7bb43Andreas Gampe    }
9274303ba97313458491e038d78efa041d41cf7bb43Andreas Gampe    return true;
9284303ba97313458491e038d78efa041d41cf7bb43Andreas Gampe  } else {
9294303ba97313458491e038d78efa041d41cf7bb43Andreas Gampe    file->Erase();
9304303ba97313458491e038d78efa041d41cf7bb43Andreas Gampe    return false;
9314303ba97313458491e038d78efa041d41cf7bb43Andreas Gampe  }
9324303ba97313458491e038d78efa041d41cf7bb43Andreas Gampe}
9334303ba97313458491e038d78efa041d41cf7bb43Andreas Gampe
934eefbe39799126afdf7d315a79359b9da23d1cef5Alex Lightstatic int patchoat(int argc, char **argv) {
93553cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  InitLogging(argv);
9366e88ef6b604a7a945a466784580c42e6554c1289Mathieu Chartier  MemMap::Init();
93753cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  const bool debug = kIsDebugBuild;
93853cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  orig_argc = argc;
93953cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  orig_argv = argv;
94053cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  TimingLogger timings("patcher", false, false);
94153cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light
94253cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  InitLogging(argv);
94353cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light
94453cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  // Skip over the command name.
94553cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  argv++;
94653cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  argc--;
94753cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light
94853cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  if (argc == 0) {
94953cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    Usage("No arguments specified");
95053cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  }
95153cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light
95253cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  timings.StartTiming("Patchoat");
95353cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light
95453cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  // cmd line args
95553cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  bool isa_set = false;
95653cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  InstructionSet isa = kNone;
95753cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  std::string input_oat_filename;
95853cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  std::string input_oat_location;
95953cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  int input_oat_fd = -1;
96053cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  bool have_input_oat = false;
96153cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  std::string input_image_location;
96253cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  std::string output_oat_filename;
96353cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  int output_oat_fd = -1;
96453cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  bool have_output_oat = false;
96553cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  std::string output_image_filename;
96653cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  int output_image_fd = -1;
96753cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  bool have_output_image = false;
96853cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  uintptr_t base_offset = 0;
96953cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  bool base_offset_set = false;
97053cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  uintptr_t orig_base_offset = 0;
97153cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  bool orig_base_offset_set = false;
97253cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  off_t base_delta = 0;
97353cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  bool base_delta_set = false;
97453cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  std::string patched_image_filename;
97553cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  std::string patched_image_location;
97653cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  bool dump_timings = kIsDebugBuild;
977cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light  bool lock_output = true;
97853cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light
979d4c4d953035d4418126d36517e402f411d6a87f3Ian Rogers  for (int i = 0; i < argc; ++i) {
98053cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    const StringPiece option(argv[i]);
98153cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    const bool log_options = false;
98253cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    if (log_options) {
98353cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      LOG(INFO) << "patchoat: option[" << i << "]=" << argv[i];
98453cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    }
98553cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    if (option.starts_with("--instruction-set=")) {
98653cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      isa_set = true;
98753cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      const char* isa_str = option.substr(strlen("--instruction-set=")).data();
98820c89303a9d89ba857bf969ad14a31f12c3be878Andreas Gampe      isa = GetInstructionSetFromString(isa_str);
98920c89303a9d89ba857bf969ad14a31f12c3be878Andreas Gampe      if (isa == kNone) {
99020c89303a9d89ba857bf969ad14a31f12c3be878Andreas Gampe        Usage("Unknown or invalid instruction set %s", isa_str);
99153cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      }
99253cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    } else if (option.starts_with("--input-oat-location=")) {
99353cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      if (have_input_oat) {
99453cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light        Usage("Only one of --input-oat-file, --input-oat-location and --input-oat-fd may be used.");
99553cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      }
99653cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      have_input_oat = true;
99753cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      input_oat_location = option.substr(strlen("--input-oat-location=")).data();
99853cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    } else if (option.starts_with("--input-oat-file=")) {
99953cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      if (have_input_oat) {
100053cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light        Usage("Only one of --input-oat-file, --input-oat-location and --input-oat-fd may be used.");
100153cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      }
100253cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      have_input_oat = true;
100353cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      input_oat_filename = option.substr(strlen("--input-oat-file=")).data();
100453cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    } else if (option.starts_with("--input-oat-fd=")) {
100553cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      if (have_input_oat) {
100653cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light        Usage("Only one of --input-oat-file, --input-oat-location and --input-oat-fd may be used.");
100753cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      }
100853cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      have_input_oat = true;
100953cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      const char* oat_fd_str = option.substr(strlen("--input-oat-fd=")).data();
101053cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      if (!ParseInt(oat_fd_str, &input_oat_fd)) {
101153cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light        Usage("Failed to parse --input-oat-fd argument '%s' as an integer", oat_fd_str);
101253cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      }
101353cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      if (input_oat_fd < 0) {
101453cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light        Usage("--input-oat-fd pass a negative value %d", input_oat_fd);
101553cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      }
101653cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    } else if (option.starts_with("--input-image-location=")) {
101753cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      input_image_location = option.substr(strlen("--input-image-location=")).data();
101853cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    } else if (option.starts_with("--output-oat-file=")) {
101953cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      if (have_output_oat) {
1020cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light        Usage("Only one of --output-oat-file, and --output-oat-fd may be used.");
102153cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      }
102253cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      have_output_oat = true;
102353cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      output_oat_filename = option.substr(strlen("--output-oat-file=")).data();
102453cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    } else if (option.starts_with("--output-oat-fd=")) {
102553cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      if (have_output_oat) {
1026cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light        Usage("Only one of --output-oat-file, --output-oat-fd may be used.");
102753cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      }
102853cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      have_output_oat = true;
102953cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      const char* oat_fd_str = option.substr(strlen("--output-oat-fd=")).data();
103053cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      if (!ParseInt(oat_fd_str, &output_oat_fd)) {
103153cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light        Usage("Failed to parse --output-oat-fd argument '%s' as an integer", oat_fd_str);
103253cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      }
103353cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      if (output_oat_fd < 0) {
103453cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light        Usage("--output-oat-fd pass a negative value %d", output_oat_fd);
103553cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      }
103653cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    } else if (option.starts_with("--output-image-file=")) {
103753cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      if (have_output_image) {
1038cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light        Usage("Only one of --output-image-file, and --output-image-fd may be used.");
103953cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      }
104053cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      have_output_image = true;
104153cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      output_image_filename = option.substr(strlen("--output-image-file=")).data();
104253cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    } else if (option.starts_with("--output-image-fd=")) {
104353cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      if (have_output_image) {
1044cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light        Usage("Only one of --output-image-file, and --output-image-fd may be used.");
104553cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      }
104653cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      have_output_image = true;
104753cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      const char* image_fd_str = option.substr(strlen("--output-image-fd=")).data();
104853cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      if (!ParseInt(image_fd_str, &output_image_fd)) {
104953cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light        Usage("Failed to parse --output-image-fd argument '%s' as an integer", image_fd_str);
105053cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      }
105153cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      if (output_image_fd < 0) {
105253cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light        Usage("--output-image-fd pass a negative value %d", output_image_fd);
105353cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      }
105453cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    } else if (option.starts_with("--orig-base-offset=")) {
105553cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      const char* orig_base_offset_str = option.substr(strlen("--orig-base-offset=")).data();
105653cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      orig_base_offset_set = true;
105753cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      if (!ParseUint(orig_base_offset_str, &orig_base_offset)) {
105853cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light        Usage("Failed to parse --orig-base-offset argument '%s' as an uintptr_t",
105953cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light              orig_base_offset_str);
106053cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      }
106153cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    } else if (option.starts_with("--base-offset=")) {
106253cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      const char* base_offset_str = option.substr(strlen("--base-offset=")).data();
106353cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      base_offset_set = true;
106453cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      if (!ParseUint(base_offset_str, &base_offset)) {
106553cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light        Usage("Failed to parse --base-offset argument '%s' as an uintptr_t", base_offset_str);
106653cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      }
106753cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    } else if (option.starts_with("--base-offset-delta=")) {
106853cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      const char* base_delta_str = option.substr(strlen("--base-offset-delta=")).data();
106953cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      base_delta_set = true;
107053cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      if (!ParseInt(base_delta_str, &base_delta)) {
107153cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light        Usage("Failed to parse --base-offset-delta argument '%s' as an off_t", base_delta_str);
107253cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      }
107353cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    } else if (option.starts_with("--patched-image-location=")) {
107453cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      patched_image_location = option.substr(strlen("--patched-image-location=")).data();
107553cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    } else if (option.starts_with("--patched-image-file=")) {
107653cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      patched_image_filename = option.substr(strlen("--patched-image-file=")).data();
1077cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light    } else if (option == "--lock-output") {
1078cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light      lock_output = true;
1079cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light    } else if (option == "--no-lock-output") {
1080cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light      lock_output = false;
108153cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    } else if (option == "--dump-timings") {
108253cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      dump_timings = true;
108353cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    } else if (option == "--no-dump-timings") {
108453cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      dump_timings = false;
108553cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    } else {
108653cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      Usage("Unknown argument %s", option.data());
108753cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    }
108853cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  }
108953cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light
109053cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  {
109153cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    // Only 1 of these may be set.
109253cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    uint32_t cnt = 0;
109353cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    cnt += (base_delta_set) ? 1 : 0;
109453cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    cnt += (base_offset_set && orig_base_offset_set) ? 1 : 0;
109553cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    cnt += (!patched_image_filename.empty()) ? 1 : 0;
109653cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    cnt += (!patched_image_location.empty()) ? 1 : 0;
109753cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    if (cnt > 1) {
109853cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      Usage("Only one of --base-offset/--orig-base-offset, --base-offset-delta, "
109953cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light            "--patched-image-filename or --patched-image-location may be used.");
110053cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    } else if (cnt == 0) {
110153cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      Usage("Must specify --base-offset-delta, --base-offset and --orig-base-offset, "
110253cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light            "--patched-image-location or --patched-image-file");
110353cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    }
110453cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  }
110553cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light
110653cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  if (have_input_oat != have_output_oat) {
110753cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    Usage("Either both input and output oat must be supplied or niether must be.");
110853cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  }
110953cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light
111053cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  if ((!input_image_location.empty()) != have_output_image) {
111153cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    Usage("Either both input and output image must be supplied or niether must be.");
111253cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  }
111353cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light
111453cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  // We know we have both the input and output so rename for clarity.
111553cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  bool have_image_files = have_output_image;
111653cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  bool have_oat_files = have_output_oat;
111753cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light
111853cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  if (!have_oat_files && !have_image_files) {
111953cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    Usage("Must be patching either an oat or an image file or both.");
112053cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  }
112153cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light
112253cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  if (!have_oat_files && !isa_set) {
112353cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    Usage("Must include ISA if patching an image file without an oat file.");
112453cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  }
112553cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light
112653cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  if (!input_oat_location.empty()) {
112753cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    if (!isa_set) {
112853cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      Usage("specifying a location requires specifying an instruction set");
112953cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    }
1130cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light    if (!LocationToFilename(input_oat_location, isa, &input_oat_filename)) {
1131cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light      Usage("Unable to find filename for input oat location %s", input_oat_location.c_str());
113253cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    }
113353cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    if (debug) {
1134cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light      LOG(INFO) << "Using input-oat-file " << input_oat_filename;
113553cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    }
113653cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  }
113753cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  if (!patched_image_location.empty()) {
113853cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    if (!isa_set) {
113953cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      Usage("specifying a location requires specifying an instruction set");
114053cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    }
1141a59dd80f9f48cb750d329d4d4af2d99d72b484d1Alex Light    std::string system_filename;
1142a59dd80f9f48cb750d329d4d4af2d99d72b484d1Alex Light    bool has_system = false;
1143a59dd80f9f48cb750d329d4d4af2d99d72b484d1Alex Light    std::string cache_filename;
1144a59dd80f9f48cb750d329d4d4af2d99d72b484d1Alex Light    bool has_cache = false;
1145a59dd80f9f48cb750d329d4d4af2d99d72b484d1Alex Light    bool has_android_data_unused = false;
11463c13a794845e0cf7887e33b2ec20de7e6ba85f8fAndreas Gampe    bool is_global_cache = false;
1147a59dd80f9f48cb750d329d4d4af2d99d72b484d1Alex Light    if (!gc::space::ImageSpace::FindImageFilename(patched_image_location.c_str(), isa,
1148a59dd80f9f48cb750d329d4d4af2d99d72b484d1Alex Light                                                  &system_filename, &has_system, &cache_filename,
11493c13a794845e0cf7887e33b2ec20de7e6ba85f8fAndreas Gampe                                                  &has_android_data_unused, &has_cache,
11503c13a794845e0cf7887e33b2ec20de7e6ba85f8fAndreas Gampe                                                  &is_global_cache)) {
1151a59dd80f9f48cb750d329d4d4af2d99d72b484d1Alex Light      Usage("Unable to determine image file for location %s", patched_image_location.c_str());
1152a59dd80f9f48cb750d329d4d4af2d99d72b484d1Alex Light    }
1153a59dd80f9f48cb750d329d4d4af2d99d72b484d1Alex Light    if (has_cache) {
1154a59dd80f9f48cb750d329d4d4af2d99d72b484d1Alex Light      patched_image_filename = cache_filename;
1155a59dd80f9f48cb750d329d4d4af2d99d72b484d1Alex Light    } else if (has_system) {
1156a59dd80f9f48cb750d329d4d4af2d99d72b484d1Alex Light      LOG(WARNING) << "Only image file found was in /system for image location "
1157a59dd80f9f48cb750d329d4d4af2d99d72b484d1Alex Light                   << patched_image_location;
1158a59dd80f9f48cb750d329d4d4af2d99d72b484d1Alex Light      patched_image_filename = system_filename;
1159a59dd80f9f48cb750d329d4d4af2d99d72b484d1Alex Light    } else {
1160a59dd80f9f48cb750d329d4d4af2d99d72b484d1Alex Light      Usage("Unable to determine image file for location %s", patched_image_location.c_str());
1161a59dd80f9f48cb750d329d4d4af2d99d72b484d1Alex Light    }
116253cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    if (debug) {
116353cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      LOG(INFO) << "Using patched-image-file " << patched_image_filename;
116453cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    }
116553cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  }
116653cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light
116753cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  if (!base_delta_set) {
116853cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    if (orig_base_offset_set && base_offset_set) {
116953cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      base_delta_set = true;
117053cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      base_delta = base_offset - orig_base_offset;
117153cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    } else if (!patched_image_filename.empty()) {
117253cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      base_delta_set = true;
117353cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      std::string error_msg;
1174eefbe39799126afdf7d315a79359b9da23d1cef5Alex Light      if (!ReadBaseDelta(patched_image_filename.c_str(), &base_delta, &error_msg)) {
117553cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light        Usage(error_msg.c_str(), patched_image_filename.c_str());
117653cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      }
117753cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    } else {
117853cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      if (base_offset_set) {
117953cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light        Usage("Unable to determine original base offset.");
118053cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      } else {
118153cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light        Usage("Must supply a desired new offset or delta.");
118253cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      }
118353cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    }
118453cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  }
118553cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light
118653cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  if (!IsAligned<kPageSize>(base_delta)) {
118753cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    Usage("Base offset/delta must be alligned to a pagesize (0x%08x) boundary.", kPageSize);
118853cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  }
118953cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light
119053cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  // Do we need to cleanup output files if we fail?
119153cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  bool new_image_out = false;
119253cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  bool new_oat_out = false;
119353cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light
119453cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  std::unique_ptr<File> input_oat;
119553cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  std::unique_ptr<File> output_oat;
119653cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  std::unique_ptr<File> output_image;
119753cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light
119853cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  if (have_image_files) {
119953cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    CHECK(!input_image_location.empty());
120053cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light
120153cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    if (output_image_fd != -1) {
1202cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light      if (output_image_filename.empty()) {
1203cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light        output_image_filename = "output-image-file";
1204cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light      }
12054303ba97313458491e038d78efa041d41cf7bb43Andreas Gampe      output_image.reset(new File(output_image_fd, output_image_filename, true));
120653cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    } else {
120753cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      CHECK(!output_image_filename.empty());
120853cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      output_image.reset(CreateOrOpen(output_image_filename.c_str(), &new_image_out));
120953cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    }
121053cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  } else {
121153cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    CHECK(output_image_filename.empty() && output_image_fd == -1 && input_image_location.empty());
121253cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  }
121353cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light
121453cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  if (have_oat_files) {
121553cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    if (input_oat_fd != -1) {
1216cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light      if (input_oat_filename.empty()) {
1217cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light        input_oat_filename = "input-oat-file";
1218cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light      }
12194303ba97313458491e038d78efa041d41cf7bb43Andreas Gampe      input_oat.reset(new File(input_oat_fd, input_oat_filename, false));
1220a473f510620958e94b586efb5398cb87f263be2fJulien Delayen      if (input_oat_fd == output_oat_fd) {
1221a473f510620958e94b586efb5398cb87f263be2fJulien Delayen        input_oat.get()->DisableAutoClose();
1222a473f510620958e94b586efb5398cb87f263be2fJulien Delayen      }
122346774767fcf7780d1455e755729198648d08742eIgor Murashkin      if (input_oat == nullptr) {
122446774767fcf7780d1455e755729198648d08742eIgor Murashkin        // Unlikely, but ensure exhaustive logging in non-0 exit code case
122546774767fcf7780d1455e755729198648d08742eIgor Murashkin        LOG(ERROR) << "Failed to open input oat file by its FD" << input_oat_fd;
122646774767fcf7780d1455e755729198648d08742eIgor Murashkin      }
122753cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    } else {
122853cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      CHECK(!input_oat_filename.empty());
122953cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      input_oat.reset(OS::OpenFileForReading(input_oat_filename.c_str()));
123046774767fcf7780d1455e755729198648d08742eIgor Murashkin      if (input_oat == nullptr) {
123146774767fcf7780d1455e755729198648d08742eIgor Murashkin        int err = errno;
123246774767fcf7780d1455e755729198648d08742eIgor Murashkin        LOG(ERROR) << "Failed to open input oat file " << input_oat_filename
123346774767fcf7780d1455e755729198648d08742eIgor Murashkin                   << ": " << strerror(err) << "(" << err << ")";
12341c83cbc4a817acbd7f9abb5b29a2d418a958e6a1Andreas Gampe      }
123553cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    }
123653cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light
123753cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    if (output_oat_fd != -1) {
1238cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light      if (output_oat_filename.empty()) {
1239cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light        output_oat_filename = "output-oat-file";
1240a59dd80f9f48cb750d329d4d4af2d99d72b484d1Alex Light      }
12414303ba97313458491e038d78efa041d41cf7bb43Andreas Gampe      output_oat.reset(new File(output_oat_fd, output_oat_filename, true));
124246774767fcf7780d1455e755729198648d08742eIgor Murashkin      if (output_oat == nullptr) {
124346774767fcf7780d1455e755729198648d08742eIgor Murashkin        // Unlikely, but ensure exhaustive logging in non-0 exit code case
124446774767fcf7780d1455e755729198648d08742eIgor Murashkin        LOG(ERROR) << "Failed to open output oat file by its FD" << output_oat_fd;
124546774767fcf7780d1455e755729198648d08742eIgor Murashkin      }
124653cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    } else {
124753cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      CHECK(!output_oat_filename.empty());
124853cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      output_oat.reset(CreateOrOpen(output_oat_filename.c_str(), &new_oat_out));
124946774767fcf7780d1455e755729198648d08742eIgor Murashkin      if (output_oat == nullptr) {
125046774767fcf7780d1455e755729198648d08742eIgor Murashkin        int err = errno;
125146774767fcf7780d1455e755729198648d08742eIgor Murashkin        LOG(ERROR) << "Failed to open output oat file " << output_oat_filename
125246774767fcf7780d1455e755729198648d08742eIgor Murashkin                   << ": " << strerror(err) << "(" << err << ")";
125346774767fcf7780d1455e755729198648d08742eIgor Murashkin      }
125453cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    }
125553cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  }
125653cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light
125746774767fcf7780d1455e755729198648d08742eIgor Murashkin  // TODO: get rid of this.
125853cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  auto cleanup = [&output_image_filename, &output_oat_filename,
125953cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light                  &new_oat_out, &new_image_out, &timings, &dump_timings](bool success) {
126053cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    timings.EndTiming();
126153cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    if (!success) {
126253cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      if (new_oat_out) {
126353cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light        CHECK(!output_oat_filename.empty());
12648c52a3f534c49580688239549fca937b36fc0aedBrian Carlstrom        TEMP_FAILURE_RETRY(unlink(output_oat_filename.c_str()));
126553cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      }
126653cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      if (new_image_out) {
126753cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light        CHECK(!output_image_filename.empty());
12688c52a3f534c49580688239549fca937b36fc0aedBrian Carlstrom        TEMP_FAILURE_RETRY(unlink(output_image_filename.c_str()));
126953cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      }
127053cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    }
127153cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    if (dump_timings) {
127253cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light      LOG(INFO) << Dumpable<TimingLogger>(timings);
127353cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    }
127446774767fcf7780d1455e755729198648d08742eIgor Murashkin
127546774767fcf7780d1455e755729198648d08742eIgor Murashkin    if (kIsDebugBuild) {
127646774767fcf7780d1455e755729198648d08742eIgor Murashkin      LOG(INFO) << "Cleaning up.. success? " << success;
127746774767fcf7780d1455e755729198648d08742eIgor Murashkin    }
127853cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  };
127953cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light
128046774767fcf7780d1455e755729198648d08742eIgor Murashkin  if (have_oat_files && (input_oat.get() == nullptr || output_oat.get() == nullptr)) {
128146774767fcf7780d1455e755729198648d08742eIgor Murashkin    LOG(ERROR) << "Failed to open input/output oat files";
1282cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light    cleanup(false);
1283cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light    return EXIT_FAILURE;
128446774767fcf7780d1455e755729198648d08742eIgor Murashkin  } else if (have_image_files && output_image.get() == nullptr) {
128546774767fcf7780d1455e755729198648d08742eIgor Murashkin    LOG(ERROR) << "Failed to open output image file";
128646774767fcf7780d1455e755729198648d08742eIgor Murashkin    cleanup(false);
128746774767fcf7780d1455e755729198648d08742eIgor Murashkin    return EXIT_FAILURE;
128846774767fcf7780d1455e755729198648d08742eIgor Murashkin  }
128946774767fcf7780d1455e755729198648d08742eIgor Murashkin
129046774767fcf7780d1455e755729198648d08742eIgor Murashkin  if (debug) {
129146774767fcf7780d1455e755729198648d08742eIgor Murashkin    LOG(INFO) << "moving offset by " << base_delta
129246774767fcf7780d1455e755729198648d08742eIgor Murashkin              << " (0x" << std::hex << base_delta << ") bytes or "
129346774767fcf7780d1455e755729198648d08742eIgor Murashkin              << std::dec << (base_delta/kPageSize) << " pages.";
1294cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light  }
1295cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light
129646774767fcf7780d1455e755729198648d08742eIgor Murashkin  // TODO: is it going to be promatic to unlink a file that was flock-ed?
1297cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light  ScopedFlock output_oat_lock;
1298cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light  if (lock_output) {
1299cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light    std::string error_msg;
1300cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light    if (have_oat_files && !output_oat_lock.Init(output_oat.get(), &error_msg)) {
1301cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light      LOG(ERROR) << "Unable to lock output oat " << output_image->GetPath() << ": " << error_msg;
1302cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light      cleanup(false);
1303cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light      return EXIT_FAILURE;
1304cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light    }
1305cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light  }
1306cf4bf386ef3f527825c70e01130b9276da4f786aAlex Light
130753cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  bool ret;
130853cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  if (have_image_files && have_oat_files) {
130953cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    TimingLogger::ScopedTiming pt("patch image and oat", &timings);
131053cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    ret = PatchOat::Patch(input_oat.get(), input_image_location, base_delta,
131146774767fcf7780d1455e755729198648d08742eIgor Murashkin                          output_oat.get(), output_image.get(), isa, &timings,
131246774767fcf7780d1455e755729198648d08742eIgor Murashkin                          output_oat_fd >= 0,  // was it opened from FD?
131346774767fcf7780d1455e755729198648d08742eIgor Murashkin                          new_oat_out);
13144303ba97313458491e038d78efa041d41cf7bb43Andreas Gampe    // The order here doesn't matter. If the first one is successfully saved and the second one
13154303ba97313458491e038d78efa041d41cf7bb43Andreas Gampe    // erased, ImageSpace will still detect a problem and not use the files.
13164303ba97313458491e038d78efa041d41cf7bb43Andreas Gampe    ret = ret && FinishFile(output_image.get(), ret);
13174303ba97313458491e038d78efa041d41cf7bb43Andreas Gampe    ret = ret && FinishFile(output_oat.get(), ret);
131853cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  } else if (have_oat_files) {
131953cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    TimingLogger::ScopedTiming pt("patch oat", &timings);
132046774767fcf7780d1455e755729198648d08742eIgor Murashkin    ret = PatchOat::Patch(input_oat.get(), base_delta, output_oat.get(), &timings,
132146774767fcf7780d1455e755729198648d08742eIgor Murashkin                          output_oat_fd >= 0,  // was it opened from FD?
132246774767fcf7780d1455e755729198648d08742eIgor Murashkin                          new_oat_out);
13234303ba97313458491e038d78efa041d41cf7bb43Andreas Gampe    ret = ret && FinishFile(output_oat.get(), ret);
132446774767fcf7780d1455e755729198648d08742eIgor Murashkin  } else if (have_image_files) {
132553cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light    TimingLogger::ScopedTiming pt("patch image", &timings);
1326eefbe39799126afdf7d315a79359b9da23d1cef5Alex Light    ret = PatchOat::Patch(input_image_location, base_delta, output_image.get(), isa, &timings);
13274303ba97313458491e038d78efa041d41cf7bb43Andreas Gampe    ret = ret && FinishFile(output_image.get(), ret);
132846774767fcf7780d1455e755729198648d08742eIgor Murashkin  } else {
132946774767fcf7780d1455e755729198648d08742eIgor Murashkin    CHECK(false);
133046774767fcf7780d1455e755729198648d08742eIgor Murashkin    ret = true;
133146774767fcf7780d1455e755729198648d08742eIgor Murashkin  }
133246774767fcf7780d1455e755729198648d08742eIgor Murashkin
133346774767fcf7780d1455e755729198648d08742eIgor Murashkin  if (kIsDebugBuild) {
133446774767fcf7780d1455e755729198648d08742eIgor Murashkin    LOG(INFO) << "Exiting with return ... " << ret;
133553cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  }
133653cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  cleanup(ret);
133753cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  return (ret) ? EXIT_SUCCESS : EXIT_FAILURE;
133853cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light}
133953cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light
134053cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light}  // namespace art
134153cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light
134253cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Lightint main(int argc, char **argv) {
134353cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light  return art::patchoat(argc, argv);
134453cb16b98acf3cf6f3a1e2204ad4958ecf1b5a3cAlex Light}
1345