blob: e750ede8fad2c9f835ab2e97868c322a54ab0021 [file] [log] [blame]
Alex Light53cb16b2014-06-12 11:26:29 -07001/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16#include "patchoat.h"
17
18#include <stdio.h>
19#include <stdlib.h>
Alex Lighta59dd802014-07-02 16:28:08 -070020#include <sys/file.h>
Alex Light53cb16b2014-06-12 11:26:29 -070021#include <sys/stat.h>
Alex Lighta59dd802014-07-02 16:28:08 -070022#include <unistd.h>
Alex Light53cb16b2014-06-12 11:26:29 -070023
24#include <string>
25#include <vector>
26
Andreas Gampe46ee31b2016-12-14 10:11:49 -080027#include "android-base/stringprintf.h"
Andreas Gampe9186ced2016-12-12 14:28:21 -080028#include "android-base/strings.h"
29
Mathieu Chartierc7853442015-03-27 14:35:38 -070030#include "art_field-inl.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070031#include "art_method-inl.h"
Ian Rogersc7dd2952014-10-21 23:31:19 -070032#include "base/dumpable.h"
Andreas Gampeb8cc1752017-04-26 21:28:50 -070033#include "base/memory_tool.h"
Alex Lighta59dd802014-07-02 16:28:08 -070034#include "base/scoped_flock.h"
Alex Light53cb16b2014-06-12 11:26:29 -070035#include "base/stringpiece.h"
Ian Rogersd4c4d952014-10-16 20:31:53 -070036#include "base/unix_file/fd_file.h"
David Brazdil7b49e6c2016-09-01 11:06:18 +010037#include "base/unix_file/random_access_file_utils.h"
Alex Light53cb16b2014-06-12 11:26:29 -070038#include "elf_utils.h"
39#include "elf_file.h"
Tong Shen62d1ca32014-09-03 17:24:56 -070040#include "elf_file_impl.h"
Ian Rogerse63db272014-07-15 15:36:11 -070041#include "gc/space/image_space.h"
Mathieu Chartier4a26f172016-01-26 14:26:18 -080042#include "image-inl.h"
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -070043#include "mirror/dex_cache.h"
Neil Fuller0e844392016-09-08 13:43:31 +010044#include "mirror/executable.h"
Alex Light53cb16b2014-06-12 11:26:29 -070045#include "mirror/object-inl.h"
Andreas Gampec6ea7d02017-02-01 16:46:28 -080046#include "mirror/object-refvisitor-inl.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070047#include "mirror/method.h"
Alex Light53cb16b2014-06-12 11:26:29 -070048#include "mirror/reference.h"
49#include "noop_compiler_callbacks.h"
50#include "offsets.h"
51#include "os.h"
52#include "runtime.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070053#include "scoped_thread_state_change-inl.h"
Alex Light53cb16b2014-06-12 11:26:29 -070054#include "thread.h"
55#include "utils.h"
56
57namespace art {
58
Alex Light0eb76d22015-08-11 18:03:47 -070059static const OatHeader* GetOatHeader(const ElfFile* elf_file) {
60 uint64_t off = 0;
61 if (!elf_file->GetSectionOffsetAndSize(".rodata", &off, nullptr)) {
62 return nullptr;
63 }
64
65 OatHeader* oat_header = reinterpret_cast<OatHeader*>(elf_file->Begin() + off);
66 return oat_header;
67}
68
Richard Uhler4bc11d02017-02-01 09:53:54 +000069static File* CreateOrOpen(const char* name) {
Jeff Haodcdc85b2015-12-04 14:06:18 -080070 if (OS::FileExists(name)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -080071 return OS::OpenFileReadWrite(name);
72 } else {
Jeff Haodcdc85b2015-12-04 14:06:18 -080073 std::unique_ptr<File> f(OS::CreateEmptyFile(name));
74 if (f.get() != nullptr) {
75 if (fchmod(f->Fd(), 0644) != 0) {
76 PLOG(ERROR) << "Unable to make " << name << " world readable";
Dimitry Ivanov7a1c0142016-03-17 15:59:38 -070077 unlink(name);
Jeff Haodcdc85b2015-12-04 14:06:18 -080078 return nullptr;
79 }
80 }
81 return f.release();
82 }
83}
84
85// Either try to close the file (close=true), or erase it.
86static bool FinishFile(File* file, bool close) {
87 if (close) {
88 if (file->FlushCloseOrErase() != 0) {
89 PLOG(ERROR) << "Failed to flush and close file.";
90 return false;
91 }
92 return true;
93 } else {
94 file->Erase();
95 return false;
96 }
97}
98
David Brazdil7b49e6c2016-09-01 11:06:18 +010099static bool SymlinkFile(const std::string& input_filename, const std::string& output_filename) {
100 if (input_filename == output_filename) {
101 // Input and output are the same, nothing to do.
102 return true;
103 }
104
105 // Unlink the original filename, since we are overwriting it.
106 unlink(output_filename.c_str());
107
108 // Create a symlink from the source file to the target path.
109 if (symlink(input_filename.c_str(), output_filename.c_str()) < 0) {
110 PLOG(ERROR) << "Failed to create symlink " << output_filename << " -> " << input_filename;
111 return false;
112 }
113
114 if (kIsDebugBuild) {
115 LOG(INFO) << "Created symlink " << output_filename << " -> " << input_filename;
116 }
117
118 return true;
119}
120
Andreas Gampe6eb6a392016-02-10 20:18:37 -0800121bool PatchOat::Patch(const std::string& image_location,
122 off_t delta,
123 const std::string& output_directory,
124 InstructionSet isa,
125 TimingLogger* timings) {
Alex Light53cb16b2014-06-12 11:26:29 -0700126 CHECK(Runtime::Current() == nullptr);
Alex Light53cb16b2014-06-12 11:26:29 -0700127 CHECK(!image_location.empty()) << "image file must have a filename.";
128
Alex Lighteefbe392014-07-08 09:53:18 -0700129 TimingLogger::ScopedTiming t("Runtime Setup", timings);
Alex Light53cb16b2014-06-12 11:26:29 -0700130
Andreas Gampe6eb6a392016-02-10 20:18:37 -0800131 CHECK_NE(isa, kNone);
Alex Light53cb16b2014-06-12 11:26:29 -0700132 const char* isa_name = GetInstructionSetString(isa);
Igor Murashkin46774762014-10-22 11:37:02 -0700133
Alex Light53cb16b2014-06-12 11:26:29 -0700134 // Set up the runtime
Ian Rogerse63db272014-07-15 15:36:11 -0700135 RuntimeOptions options;
Alex Light53cb16b2014-06-12 11:26:29 -0700136 NoopCompilerCallbacks callbacks;
137 options.push_back(std::make_pair("compilercallbacks", &callbacks));
138 std::string img = "-Ximage:" + image_location;
139 options.push_back(std::make_pair(img.c_str(), nullptr));
140 options.push_back(std::make_pair("imageinstructionset", reinterpret_cast<const void*>(isa_name)));
Calin Juravle01aaf6e2015-06-19 22:05:39 +0100141 options.push_back(std::make_pair("-Xno-sig-chain", nullptr));
Alex Light53cb16b2014-06-12 11:26:29 -0700142 if (!Runtime::Create(options, false)) {
143 LOG(ERROR) << "Unable to initialize runtime";
144 return false;
145 }
Andreas Gampeb8cc1752017-04-26 21:28:50 -0700146 std::unique_ptr<Runtime> runtime(Runtime::Current());
147
Alex Light53cb16b2014-06-12 11:26:29 -0700148 // Runtime::Create acquired the mutator_lock_ that is normally given away when we Runtime::Start,
149 // give it away now and then switch to a more manageable ScopedObjectAccess.
150 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
151 ScopedObjectAccess soa(Thread::Current());
152
Richard Uhler4bc11d02017-02-01 09:53:54 +0000153 t.NewTiming("Image Patching setup");
Jeff Haodcdc85b2015-12-04 14:06:18 -0800154 std::vector<gc::space::ImageSpace*> spaces = Runtime::Current()->GetHeap()->GetBootImageSpaces();
155 std::map<gc::space::ImageSpace*, std::unique_ptr<File>> space_to_file_map;
156 std::map<gc::space::ImageSpace*, std::unique_ptr<MemMap>> space_to_memmap_map;
157 std::map<gc::space::ImageSpace*, PatchOat> space_to_patchoat_map;
Alex Light53cb16b2014-06-12 11:26:29 -0700158
Jeff Haodcdc85b2015-12-04 14:06:18 -0800159 for (size_t i = 0; i < spaces.size(); ++i) {
160 gc::space::ImageSpace* space = spaces[i];
161 std::string input_image_filename = space->GetImageFilename();
162 std::unique_ptr<File> input_image(OS::OpenFileForReading(input_image_filename.c_str()));
163 if (input_image.get() == nullptr) {
164 LOG(ERROR) << "Unable to open input image file at " << input_image_filename;
Igor Murashkin46774762014-10-22 11:37:02 -0700165 return false;
166 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800167
168 int64_t image_len = input_image->GetLength();
169 if (image_len < 0) {
170 LOG(ERROR) << "Error while getting image length";
171 return false;
172 }
173 ImageHeader image_header;
174 if (sizeof(image_header) != input_image->Read(reinterpret_cast<char*>(&image_header),
175 sizeof(image_header), 0)) {
176 LOG(ERROR) << "Unable to read image header from image file " << input_image->GetPath();
177 }
178
179 /*bool is_image_pic = */IsImagePic(image_header, input_image->GetPath());
180 // Nothing special to do right now since the image always needs to get patched.
181 // Perhaps in some far-off future we may have images with relative addresses that are true-PIC.
182
183 // Create the map where we will write the image patches to.
184 std::string error_msg;
185 std::unique_ptr<MemMap> image(MemMap::MapFile(image_len,
186 PROT_READ | PROT_WRITE,
187 MAP_PRIVATE,
188 input_image->Fd(),
189 0,
190 /*low_4gb*/false,
191 input_image->GetPath().c_str(),
192 &error_msg));
193 if (image.get() == nullptr) {
194 LOG(ERROR) << "Unable to map image file " << input_image->GetPath() << " : " << error_msg;
195 return false;
196 }
197 space_to_file_map.emplace(space, std::move(input_image));
198 space_to_memmap_map.emplace(space, std::move(image));
Igor Murashkin46774762014-10-22 11:37:02 -0700199 }
200
Richard Uhler4bc11d02017-02-01 09:53:54 +0000201 // Symlink PIC oat and vdex files and patch the image spaces in memory.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800202 for (size_t i = 0; i < spaces.size(); ++i) {
203 gc::space::ImageSpace* space = spaces[i];
204 std::string input_image_filename = space->GetImageFilename();
David Brazdil7b49e6c2016-09-01 11:06:18 +0100205 std::string input_vdex_filename =
206 ImageHeader::GetVdexLocationFromImageLocation(input_image_filename);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800207 std::string input_oat_filename =
208 ImageHeader::GetOatLocationFromImageLocation(input_image_filename);
209 std::unique_ptr<File> input_oat_file(OS::OpenFileForReading(input_oat_filename.c_str()));
210 if (input_oat_file.get() == nullptr) {
211 LOG(ERROR) << "Unable to open input oat file at " << input_oat_filename;
212 return false;
213 }
214 std::string error_msg;
215 std::unique_ptr<ElfFile> elf(ElfFile::Open(input_oat_file.get(),
216 PROT_READ | PROT_WRITE, MAP_PRIVATE, &error_msg));
217 if (elf.get() == nullptr) {
218 LOG(ERROR) << "Unable to open oat file " << input_oat_file->GetPath() << " : " << error_msg;
219 return false;
220 }
221
Jeff Haodcdc85b2015-12-04 14:06:18 -0800222 MaybePic is_oat_pic = IsOatPic(elf.get());
223 if (is_oat_pic >= ERROR_FIRST) {
224 // Error logged by IsOatPic
225 return false;
Richard Uhler4bc11d02017-02-01 09:53:54 +0000226 } else if (is_oat_pic == NOT_PIC) {
227 LOG(ERROR) << "patchoat cannot be used on non-PIC oat file: " << input_oat_file->GetPath();
228 return false;
229 } else {
230 CHECK(is_oat_pic == PIC);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800231
Richard Uhler4bc11d02017-02-01 09:53:54 +0000232 // Create a symlink.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800233 std::string converted_image_filename = space->GetImageLocation();
234 std::replace(converted_image_filename.begin() + 1, converted_image_filename.end(), '/', '@');
235 std::string output_image_filename = output_directory +
Andreas Gampe9186ced2016-12-12 14:28:21 -0800236 (android::base::StartsWith(converted_image_filename, "/") ? "" : "/") +
237 converted_image_filename;
David Brazdil7b49e6c2016-09-01 11:06:18 +0100238 std::string output_vdex_filename =
239 ImageHeader::GetVdexLocationFromImageLocation(output_image_filename);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800240 std::string output_oat_filename =
241 ImageHeader::GetOatLocationFromImageLocation(output_image_filename);
242
243 if (!ReplaceOatFileWithSymlink(input_oat_file->GetPath(),
Richard Uhler4bc11d02017-02-01 09:53:54 +0000244 output_oat_filename) ||
David Brazdil7b49e6c2016-09-01 11:06:18 +0100245 !SymlinkFile(input_vdex_filename, output_vdex_filename)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800246 // Errors already logged by above call.
247 return false;
248 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800249 }
250
251 PatchOat& p = space_to_patchoat_map.emplace(space,
252 PatchOat(
253 isa,
Jeff Haodcdc85b2015-12-04 14:06:18 -0800254 space_to_memmap_map.find(space)->second.get(),
255 space->GetLiveBitmap(),
256 space->GetMemMap(),
257 delta,
258 &space_to_memmap_map,
259 timings)).first->second;
260
Richard Uhler4bc11d02017-02-01 09:53:54 +0000261 t.NewTiming("Patching image");
Jeff Haodcdc85b2015-12-04 14:06:18 -0800262 if (!p.PatchImage(i == 0)) {
263 LOG(ERROR) << "Failed to patch image file " << input_image_filename;
264 return false;
265 }
Alex Light53cb16b2014-06-12 11:26:29 -0700266 }
267
Richard Uhler4bc11d02017-02-01 09:53:54 +0000268 // Write the patched image spaces.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800269 for (size_t i = 0; i < spaces.size(); ++i) {
270 gc::space::ImageSpace* space = spaces[i];
Jeff Haodcdc85b2015-12-04 14:06:18 -0800271
Richard Uhler4bc11d02017-02-01 09:53:54 +0000272 t.NewTiming("Writing image");
Jeff Haodcdc85b2015-12-04 14:06:18 -0800273 std::string converted_image_filename = space->GetImageLocation();
274 std::replace(converted_image_filename.begin() + 1, converted_image_filename.end(), '/', '@');
275 std::string output_image_filename = output_directory +
Andreas Gampe9186ced2016-12-12 14:28:21 -0800276 (android::base::StartsWith(converted_image_filename, "/") ? "" : "/") +
277 converted_image_filename;
Richard Uhler4bc11d02017-02-01 09:53:54 +0000278 std::unique_ptr<File> output_image_file(CreateOrOpen(output_image_filename.c_str()));
Jeff Haodcdc85b2015-12-04 14:06:18 -0800279 if (output_image_file.get() == nullptr) {
280 LOG(ERROR) << "Failed to open output image file at " << output_image_filename;
281 return false;
282 }
283
284 PatchOat& p = space_to_patchoat_map.find(space)->second;
285
Serdjuk, Nikolay Yd12f9c12016-03-22 10:06:33 +0600286 bool success = p.WriteImage(output_image_file.get());
287 success = FinishFile(output_image_file.get(), success);
288 if (!success) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800289 return false;
290 }
Alex Light53cb16b2014-06-12 11:26:29 -0700291 }
Andreas Gampeb8cc1752017-04-26 21:28:50 -0700292
293 if (!kIsDebugBuild && !(RUNNING_ON_MEMORY_TOOL && kMemoryToolDetectsLeaks)) {
294 // We want to just exit on non-debug builds, not bringing the runtime down
295 // in an orderly fashion. So release the following fields.
296 runtime.release();
297 }
298
Alex Light53cb16b2014-06-12 11:26:29 -0700299 return true;
300}
301
Alex Light53cb16b2014-06-12 11:26:29 -0700302bool PatchOat::WriteImage(File* out) {
Alex Lighteefbe392014-07-08 09:53:18 -0700303 TimingLogger::ScopedTiming t("Writing image File", timings_);
Alex Lighta59dd802014-07-02 16:28:08 -0700304 std::string error_msg;
305
Alex Lightcf4bf382014-07-24 11:29:14 -0700306 ScopedFlock img_flock;
307 img_flock.Init(out, &error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -0700308
Alex Light53cb16b2014-06-12 11:26:29 -0700309 CHECK(image_ != nullptr);
310 CHECK(out != nullptr);
311 size_t expect = image_->Size();
312 if (out->WriteFully(reinterpret_cast<char*>(image_->Begin()), expect) &&
313 out->SetLength(expect) == 0) {
314 return true;
315 } else {
316 LOG(ERROR) << "Writing to image file " << out->GetPath() << " failed.";
317 return false;
318 }
319}
320
Igor Murashkin46774762014-10-22 11:37:02 -0700321bool PatchOat::IsImagePic(const ImageHeader& image_header, const std::string& image_path) {
322 if (!image_header.CompilePic()) {
323 if (kIsDebugBuild) {
324 LOG(INFO) << "image at location " << image_path << " was *not* compiled pic";
325 }
326 return false;
327 }
328
329 if (kIsDebugBuild) {
330 LOG(INFO) << "image at location " << image_path << " was compiled PIC";
331 }
332
333 return true;
334}
335
336PatchOat::MaybePic PatchOat::IsOatPic(const ElfFile* oat_in) {
337 if (oat_in == nullptr) {
338 LOG(ERROR) << "No ELF input oat fie available";
339 return ERROR_OAT_FILE;
340 }
341
Brian Carlstromf5b0f2c2016-10-14 01:04:26 -0700342 const std::string& file_path = oat_in->GetFilePath();
Igor Murashkin46774762014-10-22 11:37:02 -0700343
344 const OatHeader* oat_header = GetOatHeader(oat_in);
345 if (oat_header == nullptr) {
346 LOG(ERROR) << "Failed to find oat header in oat file " << file_path;
347 return ERROR_OAT_FILE;
348 }
349
350 if (!oat_header->IsValid()) {
351 LOG(ERROR) << "Elf file " << file_path << " has an invalid oat header";
352 return ERROR_OAT_FILE;
353 }
354
355 bool is_pic = oat_header->IsPic();
356 if (kIsDebugBuild) {
357 LOG(INFO) << "Oat file at " << file_path << " is " << (is_pic ? "PIC" : "not pic");
358 }
359
360 return is_pic ? PIC : NOT_PIC;
361}
362
363bool PatchOat::ReplaceOatFileWithSymlink(const std::string& input_oat_filename,
Richard Uhler4bc11d02017-02-01 09:53:54 +0000364 const std::string& output_oat_filename) {
Igor Murashkin46774762014-10-22 11:37:02 -0700365 // Delete the original file, since we won't need it.
Dimitry Ivanov7a1c0142016-03-17 15:59:38 -0700366 unlink(output_oat_filename.c_str());
Igor Murashkin46774762014-10-22 11:37:02 -0700367
368 // Create a symlink from the old oat to the new oat
369 if (symlink(input_oat_filename.c_str(), output_oat_filename.c_str()) < 0) {
370 int err = errno;
371 LOG(ERROR) << "Failed to create symlink at " << output_oat_filename
372 << " error(" << err << "): " << strerror(err);
373 return false;
374 }
375
376 if (kIsDebugBuild) {
377 LOG(INFO) << "Created symlink " << output_oat_filename << " -> " << input_oat_filename;
378 }
379
380 return true;
381}
382
Vladimir Markoad06b982016-11-17 16:38:59 +0000383class PatchOat::PatchOatArtFieldVisitor : public ArtFieldVisitor {
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700384 public:
385 explicit PatchOatArtFieldVisitor(PatchOat* patch_oat) : patch_oat_(patch_oat) {}
386
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700387 void Visit(ArtField* field) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700388 ArtField* const dest = patch_oat_->RelocatedCopyOf(field);
Mathieu Chartier3398c782016-09-30 10:27:43 -0700389 dest->SetDeclaringClass(
Mathieu Chartier1cc62e42016-10-03 18:01:28 -0700390 patch_oat_->RelocatedAddressOfPointer(field->GetDeclaringClass().Ptr()));
Mathieu Chartiere401d142015-04-22 13:56:20 -0700391 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700392
393 private:
394 PatchOat* const patch_oat_;
395};
396
397void PatchOat::PatchArtFields(const ImageHeader* image_header) {
398 PatchOatArtFieldVisitor visitor(this);
Mathieu Chartiere42888f2016-04-14 10:49:19 -0700399 image_header->VisitPackedArtFields(&visitor, heap_->Begin());
Mathieu Chartiere401d142015-04-22 13:56:20 -0700400}
401
Vladimir Markoad06b982016-11-17 16:38:59 +0000402class PatchOat::PatchOatArtMethodVisitor : public ArtMethodVisitor {
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700403 public:
404 explicit PatchOatArtMethodVisitor(PatchOat* patch_oat) : patch_oat_(patch_oat) {}
405
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700406 void Visit(ArtMethod* method) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700407 ArtMethod* const dest = patch_oat_->RelocatedCopyOf(method);
408 patch_oat_->FixupMethod(method, dest);
409 }
410
411 private:
412 PatchOat* const patch_oat_;
413};
414
Mathieu Chartiere401d142015-04-22 13:56:20 -0700415void PatchOat::PatchArtMethods(const ImageHeader* image_header) {
Andreas Gampe542451c2016-07-26 09:02:02 -0700416 const PointerSize pointer_size = InstructionSetPointerSize(isa_);
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700417 PatchOatArtMethodVisitor visitor(this);
Mathieu Chartiere42888f2016-04-14 10:49:19 -0700418 image_header->VisitPackedArtMethods(&visitor, heap_->Begin(), pointer_size);
419}
420
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +0000421void PatchOat::PatchImTables(const ImageHeader* image_header) {
Andreas Gampe542451c2016-07-26 09:02:02 -0700422 const PointerSize pointer_size = InstructionSetPointerSize(isa_);
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +0000423 // We can safely walk target image since the conflict tables are independent.
424 image_header->VisitPackedImTables(
425 [this](ArtMethod* method) {
426 return RelocatedAddressOfPointer(method);
427 },
428 image_->Begin(),
429 pointer_size);
430}
431
Mathieu Chartiere42888f2016-04-14 10:49:19 -0700432void PatchOat::PatchImtConflictTables(const ImageHeader* image_header) {
Andreas Gampe542451c2016-07-26 09:02:02 -0700433 const PointerSize pointer_size = InstructionSetPointerSize(isa_);
Mathieu Chartiere42888f2016-04-14 10:49:19 -0700434 // We can safely walk target image since the conflict tables are independent.
435 image_header->VisitPackedImtConflictTables(
436 [this](ArtMethod* method) {
437 return RelocatedAddressOfPointer(method);
438 },
439 image_->Begin(),
440 pointer_size);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700441}
442
Vladimir Markoad06b982016-11-17 16:38:59 +0000443class PatchOat::FixupRootVisitor : public RootVisitor {
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700444 public:
445 explicit FixupRootVisitor(const PatchOat* patch_oat) : patch_oat_(patch_oat) {
446 }
447
448 void VisitRoots(mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700449 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700450 for (size_t i = 0; i < count; ++i) {
451 *roots[i] = patch_oat_->RelocatedAddressOfPointer(*roots[i]);
452 }
453 }
454
455 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots, size_t count,
456 const RootInfo& info ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700457 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700458 for (size_t i = 0; i < count; ++i) {
459 roots[i]->Assign(patch_oat_->RelocatedAddressOfPointer(roots[i]->AsMirrorPtr()));
460 }
461 }
462
463 private:
464 const PatchOat* const patch_oat_;
465};
466
467void PatchOat::PatchInternedStrings(const ImageHeader* image_header) {
468 const auto& section = image_header->GetImageSection(ImageHeader::kSectionInternedStrings);
469 InternTable temp_table;
470 // Note that we require that ReadFromMemory does not make an internal copy of the elements.
471 // This also relies on visit roots not doing any verification which could fail after we update
472 // the roots to be the image addresses.
Mathieu Chartierea0831f2015-12-29 13:17:37 -0800473 temp_table.AddTableFromMemory(image_->Begin() + section.Offset());
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700474 FixupRootVisitor visitor(this);
475 temp_table.VisitRoots(&visitor, kVisitRootFlagAllRoots);
476}
477
Mathieu Chartier208a5cb2015-12-02 15:44:07 -0800478void PatchOat::PatchClassTable(const ImageHeader* image_header) {
479 const auto& section = image_header->GetImageSection(ImageHeader::kSectionClassTable);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800480 if (section.Size() == 0) {
481 return;
482 }
Mathieu Chartier208a5cb2015-12-02 15:44:07 -0800483 // Note that we require that ReadFromMemory does not make an internal copy of the elements.
484 // This also relies on visit roots not doing any verification which could fail after we update
485 // the roots to be the image addresses.
486 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
487 ClassTable temp_table;
488 temp_table.ReadFromMemory(image_->Begin() + section.Offset());
489 FixupRootVisitor visitor(this);
Mathieu Chartier58c3f6a2016-12-01 14:21:11 -0800490 temp_table.VisitRoots(UnbufferedRootVisitor(&visitor, RootInfo(kRootUnknown)));
Mathieu Chartier208a5cb2015-12-02 15:44:07 -0800491}
492
493
Vladimir Markoad06b982016-11-17 16:38:59 +0000494class PatchOat::RelocatedPointerVisitor {
Mathieu Chartier4b00d342015-11-13 10:42:08 -0800495 public:
496 explicit RelocatedPointerVisitor(PatchOat* patch_oat) : patch_oat_(patch_oat) {}
497
498 template <typename T>
Mathieu Chartier8c19d242017-03-06 12:35:10 -0800499 T* operator()(T* ptr, void** dest_addr ATTRIBUTE_UNUSED = 0) const {
Mathieu Chartier4b00d342015-11-13 10:42:08 -0800500 return patch_oat_->RelocatedAddressOfPointer(ptr);
501 }
502
503 private:
504 PatchOat* const patch_oat_;
505};
506
Mathieu Chartierc7853442015-03-27 14:35:38 -0700507void PatchOat::PatchDexFileArrays(mirror::ObjectArray<mirror::Object>* img_roots) {
508 auto* dex_caches = down_cast<mirror::ObjectArray<mirror::DexCache>*>(
509 img_roots->Get(ImageHeader::kDexCaches));
Andreas Gampe542451c2016-07-26 09:02:02 -0700510 const PointerSize pointer_size = InstructionSetPointerSize(isa_);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700511 for (size_t i = 0, count = dex_caches->GetLength(); i < count; ++i) {
Vladimir Marko05792b92015-08-03 11:56:49 +0100512 auto* orig_dex_cache = dex_caches->GetWithoutChecks(i);
513 auto* copy_dex_cache = RelocatedCopyOf(orig_dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +0100514 // Though the DexCache array fields are usually treated as native pointers, we set the full
515 // 64-bit values here, clearing the top 32 bits for 32-bit targets. The zero-extension is
516 // done by casting to the unsigned type uintptr_t before casting to int64_t, i.e.
517 // static_cast<int64_t>(reinterpret_cast<uintptr_t>(image_begin_ + offset))).
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -0700518 mirror::StringDexCacheType* orig_strings = orig_dex_cache->GetStrings();
519 mirror::StringDexCacheType* relocated_strings = RelocatedAddressOfPointer(orig_strings);
Vladimir Marko05792b92015-08-03 11:56:49 +0100520 copy_dex_cache->SetField64<false>(
521 mirror::DexCache::StringsOffset(),
522 static_cast<int64_t>(reinterpret_cast<uintptr_t>(relocated_strings)));
523 if (orig_strings != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -0800524 orig_dex_cache->FixupStrings(RelocatedCopyOf(orig_strings), RelocatedPointerVisitor(this));
Mathieu Chartierc7853442015-03-27 14:35:38 -0700525 }
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000526 mirror::TypeDexCacheType* orig_types = orig_dex_cache->GetResolvedTypes();
527 mirror::TypeDexCacheType* relocated_types = RelocatedAddressOfPointer(orig_types);
Vladimir Marko05792b92015-08-03 11:56:49 +0100528 copy_dex_cache->SetField64<false>(
529 mirror::DexCache::ResolvedTypesOffset(),
530 static_cast<int64_t>(reinterpret_cast<uintptr_t>(relocated_types)));
531 if (orig_types != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -0800532 orig_dex_cache->FixupResolvedTypes(RelocatedCopyOf(orig_types),
533 RelocatedPointerVisitor(this));
Vladimir Marko05792b92015-08-03 11:56:49 +0100534 }
535 ArtMethod** orig_methods = orig_dex_cache->GetResolvedMethods();
536 ArtMethod** relocated_methods = RelocatedAddressOfPointer(orig_methods);
537 copy_dex_cache->SetField64<false>(
538 mirror::DexCache::ResolvedMethodsOffset(),
539 static_cast<int64_t>(reinterpret_cast<uintptr_t>(relocated_methods)));
540 if (orig_methods != nullptr) {
541 ArtMethod** copy_methods = RelocatedCopyOf(orig_methods);
542 for (size_t j = 0, num = orig_dex_cache->NumResolvedMethods(); j != num; ++j) {
543 ArtMethod* orig = mirror::DexCache::GetElementPtrSize(orig_methods, j, pointer_size);
544 ArtMethod* copy = RelocatedAddressOfPointer(orig);
545 mirror::DexCache::SetElementPtrSize(copy_methods, j, copy, pointer_size);
546 }
547 }
Vladimir Markof44d36c2017-03-14 14:18:46 +0000548 mirror::FieldDexCacheType* orig_fields = orig_dex_cache->GetResolvedFields();
549 mirror::FieldDexCacheType* relocated_fields = RelocatedAddressOfPointer(orig_fields);
Vladimir Marko05792b92015-08-03 11:56:49 +0100550 copy_dex_cache->SetField64<false>(
551 mirror::DexCache::ResolvedFieldsOffset(),
552 static_cast<int64_t>(reinterpret_cast<uintptr_t>(relocated_fields)));
553 if (orig_fields != nullptr) {
Vladimir Markof44d36c2017-03-14 14:18:46 +0000554 mirror::FieldDexCacheType* copy_fields = RelocatedCopyOf(orig_fields);
Vladimir Marko05792b92015-08-03 11:56:49 +0100555 for (size_t j = 0, num = orig_dex_cache->NumResolvedFields(); j != num; ++j) {
Vladimir Markof44d36c2017-03-14 14:18:46 +0000556 mirror::FieldDexCachePair orig =
557 mirror::DexCache::GetNativePairPtrSize(orig_fields, j, pointer_size);
558 mirror::FieldDexCachePair copy(RelocatedAddressOfPointer(orig.object), orig.index);
559 mirror::DexCache::SetNativePairPtrSize(copy_fields, j, copy, pointer_size);
Vladimir Marko05792b92015-08-03 11:56:49 +0100560 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700561 }
Narayan Kamath7fe56582016-10-14 18:49:12 +0100562 mirror::MethodTypeDexCacheType* orig_method_types = orig_dex_cache->GetResolvedMethodTypes();
563 mirror::MethodTypeDexCacheType* relocated_method_types =
564 RelocatedAddressOfPointer(orig_method_types);
565 copy_dex_cache->SetField64<false>(
566 mirror::DexCache::ResolvedMethodTypesOffset(),
567 static_cast<int64_t>(reinterpret_cast<uintptr_t>(relocated_method_types)));
568 if (orig_method_types != nullptr) {
569 orig_dex_cache->FixupResolvedMethodTypes(RelocatedCopyOf(orig_method_types),
570 RelocatedPointerVisitor(this));
571 }
Orion Hodsonc069a302017-01-18 09:23:12 +0000572
573 GcRoot<mirror::CallSite>* orig_call_sites = orig_dex_cache->GetResolvedCallSites();
574 GcRoot<mirror::CallSite>* relocated_call_sites = RelocatedAddressOfPointer(orig_call_sites);
575 copy_dex_cache->SetField64<false>(
576 mirror::DexCache::ResolvedCallSitesOffset(),
577 static_cast<int64_t>(reinterpret_cast<uintptr_t>(relocated_call_sites)));
578 if (orig_call_sites != nullptr) {
579 orig_dex_cache->FixupResolvedCallSites(RelocatedCopyOf(orig_call_sites),
580 RelocatedPointerVisitor(this));
581 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700582 }
583}
584
Jeff Haodcdc85b2015-12-04 14:06:18 -0800585bool PatchOat::PatchImage(bool primary_image) {
Alex Light53cb16b2014-06-12 11:26:29 -0700586 ImageHeader* image_header = reinterpret_cast<ImageHeader*>(image_->Begin());
587 CHECK_GT(image_->Size(), sizeof(ImageHeader));
588 // These are the roots from the original file.
Mathieu Chartierc7853442015-03-27 14:35:38 -0700589 auto* img_roots = image_header->GetImageRoots();
Alex Light53cb16b2014-06-12 11:26:29 -0700590 image_header->RelocateImage(delta_);
591
Mathieu Chartierc7853442015-03-27 14:35:38 -0700592 PatchArtFields(image_header);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700593 PatchArtMethods(image_header);
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +0000594 PatchImTables(image_header);
Mathieu Chartiere42888f2016-04-14 10:49:19 -0700595 PatchImtConflictTables(image_header);
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700596 PatchInternedStrings(image_header);
Mathieu Chartier208a5cb2015-12-02 15:44:07 -0800597 PatchClassTable(image_header);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700598 // Patch dex file int/long arrays which point to ArtFields.
599 PatchDexFileArrays(img_roots);
600
Jeff Haodcdc85b2015-12-04 14:06:18 -0800601 if (primary_image) {
602 VisitObject(img_roots);
603 }
604
Alex Light53cb16b2014-06-12 11:26:29 -0700605 if (!image_header->IsValid()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800606 LOG(ERROR) << "relocation renders image header invalid";
Alex Light53cb16b2014-06-12 11:26:29 -0700607 return false;
608 }
609
610 {
Alex Lighteefbe392014-07-08 09:53:18 -0700611 TimingLogger::ScopedTiming t("Walk Bitmap", timings_);
Alex Light53cb16b2014-06-12 11:26:29 -0700612 // Walk the bitmap.
613 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
614 bitmap_->Walk(PatchOat::BitmapCallback, this);
615 }
616 return true;
617}
618
Alex Light53cb16b2014-06-12 11:26:29 -0700619
Mathieu Chartier31e88222016-10-14 18:43:19 -0700620void PatchOat::PatchVisitor::operator() (ObjPtr<mirror::Object> obj,
621 MemberOffset off,
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700622 bool is_static_unused ATTRIBUTE_UNUSED) const {
Alex Light53cb16b2014-06-12 11:26:29 -0700623 mirror::Object* referent = obj->GetFieldObject<mirror::Object, kVerifyNone>(off);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700624 mirror::Object* moved_object = patcher_->RelocatedAddressOfPointer(referent);
Alex Light53cb16b2014-06-12 11:26:29 -0700625 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(off, moved_object);
626}
627
Mathieu Chartier31e88222016-10-14 18:43:19 -0700628void PatchOat::PatchVisitor::operator() (ObjPtr<mirror::Class> cls ATTRIBUTE_UNUSED,
629 ObjPtr<mirror::Reference> ref) const {
Alex Light53cb16b2014-06-12 11:26:29 -0700630 MemberOffset off = mirror::Reference::ReferentOffset();
631 mirror::Object* referent = ref->GetReferent();
Mathieu Chartiera13abba2016-04-21 10:23:16 -0700632 DCHECK(referent == nullptr ||
633 Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(referent)) << referent;
Mathieu Chartierc7853442015-03-27 14:35:38 -0700634 mirror::Object* moved_object = patcher_->RelocatedAddressOfPointer(referent);
Alex Light53cb16b2014-06-12 11:26:29 -0700635 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(off, moved_object);
636}
637
Alex Light53cb16b2014-06-12 11:26:29 -0700638// Called by BitmapCallback
639void PatchOat::VisitObject(mirror::Object* object) {
640 mirror::Object* copy = RelocatedCopyOf(object);
641 CHECK(copy != nullptr);
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700642 if (kUseBakerReadBarrier) {
643 object->AssertReadBarrierState();
Alex Light53cb16b2014-06-12 11:26:29 -0700644 }
645 PatchOat::PatchVisitor visitor(this, copy);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -0700646 object->VisitReferences<kVerifyNone>(visitor, visitor);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700647 if (object->IsClass<kVerifyNone>()) {
Andreas Gampe542451c2016-07-26 09:02:02 -0700648 const PointerSize pointer_size = InstructionSetPointerSize(isa_);
Mathieu Chartier4b00d342015-11-13 10:42:08 -0800649 mirror::Class* klass = object->AsClass();
650 mirror::Class* copy_klass = down_cast<mirror::Class*>(copy);
651 RelocatedPointerVisitor native_visitor(this);
652 klass->FixupNativePointers(copy_klass, pointer_size, native_visitor);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700653 auto* vtable = klass->GetVTable();
654 if (vtable != nullptr) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800655 vtable->Fixup(RelocatedCopyOfFollowImages(vtable), pointer_size, native_visitor);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700656 }
Mathieu Chartier6beced42016-11-15 15:51:31 -0800657 mirror::IfTable* iftable = klass->GetIfTable();
658 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
659 if (iftable->GetMethodArrayCount(i) > 0) {
660 auto* method_array = iftable->GetMethodArray(i);
661 CHECK(method_array != nullptr);
662 method_array->Fixup(RelocatedCopyOfFollowImages(method_array),
663 pointer_size,
664 native_visitor);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700665 }
666 }
Mathieu Chartier4b00d342015-11-13 10:42:08 -0800667 } else if (object->GetClass() == mirror::Method::StaticClass() ||
668 object->GetClass() == mirror::Constructor::StaticClass()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700669 // Need to go update the ArtMethod.
Neil Fuller0e844392016-09-08 13:43:31 +0100670 auto* dest = down_cast<mirror::Executable*>(copy);
671 auto* src = down_cast<mirror::Executable*>(object);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700672 dest->SetArtMethod(RelocatedAddressOfPointer(src->GetArtMethod()));
Alex Light53cb16b2014-06-12 11:26:29 -0700673 }
674}
675
Mathieu Chartiere401d142015-04-22 13:56:20 -0700676void PatchOat::FixupMethod(ArtMethod* object, ArtMethod* copy) {
Andreas Gampe542451c2016-07-26 09:02:02 -0700677 const PointerSize pointer_size = InstructionSetPointerSize(isa_);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700678 copy->CopyFrom(object, pointer_size);
Alex Light53cb16b2014-06-12 11:26:29 -0700679 // Just update the entry points if it looks like we should.
Alex Lighteefbe392014-07-08 09:53:18 -0700680 // TODO: sanity check all the pointers' values
Mathieu Chartiere401d142015-04-22 13:56:20 -0700681 copy->SetDeclaringClass(RelocatedAddressOfPointer(object->GetDeclaringClass()));
Vladimir Marko05792b92015-08-03 11:56:49 +0100682 copy->SetDexCacheResolvedMethods(
683 RelocatedAddressOfPointer(object->GetDexCacheResolvedMethods(pointer_size)), pointer_size);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700684 copy->SetEntryPointFromQuickCompiledCodePtrSize(RelocatedAddressOfPointer(
685 object->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size)), pointer_size);
Mathieu Chartiere42888f2016-04-14 10:49:19 -0700686 // No special handling for IMT conflict table since all pointers are moved by the same offset.
Andreas Gampe75f08852016-07-19 08:06:07 -0700687 copy->SetDataPtrSize(RelocatedAddressOfPointer(
688 object->GetDataPtrSize(pointer_size)), pointer_size);
Alex Light53cb16b2014-06-12 11:26:29 -0700689}
690
Alex Light53cb16b2014-06-12 11:26:29 -0700691static int orig_argc;
692static char** orig_argv;
693
694static std::string CommandLine() {
695 std::vector<std::string> command;
696 for (int i = 0; i < orig_argc; ++i) {
697 command.push_back(orig_argv[i]);
698 }
Andreas Gampe9186ced2016-12-12 14:28:21 -0800699 return android::base::Join(command, ' ');
Alex Light53cb16b2014-06-12 11:26:29 -0700700}
701
702static void UsageErrorV(const char* fmt, va_list ap) {
703 std::string error;
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800704 android::base::StringAppendV(&error, fmt, ap);
Alex Light53cb16b2014-06-12 11:26:29 -0700705 LOG(ERROR) << error;
706}
707
708static void UsageError(const char* fmt, ...) {
709 va_list ap;
710 va_start(ap, fmt);
711 UsageErrorV(fmt, ap);
712 va_end(ap);
713}
714
Andreas Gampe794ad762015-02-23 08:12:24 -0800715NO_RETURN static void Usage(const char *fmt, ...) {
Alex Light53cb16b2014-06-12 11:26:29 -0700716 va_list ap;
717 va_start(ap, fmt);
718 UsageErrorV(fmt, ap);
719 va_end(ap);
720
721 UsageError("Command: %s", CommandLine().c_str());
722 UsageError("Usage: patchoat [options]...");
723 UsageError("");
724 UsageError(" --instruction-set=<isa>: Specifies the instruction set the patched code is");
Richard Uhler4bc11d02017-02-01 09:53:54 +0000725 UsageError(" compiled for (required).");
Alex Light53cb16b2014-06-12 11:26:29 -0700726 UsageError("");
727 UsageError(" --input-image-location=<file.art>: Specifies the 'location' of the image file to");
Richard Uhler4bc11d02017-02-01 09:53:54 +0000728 UsageError(" be patched.");
Alex Light53cb16b2014-06-12 11:26:29 -0700729 UsageError("");
730 UsageError(" --output-image-file=<file.art>: Specifies the exact file to write the patched");
731 UsageError(" image file to.");
732 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700733 UsageError(" --base-offset-delta=<delta>: Specify the amount to change the old base-offset by.");
734 UsageError(" This value may be negative.");
735 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700736 UsageError(" --dump-timings: dump out patch timing information");
737 UsageError("");
738 UsageError(" --no-dump-timings: do not dump out patch timing information");
739 UsageError("");
740
741 exit(EXIT_FAILURE);
742}
743
Andreas Gampe6eb6a392016-02-10 20:18:37 -0800744static int patchoat_image(TimingLogger& timings,
745 InstructionSet isa,
746 const std::string& input_image_location,
747 const std::string& output_image_filename,
748 off_t base_delta,
749 bool base_delta_set,
750 bool debug) {
751 CHECK(!input_image_location.empty());
752 if (output_image_filename.empty()) {
753 Usage("Image patching requires --output-image-file");
754 }
755
756 if (!base_delta_set) {
757 Usage("Must supply a desired new offset or delta.");
758 }
759
760 if (!IsAligned<kPageSize>(base_delta)) {
761 Usage("Base offset/delta must be aligned to a pagesize (0x%08x) boundary.", kPageSize);
762 }
763
764 if (debug) {
765 LOG(INFO) << "moving offset by " << base_delta
766 << " (0x" << std::hex << base_delta << ") bytes or "
767 << std::dec << (base_delta/kPageSize) << " pages.";
768 }
769
770 TimingLogger::ScopedTiming pt("patch image and oat", &timings);
771
772 std::string output_directory =
Andreas Gampeca620d72016-11-08 08:09:33 -0800773 output_image_filename.substr(0, output_image_filename.find_last_of('/'));
Andreas Gampe6eb6a392016-02-10 20:18:37 -0800774 bool ret = PatchOat::Patch(input_image_location, base_delta, output_directory, isa, &timings);
775
776 if (kIsDebugBuild) {
777 LOG(INFO) << "Exiting with return ... " << ret;
778 }
779 return ret ? EXIT_SUCCESS : EXIT_FAILURE;
780}
781
Alex Lighteefbe392014-07-08 09:53:18 -0700782static int patchoat(int argc, char **argv) {
David Sehrf57589f2016-10-17 10:09:33 -0700783 InitLogging(argv, Runtime::Aborter);
Mathieu Chartier6e88ef62014-10-14 15:01:24 -0700784 MemMap::Init();
Alex Light53cb16b2014-06-12 11:26:29 -0700785 const bool debug = kIsDebugBuild;
786 orig_argc = argc;
787 orig_argv = argv;
788 TimingLogger timings("patcher", false, false);
789
Alex Light53cb16b2014-06-12 11:26:29 -0700790 // Skip over the command name.
791 argv++;
792 argc--;
793
794 if (argc == 0) {
795 Usage("No arguments specified");
796 }
797
798 timings.StartTiming("Patchoat");
799
800 // cmd line args
801 bool isa_set = false;
802 InstructionSet isa = kNone;
Alex Light53cb16b2014-06-12 11:26:29 -0700803 std::string input_image_location;
Alex Light53cb16b2014-06-12 11:26:29 -0700804 std::string output_image_filename;
Alex Light53cb16b2014-06-12 11:26:29 -0700805 off_t base_delta = 0;
806 bool base_delta_set = false;
Alex Light53cb16b2014-06-12 11:26:29 -0700807 bool dump_timings = kIsDebugBuild;
808
Ian Rogersd4c4d952014-10-16 20:31:53 -0700809 for (int i = 0; i < argc; ++i) {
Alex Light53cb16b2014-06-12 11:26:29 -0700810 const StringPiece option(argv[i]);
811 const bool log_options = false;
812 if (log_options) {
813 LOG(INFO) << "patchoat: option[" << i << "]=" << argv[i];
814 }
Alex Light53cb16b2014-06-12 11:26:29 -0700815 if (option.starts_with("--instruction-set=")) {
816 isa_set = true;
817 const char* isa_str = option.substr(strlen("--instruction-set=")).data();
Andreas Gampe20c89302014-08-19 17:28:06 -0700818 isa = GetInstructionSetFromString(isa_str);
819 if (isa == kNone) {
820 Usage("Unknown or invalid instruction set %s", isa_str);
Alex Light53cb16b2014-06-12 11:26:29 -0700821 }
Alex Light53cb16b2014-06-12 11:26:29 -0700822 } else if (option.starts_with("--input-image-location=")) {
823 input_image_location = option.substr(strlen("--input-image-location=")).data();
Alex Light53cb16b2014-06-12 11:26:29 -0700824 } else if (option.starts_with("--output-image-file=")) {
Alex Light53cb16b2014-06-12 11:26:29 -0700825 output_image_filename = option.substr(strlen("--output-image-file=")).data();
Alex Light53cb16b2014-06-12 11:26:29 -0700826 } else if (option.starts_with("--base-offset-delta=")) {
827 const char* base_delta_str = option.substr(strlen("--base-offset-delta=")).data();
828 base_delta_set = true;
829 if (!ParseInt(base_delta_str, &base_delta)) {
830 Usage("Failed to parse --base-offset-delta argument '%s' as an off_t", base_delta_str);
831 }
Alex Light53cb16b2014-06-12 11:26:29 -0700832 } else if (option == "--dump-timings") {
833 dump_timings = true;
834 } else if (option == "--no-dump-timings") {
835 dump_timings = false;
836 } else {
837 Usage("Unknown argument %s", option.data());
838 }
839 }
840
Andreas Gampe6eb6a392016-02-10 20:18:37 -0800841 // The instruction set is mandatory. This simplifies things...
842 if (!isa_set) {
843 Usage("Instruction set must be set.");
Alex Light53cb16b2014-06-12 11:26:29 -0700844 }
845
Richard Uhler4bc11d02017-02-01 09:53:54 +0000846 int ret = patchoat_image(timings,
847 isa,
848 input_image_location,
849 output_image_filename,
850 base_delta,
851 base_delta_set,
852 debug);
Alex Light53cb16b2014-06-12 11:26:29 -0700853
Andreas Gampe6eb6a392016-02-10 20:18:37 -0800854 timings.EndTiming();
855 if (dump_timings) {
856 LOG(INFO) << Dumpable<TimingLogger>(timings);
Alex Light53cb16b2014-06-12 11:26:29 -0700857 }
858
Andreas Gampe6eb6a392016-02-10 20:18:37 -0800859 return ret;
Alex Light53cb16b2014-06-12 11:26:29 -0700860}
861
862} // namespace art
863
864int main(int argc, char **argv) {
865 return art::patchoat(argc, argv);
866}