blob: fbb0978d53ac8808c673f43b8519413a8c85d356 [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"
Alex Lighta59dd802014-07-02 16:28:08 -070033#include "base/scoped_flock.h"
Alex Light53cb16b2014-06-12 11:26:29 -070034#include "base/stringpiece.h"
Ian Rogersd4c4d952014-10-16 20:31:53 -070035#include "base/unix_file/fd_file.h"
David Brazdil7b49e6c2016-09-01 11:06:18 +010036#include "base/unix_file/random_access_file_utils.h"
Alex Light53cb16b2014-06-12 11:26:29 -070037#include "elf_utils.h"
38#include "elf_file.h"
Tong Shen62d1ca32014-09-03 17:24:56 -070039#include "elf_file_impl.h"
Ian Rogerse63db272014-07-15 15:36:11 -070040#include "gc/space/image_space.h"
Mathieu Chartier4a26f172016-01-26 14:26:18 -080041#include "image-inl.h"
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -070042#include "mirror/dex_cache.h"
Neil Fuller0e844392016-09-08 13:43:31 +010043#include "mirror/executable.h"
Alex Light53cb16b2014-06-12 11:26:29 -070044#include "mirror/object-inl.h"
Andreas Gampec6ea7d02017-02-01 16:46:28 -080045#include "mirror/object-refvisitor-inl.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070046#include "mirror/method.h"
Alex Light53cb16b2014-06-12 11:26:29 -070047#include "mirror/reference.h"
48#include "noop_compiler_callbacks.h"
49#include "offsets.h"
50#include "os.h"
51#include "runtime.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070052#include "scoped_thread_state_change-inl.h"
Alex Light53cb16b2014-06-12 11:26:29 -070053#include "thread.h"
54#include "utils.h"
55
56namespace art {
57
Alex Light0eb76d22015-08-11 18:03:47 -070058static const OatHeader* GetOatHeader(const ElfFile* elf_file) {
59 uint64_t off = 0;
60 if (!elf_file->GetSectionOffsetAndSize(".rodata", &off, nullptr)) {
61 return nullptr;
62 }
63
64 OatHeader* oat_header = reinterpret_cast<OatHeader*>(elf_file->Begin() + off);
65 return oat_header;
66}
67
Richard Uhler4bc11d02017-02-01 09:53:54 +000068static File* CreateOrOpen(const char* name) {
Jeff Haodcdc85b2015-12-04 14:06:18 -080069 if (OS::FileExists(name)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -080070 return OS::OpenFileReadWrite(name);
71 } else {
Jeff Haodcdc85b2015-12-04 14:06:18 -080072 std::unique_ptr<File> f(OS::CreateEmptyFile(name));
73 if (f.get() != nullptr) {
74 if (fchmod(f->Fd(), 0644) != 0) {
75 PLOG(ERROR) << "Unable to make " << name << " world readable";
Dimitry Ivanov7a1c0142016-03-17 15:59:38 -070076 unlink(name);
Jeff Haodcdc85b2015-12-04 14:06:18 -080077 return nullptr;
78 }
79 }
80 return f.release();
81 }
82}
83
84// Either try to close the file (close=true), or erase it.
85static bool FinishFile(File* file, bool close) {
86 if (close) {
87 if (file->FlushCloseOrErase() != 0) {
88 PLOG(ERROR) << "Failed to flush and close file.";
89 return false;
90 }
91 return true;
92 } else {
93 file->Erase();
94 return false;
95 }
96}
97
David Brazdil7b49e6c2016-09-01 11:06:18 +010098static bool SymlinkFile(const std::string& input_filename, const std::string& output_filename) {
99 if (input_filename == output_filename) {
100 // Input and output are the same, nothing to do.
101 return true;
102 }
103
104 // Unlink the original filename, since we are overwriting it.
105 unlink(output_filename.c_str());
106
107 // Create a symlink from the source file to the target path.
108 if (symlink(input_filename.c_str(), output_filename.c_str()) < 0) {
109 PLOG(ERROR) << "Failed to create symlink " << output_filename << " -> " << input_filename;
110 return false;
111 }
112
113 if (kIsDebugBuild) {
114 LOG(INFO) << "Created symlink " << output_filename << " -> " << input_filename;
115 }
116
117 return true;
118}
119
Andreas Gampe6eb6a392016-02-10 20:18:37 -0800120bool PatchOat::Patch(const std::string& image_location,
121 off_t delta,
122 const std::string& output_directory,
123 InstructionSet isa,
124 TimingLogger* timings) {
Alex Light53cb16b2014-06-12 11:26:29 -0700125 CHECK(Runtime::Current() == nullptr);
Alex Light53cb16b2014-06-12 11:26:29 -0700126 CHECK(!image_location.empty()) << "image file must have a filename.";
127
Alex Lighteefbe392014-07-08 09:53:18 -0700128 TimingLogger::ScopedTiming t("Runtime Setup", timings);
Alex Light53cb16b2014-06-12 11:26:29 -0700129
Andreas Gampe6eb6a392016-02-10 20:18:37 -0800130 CHECK_NE(isa, kNone);
Alex Light53cb16b2014-06-12 11:26:29 -0700131 const char* isa_name = GetInstructionSetString(isa);
Igor Murashkin46774762014-10-22 11:37:02 -0700132
Alex Light53cb16b2014-06-12 11:26:29 -0700133 // Set up the runtime
Ian Rogerse63db272014-07-15 15:36:11 -0700134 RuntimeOptions options;
Alex Light53cb16b2014-06-12 11:26:29 -0700135 NoopCompilerCallbacks callbacks;
136 options.push_back(std::make_pair("compilercallbacks", &callbacks));
137 std::string img = "-Ximage:" + image_location;
138 options.push_back(std::make_pair(img.c_str(), nullptr));
139 options.push_back(std::make_pair("imageinstructionset", reinterpret_cast<const void*>(isa_name)));
Calin Juravle01aaf6e2015-06-19 22:05:39 +0100140 options.push_back(std::make_pair("-Xno-sig-chain", nullptr));
Alex Light53cb16b2014-06-12 11:26:29 -0700141 if (!Runtime::Create(options, false)) {
142 LOG(ERROR) << "Unable to initialize runtime";
143 return false;
144 }
145 // Runtime::Create acquired the mutator_lock_ that is normally given away when we Runtime::Start,
146 // give it away now and then switch to a more manageable ScopedObjectAccess.
147 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
148 ScopedObjectAccess soa(Thread::Current());
149
Richard Uhler4bc11d02017-02-01 09:53:54 +0000150 t.NewTiming("Image Patching setup");
Jeff Haodcdc85b2015-12-04 14:06:18 -0800151 std::vector<gc::space::ImageSpace*> spaces = Runtime::Current()->GetHeap()->GetBootImageSpaces();
152 std::map<gc::space::ImageSpace*, std::unique_ptr<File>> space_to_file_map;
153 std::map<gc::space::ImageSpace*, std::unique_ptr<MemMap>> space_to_memmap_map;
154 std::map<gc::space::ImageSpace*, PatchOat> space_to_patchoat_map;
Alex Light53cb16b2014-06-12 11:26:29 -0700155
Jeff Haodcdc85b2015-12-04 14:06:18 -0800156 for (size_t i = 0; i < spaces.size(); ++i) {
157 gc::space::ImageSpace* space = spaces[i];
158 std::string input_image_filename = space->GetImageFilename();
159 std::unique_ptr<File> input_image(OS::OpenFileForReading(input_image_filename.c_str()));
160 if (input_image.get() == nullptr) {
161 LOG(ERROR) << "Unable to open input image file at " << input_image_filename;
Igor Murashkin46774762014-10-22 11:37:02 -0700162 return false;
163 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800164
165 int64_t image_len = input_image->GetLength();
166 if (image_len < 0) {
167 LOG(ERROR) << "Error while getting image length";
168 return false;
169 }
170 ImageHeader image_header;
171 if (sizeof(image_header) != input_image->Read(reinterpret_cast<char*>(&image_header),
172 sizeof(image_header), 0)) {
173 LOG(ERROR) << "Unable to read image header from image file " << input_image->GetPath();
174 }
175
176 /*bool is_image_pic = */IsImagePic(image_header, input_image->GetPath());
177 // Nothing special to do right now since the image always needs to get patched.
178 // Perhaps in some far-off future we may have images with relative addresses that are true-PIC.
179
180 // Create the map where we will write the image patches to.
181 std::string error_msg;
182 std::unique_ptr<MemMap> image(MemMap::MapFile(image_len,
183 PROT_READ | PROT_WRITE,
184 MAP_PRIVATE,
185 input_image->Fd(),
186 0,
187 /*low_4gb*/false,
188 input_image->GetPath().c_str(),
189 &error_msg));
190 if (image.get() == nullptr) {
191 LOG(ERROR) << "Unable to map image file " << input_image->GetPath() << " : " << error_msg;
192 return false;
193 }
194 space_to_file_map.emplace(space, std::move(input_image));
195 space_to_memmap_map.emplace(space, std::move(image));
Igor Murashkin46774762014-10-22 11:37:02 -0700196 }
197
Richard Uhler4bc11d02017-02-01 09:53:54 +0000198 // Symlink PIC oat and vdex files and patch the image spaces in memory.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800199 for (size_t i = 0; i < spaces.size(); ++i) {
200 gc::space::ImageSpace* space = spaces[i];
201 std::string input_image_filename = space->GetImageFilename();
David Brazdil7b49e6c2016-09-01 11:06:18 +0100202 std::string input_vdex_filename =
203 ImageHeader::GetVdexLocationFromImageLocation(input_image_filename);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800204 std::string input_oat_filename =
205 ImageHeader::GetOatLocationFromImageLocation(input_image_filename);
206 std::unique_ptr<File> input_oat_file(OS::OpenFileForReading(input_oat_filename.c_str()));
207 if (input_oat_file.get() == nullptr) {
208 LOG(ERROR) << "Unable to open input oat file at " << input_oat_filename;
209 return false;
210 }
211 std::string error_msg;
212 std::unique_ptr<ElfFile> elf(ElfFile::Open(input_oat_file.get(),
213 PROT_READ | PROT_WRITE, MAP_PRIVATE, &error_msg));
214 if (elf.get() == nullptr) {
215 LOG(ERROR) << "Unable to open oat file " << input_oat_file->GetPath() << " : " << error_msg;
216 return false;
217 }
218
Jeff Haodcdc85b2015-12-04 14:06:18 -0800219 MaybePic is_oat_pic = IsOatPic(elf.get());
220 if (is_oat_pic >= ERROR_FIRST) {
221 // Error logged by IsOatPic
222 return false;
Richard Uhler4bc11d02017-02-01 09:53:54 +0000223 } else if (is_oat_pic == NOT_PIC) {
224 LOG(ERROR) << "patchoat cannot be used on non-PIC oat file: " << input_oat_file->GetPath();
225 return false;
226 } else {
227 CHECK(is_oat_pic == PIC);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800228
Richard Uhler4bc11d02017-02-01 09:53:54 +0000229 // Create a symlink.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800230 std::string converted_image_filename = space->GetImageLocation();
231 std::replace(converted_image_filename.begin() + 1, converted_image_filename.end(), '/', '@');
232 std::string output_image_filename = output_directory +
Andreas Gampe9186ced2016-12-12 14:28:21 -0800233 (android::base::StartsWith(converted_image_filename, "/") ? "" : "/") +
234 converted_image_filename;
David Brazdil7b49e6c2016-09-01 11:06:18 +0100235 std::string output_vdex_filename =
236 ImageHeader::GetVdexLocationFromImageLocation(output_image_filename);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800237 std::string output_oat_filename =
238 ImageHeader::GetOatLocationFromImageLocation(output_image_filename);
239
240 if (!ReplaceOatFileWithSymlink(input_oat_file->GetPath(),
Richard Uhler4bc11d02017-02-01 09:53:54 +0000241 output_oat_filename) ||
David Brazdil7b49e6c2016-09-01 11:06:18 +0100242 !SymlinkFile(input_vdex_filename, output_vdex_filename)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800243 // Errors already logged by above call.
244 return false;
245 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800246 }
247
248 PatchOat& p = space_to_patchoat_map.emplace(space,
249 PatchOat(
250 isa,
Jeff Haodcdc85b2015-12-04 14:06:18 -0800251 space_to_memmap_map.find(space)->second.get(),
252 space->GetLiveBitmap(),
253 space->GetMemMap(),
254 delta,
255 &space_to_memmap_map,
256 timings)).first->second;
257
Richard Uhler4bc11d02017-02-01 09:53:54 +0000258 t.NewTiming("Patching image");
Jeff Haodcdc85b2015-12-04 14:06:18 -0800259 if (!p.PatchImage(i == 0)) {
260 LOG(ERROR) << "Failed to patch image file " << input_image_filename;
261 return false;
262 }
Alex Light53cb16b2014-06-12 11:26:29 -0700263 }
264
Richard Uhler4bc11d02017-02-01 09:53:54 +0000265 // Write the patched image spaces.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800266 for (size_t i = 0; i < spaces.size(); ++i) {
267 gc::space::ImageSpace* space = spaces[i];
Jeff Haodcdc85b2015-12-04 14:06:18 -0800268
Richard Uhler4bc11d02017-02-01 09:53:54 +0000269 t.NewTiming("Writing image");
Jeff Haodcdc85b2015-12-04 14:06:18 -0800270 std::string converted_image_filename = space->GetImageLocation();
271 std::replace(converted_image_filename.begin() + 1, converted_image_filename.end(), '/', '@');
272 std::string output_image_filename = output_directory +
Andreas Gampe9186ced2016-12-12 14:28:21 -0800273 (android::base::StartsWith(converted_image_filename, "/") ? "" : "/") +
274 converted_image_filename;
Richard Uhler4bc11d02017-02-01 09:53:54 +0000275 std::unique_ptr<File> output_image_file(CreateOrOpen(output_image_filename.c_str()));
Jeff Haodcdc85b2015-12-04 14:06:18 -0800276 if (output_image_file.get() == nullptr) {
277 LOG(ERROR) << "Failed to open output image file at " << output_image_filename;
278 return false;
279 }
280
281 PatchOat& p = space_to_patchoat_map.find(space)->second;
282
Serdjuk, Nikolay Yd12f9c12016-03-22 10:06:33 +0600283 bool success = p.WriteImage(output_image_file.get());
284 success = FinishFile(output_image_file.get(), success);
285 if (!success) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800286 return false;
287 }
Alex Light53cb16b2014-06-12 11:26:29 -0700288 }
289 return true;
290}
291
Alex Light53cb16b2014-06-12 11:26:29 -0700292bool PatchOat::WriteImage(File* out) {
Alex Lighteefbe392014-07-08 09:53:18 -0700293 TimingLogger::ScopedTiming t("Writing image File", timings_);
Alex Lighta59dd802014-07-02 16:28:08 -0700294 std::string error_msg;
295
Alex Lightcf4bf382014-07-24 11:29:14 -0700296 ScopedFlock img_flock;
297 img_flock.Init(out, &error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -0700298
Alex Light53cb16b2014-06-12 11:26:29 -0700299 CHECK(image_ != nullptr);
300 CHECK(out != nullptr);
301 size_t expect = image_->Size();
302 if (out->WriteFully(reinterpret_cast<char*>(image_->Begin()), expect) &&
303 out->SetLength(expect) == 0) {
304 return true;
305 } else {
306 LOG(ERROR) << "Writing to image file " << out->GetPath() << " failed.";
307 return false;
308 }
309}
310
Igor Murashkin46774762014-10-22 11:37:02 -0700311bool PatchOat::IsImagePic(const ImageHeader& image_header, const std::string& image_path) {
312 if (!image_header.CompilePic()) {
313 if (kIsDebugBuild) {
314 LOG(INFO) << "image at location " << image_path << " was *not* compiled pic";
315 }
316 return false;
317 }
318
319 if (kIsDebugBuild) {
320 LOG(INFO) << "image at location " << image_path << " was compiled PIC";
321 }
322
323 return true;
324}
325
326PatchOat::MaybePic PatchOat::IsOatPic(const ElfFile* oat_in) {
327 if (oat_in == nullptr) {
328 LOG(ERROR) << "No ELF input oat fie available";
329 return ERROR_OAT_FILE;
330 }
331
Brian Carlstromf5b0f2c2016-10-14 01:04:26 -0700332 const std::string& file_path = oat_in->GetFilePath();
Igor Murashkin46774762014-10-22 11:37:02 -0700333
334 const OatHeader* oat_header = GetOatHeader(oat_in);
335 if (oat_header == nullptr) {
336 LOG(ERROR) << "Failed to find oat header in oat file " << file_path;
337 return ERROR_OAT_FILE;
338 }
339
340 if (!oat_header->IsValid()) {
341 LOG(ERROR) << "Elf file " << file_path << " has an invalid oat header";
342 return ERROR_OAT_FILE;
343 }
344
345 bool is_pic = oat_header->IsPic();
346 if (kIsDebugBuild) {
347 LOG(INFO) << "Oat file at " << file_path << " is " << (is_pic ? "PIC" : "not pic");
348 }
349
350 return is_pic ? PIC : NOT_PIC;
351}
352
353bool PatchOat::ReplaceOatFileWithSymlink(const std::string& input_oat_filename,
Richard Uhler4bc11d02017-02-01 09:53:54 +0000354 const std::string& output_oat_filename) {
Igor Murashkin46774762014-10-22 11:37:02 -0700355 // Delete the original file, since we won't need it.
Dimitry Ivanov7a1c0142016-03-17 15:59:38 -0700356 unlink(output_oat_filename.c_str());
Igor Murashkin46774762014-10-22 11:37:02 -0700357
358 // Create a symlink from the old oat to the new oat
359 if (symlink(input_oat_filename.c_str(), output_oat_filename.c_str()) < 0) {
360 int err = errno;
361 LOG(ERROR) << "Failed to create symlink at " << output_oat_filename
362 << " error(" << err << "): " << strerror(err);
363 return false;
364 }
365
366 if (kIsDebugBuild) {
367 LOG(INFO) << "Created symlink " << output_oat_filename << " -> " << input_oat_filename;
368 }
369
370 return true;
371}
372
Vladimir Markoad06b982016-11-17 16:38:59 +0000373class PatchOat::PatchOatArtFieldVisitor : public ArtFieldVisitor {
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700374 public:
375 explicit PatchOatArtFieldVisitor(PatchOat* patch_oat) : patch_oat_(patch_oat) {}
376
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700377 void Visit(ArtField* field) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700378 ArtField* const dest = patch_oat_->RelocatedCopyOf(field);
Mathieu Chartier3398c782016-09-30 10:27:43 -0700379 dest->SetDeclaringClass(
Mathieu Chartier1cc62e42016-10-03 18:01:28 -0700380 patch_oat_->RelocatedAddressOfPointer(field->GetDeclaringClass().Ptr()));
Mathieu Chartiere401d142015-04-22 13:56:20 -0700381 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700382
383 private:
384 PatchOat* const patch_oat_;
385};
386
387void PatchOat::PatchArtFields(const ImageHeader* image_header) {
388 PatchOatArtFieldVisitor visitor(this);
Mathieu Chartiere42888f2016-04-14 10:49:19 -0700389 image_header->VisitPackedArtFields(&visitor, heap_->Begin());
Mathieu Chartiere401d142015-04-22 13:56:20 -0700390}
391
Vladimir Markoad06b982016-11-17 16:38:59 +0000392class PatchOat::PatchOatArtMethodVisitor : public ArtMethodVisitor {
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700393 public:
394 explicit PatchOatArtMethodVisitor(PatchOat* patch_oat) : patch_oat_(patch_oat) {}
395
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700396 void Visit(ArtMethod* method) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700397 ArtMethod* const dest = patch_oat_->RelocatedCopyOf(method);
398 patch_oat_->FixupMethod(method, dest);
399 }
400
401 private:
402 PatchOat* const patch_oat_;
403};
404
Mathieu Chartiere401d142015-04-22 13:56:20 -0700405void PatchOat::PatchArtMethods(const ImageHeader* image_header) {
Andreas Gampe542451c2016-07-26 09:02:02 -0700406 const PointerSize pointer_size = InstructionSetPointerSize(isa_);
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700407 PatchOatArtMethodVisitor visitor(this);
Mathieu Chartiere42888f2016-04-14 10:49:19 -0700408 image_header->VisitPackedArtMethods(&visitor, heap_->Begin(), pointer_size);
409}
410
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +0000411void PatchOat::PatchImTables(const ImageHeader* image_header) {
Andreas Gampe542451c2016-07-26 09:02:02 -0700412 const PointerSize pointer_size = InstructionSetPointerSize(isa_);
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +0000413 // We can safely walk target image since the conflict tables are independent.
414 image_header->VisitPackedImTables(
415 [this](ArtMethod* method) {
416 return RelocatedAddressOfPointer(method);
417 },
418 image_->Begin(),
419 pointer_size);
420}
421
Mathieu Chartiere42888f2016-04-14 10:49:19 -0700422void PatchOat::PatchImtConflictTables(const ImageHeader* image_header) {
Andreas Gampe542451c2016-07-26 09:02:02 -0700423 const PointerSize pointer_size = InstructionSetPointerSize(isa_);
Mathieu Chartiere42888f2016-04-14 10:49:19 -0700424 // We can safely walk target image since the conflict tables are independent.
425 image_header->VisitPackedImtConflictTables(
426 [this](ArtMethod* method) {
427 return RelocatedAddressOfPointer(method);
428 },
429 image_->Begin(),
430 pointer_size);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700431}
432
Vladimir Markoad06b982016-11-17 16:38:59 +0000433class PatchOat::FixupRootVisitor : public RootVisitor {
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700434 public:
435 explicit FixupRootVisitor(const PatchOat* patch_oat) : patch_oat_(patch_oat) {
436 }
437
438 void VisitRoots(mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700439 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700440 for (size_t i = 0; i < count; ++i) {
441 *roots[i] = patch_oat_->RelocatedAddressOfPointer(*roots[i]);
442 }
443 }
444
445 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots, size_t count,
446 const RootInfo& info ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700447 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700448 for (size_t i = 0; i < count; ++i) {
449 roots[i]->Assign(patch_oat_->RelocatedAddressOfPointer(roots[i]->AsMirrorPtr()));
450 }
451 }
452
453 private:
454 const PatchOat* const patch_oat_;
455};
456
457void PatchOat::PatchInternedStrings(const ImageHeader* image_header) {
458 const auto& section = image_header->GetImageSection(ImageHeader::kSectionInternedStrings);
459 InternTable temp_table;
460 // Note that we require that ReadFromMemory does not make an internal copy of the elements.
461 // This also relies on visit roots not doing any verification which could fail after we update
462 // the roots to be the image addresses.
Mathieu Chartierea0831f2015-12-29 13:17:37 -0800463 temp_table.AddTableFromMemory(image_->Begin() + section.Offset());
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700464 FixupRootVisitor visitor(this);
465 temp_table.VisitRoots(&visitor, kVisitRootFlagAllRoots);
466}
467
Mathieu Chartier208a5cb2015-12-02 15:44:07 -0800468void PatchOat::PatchClassTable(const ImageHeader* image_header) {
469 const auto& section = image_header->GetImageSection(ImageHeader::kSectionClassTable);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800470 if (section.Size() == 0) {
471 return;
472 }
Mathieu Chartier208a5cb2015-12-02 15:44:07 -0800473 // Note that we require that ReadFromMemory does not make an internal copy of the elements.
474 // This also relies on visit roots not doing any verification which could fail after we update
475 // the roots to be the image addresses.
476 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
477 ClassTable temp_table;
478 temp_table.ReadFromMemory(image_->Begin() + section.Offset());
479 FixupRootVisitor visitor(this);
Mathieu Chartier58c3f6a2016-12-01 14:21:11 -0800480 temp_table.VisitRoots(UnbufferedRootVisitor(&visitor, RootInfo(kRootUnknown)));
Mathieu Chartier208a5cb2015-12-02 15:44:07 -0800481}
482
483
Vladimir Markoad06b982016-11-17 16:38:59 +0000484class PatchOat::RelocatedPointerVisitor {
Mathieu Chartier4b00d342015-11-13 10:42:08 -0800485 public:
486 explicit RelocatedPointerVisitor(PatchOat* patch_oat) : patch_oat_(patch_oat) {}
487
488 template <typename T>
Mathieu Chartier8c19d242017-03-06 12:35:10 -0800489 T* operator()(T* ptr, void** dest_addr ATTRIBUTE_UNUSED = 0) const {
Mathieu Chartier4b00d342015-11-13 10:42:08 -0800490 return patch_oat_->RelocatedAddressOfPointer(ptr);
491 }
492
493 private:
494 PatchOat* const patch_oat_;
495};
496
Mathieu Chartierc7853442015-03-27 14:35:38 -0700497void PatchOat::PatchDexFileArrays(mirror::ObjectArray<mirror::Object>* img_roots) {
498 auto* dex_caches = down_cast<mirror::ObjectArray<mirror::DexCache>*>(
499 img_roots->Get(ImageHeader::kDexCaches));
Andreas Gampe542451c2016-07-26 09:02:02 -0700500 const PointerSize pointer_size = InstructionSetPointerSize(isa_);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700501 for (size_t i = 0, count = dex_caches->GetLength(); i < count; ++i) {
Vladimir Marko05792b92015-08-03 11:56:49 +0100502 auto* orig_dex_cache = dex_caches->GetWithoutChecks(i);
503 auto* copy_dex_cache = RelocatedCopyOf(orig_dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +0100504 // Though the DexCache array fields are usually treated as native pointers, we set the full
505 // 64-bit values here, clearing the top 32 bits for 32-bit targets. The zero-extension is
506 // done by casting to the unsigned type uintptr_t before casting to int64_t, i.e.
507 // static_cast<int64_t>(reinterpret_cast<uintptr_t>(image_begin_ + offset))).
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -0700508 mirror::StringDexCacheType* orig_strings = orig_dex_cache->GetStrings();
509 mirror::StringDexCacheType* relocated_strings = RelocatedAddressOfPointer(orig_strings);
Vladimir Marko05792b92015-08-03 11:56:49 +0100510 copy_dex_cache->SetField64<false>(
511 mirror::DexCache::StringsOffset(),
512 static_cast<int64_t>(reinterpret_cast<uintptr_t>(relocated_strings)));
513 if (orig_strings != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -0800514 orig_dex_cache->FixupStrings(RelocatedCopyOf(orig_strings), RelocatedPointerVisitor(this));
Mathieu Chartierc7853442015-03-27 14:35:38 -0700515 }
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000516 mirror::TypeDexCacheType* orig_types = orig_dex_cache->GetResolvedTypes();
517 mirror::TypeDexCacheType* relocated_types = RelocatedAddressOfPointer(orig_types);
Vladimir Marko05792b92015-08-03 11:56:49 +0100518 copy_dex_cache->SetField64<false>(
519 mirror::DexCache::ResolvedTypesOffset(),
520 static_cast<int64_t>(reinterpret_cast<uintptr_t>(relocated_types)));
521 if (orig_types != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -0800522 orig_dex_cache->FixupResolvedTypes(RelocatedCopyOf(orig_types),
523 RelocatedPointerVisitor(this));
Vladimir Marko05792b92015-08-03 11:56:49 +0100524 }
525 ArtMethod** orig_methods = orig_dex_cache->GetResolvedMethods();
526 ArtMethod** relocated_methods = RelocatedAddressOfPointer(orig_methods);
527 copy_dex_cache->SetField64<false>(
528 mirror::DexCache::ResolvedMethodsOffset(),
529 static_cast<int64_t>(reinterpret_cast<uintptr_t>(relocated_methods)));
530 if (orig_methods != nullptr) {
531 ArtMethod** copy_methods = RelocatedCopyOf(orig_methods);
532 for (size_t j = 0, num = orig_dex_cache->NumResolvedMethods(); j != num; ++j) {
533 ArtMethod* orig = mirror::DexCache::GetElementPtrSize(orig_methods, j, pointer_size);
534 ArtMethod* copy = RelocatedAddressOfPointer(orig);
535 mirror::DexCache::SetElementPtrSize(copy_methods, j, copy, pointer_size);
536 }
537 }
Vladimir Markof44d36c2017-03-14 14:18:46 +0000538 mirror::FieldDexCacheType* orig_fields = orig_dex_cache->GetResolvedFields();
539 mirror::FieldDexCacheType* relocated_fields = RelocatedAddressOfPointer(orig_fields);
Vladimir Marko05792b92015-08-03 11:56:49 +0100540 copy_dex_cache->SetField64<false>(
541 mirror::DexCache::ResolvedFieldsOffset(),
542 static_cast<int64_t>(reinterpret_cast<uintptr_t>(relocated_fields)));
543 if (orig_fields != nullptr) {
Vladimir Markof44d36c2017-03-14 14:18:46 +0000544 mirror::FieldDexCacheType* copy_fields = RelocatedCopyOf(orig_fields);
Vladimir Marko05792b92015-08-03 11:56:49 +0100545 for (size_t j = 0, num = orig_dex_cache->NumResolvedFields(); j != num; ++j) {
Vladimir Markof44d36c2017-03-14 14:18:46 +0000546 mirror::FieldDexCachePair orig =
547 mirror::DexCache::GetNativePairPtrSize(orig_fields, j, pointer_size);
548 mirror::FieldDexCachePair copy(RelocatedAddressOfPointer(orig.object), orig.index);
549 mirror::DexCache::SetNativePairPtrSize(copy_fields, j, copy, pointer_size);
Vladimir Marko05792b92015-08-03 11:56:49 +0100550 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700551 }
Narayan Kamath7fe56582016-10-14 18:49:12 +0100552 mirror::MethodTypeDexCacheType* orig_method_types = orig_dex_cache->GetResolvedMethodTypes();
553 mirror::MethodTypeDexCacheType* relocated_method_types =
554 RelocatedAddressOfPointer(orig_method_types);
555 copy_dex_cache->SetField64<false>(
556 mirror::DexCache::ResolvedMethodTypesOffset(),
557 static_cast<int64_t>(reinterpret_cast<uintptr_t>(relocated_method_types)));
558 if (orig_method_types != nullptr) {
559 orig_dex_cache->FixupResolvedMethodTypes(RelocatedCopyOf(orig_method_types),
560 RelocatedPointerVisitor(this));
561 }
Orion Hodsonc069a302017-01-18 09:23:12 +0000562
563 GcRoot<mirror::CallSite>* orig_call_sites = orig_dex_cache->GetResolvedCallSites();
564 GcRoot<mirror::CallSite>* relocated_call_sites = RelocatedAddressOfPointer(orig_call_sites);
565 copy_dex_cache->SetField64<false>(
566 mirror::DexCache::ResolvedCallSitesOffset(),
567 static_cast<int64_t>(reinterpret_cast<uintptr_t>(relocated_call_sites)));
568 if (orig_call_sites != nullptr) {
569 orig_dex_cache->FixupResolvedCallSites(RelocatedCopyOf(orig_call_sites),
570 RelocatedPointerVisitor(this));
571 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700572 }
573}
574
Jeff Haodcdc85b2015-12-04 14:06:18 -0800575bool PatchOat::PatchImage(bool primary_image) {
Alex Light53cb16b2014-06-12 11:26:29 -0700576 ImageHeader* image_header = reinterpret_cast<ImageHeader*>(image_->Begin());
577 CHECK_GT(image_->Size(), sizeof(ImageHeader));
578 // These are the roots from the original file.
Mathieu Chartierc7853442015-03-27 14:35:38 -0700579 auto* img_roots = image_header->GetImageRoots();
Alex Light53cb16b2014-06-12 11:26:29 -0700580 image_header->RelocateImage(delta_);
581
Mathieu Chartierc7853442015-03-27 14:35:38 -0700582 PatchArtFields(image_header);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700583 PatchArtMethods(image_header);
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +0000584 PatchImTables(image_header);
Mathieu Chartiere42888f2016-04-14 10:49:19 -0700585 PatchImtConflictTables(image_header);
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700586 PatchInternedStrings(image_header);
Mathieu Chartier208a5cb2015-12-02 15:44:07 -0800587 PatchClassTable(image_header);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700588 // Patch dex file int/long arrays which point to ArtFields.
589 PatchDexFileArrays(img_roots);
590
Jeff Haodcdc85b2015-12-04 14:06:18 -0800591 if (primary_image) {
592 VisitObject(img_roots);
593 }
594
Alex Light53cb16b2014-06-12 11:26:29 -0700595 if (!image_header->IsValid()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800596 LOG(ERROR) << "relocation renders image header invalid";
Alex Light53cb16b2014-06-12 11:26:29 -0700597 return false;
598 }
599
600 {
Alex Lighteefbe392014-07-08 09:53:18 -0700601 TimingLogger::ScopedTiming t("Walk Bitmap", timings_);
Alex Light53cb16b2014-06-12 11:26:29 -0700602 // Walk the bitmap.
603 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
604 bitmap_->Walk(PatchOat::BitmapCallback, this);
605 }
606 return true;
607}
608
Alex Light53cb16b2014-06-12 11:26:29 -0700609
Mathieu Chartier31e88222016-10-14 18:43:19 -0700610void PatchOat::PatchVisitor::operator() (ObjPtr<mirror::Object> obj,
611 MemberOffset off,
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700612 bool is_static_unused ATTRIBUTE_UNUSED) const {
Alex Light53cb16b2014-06-12 11:26:29 -0700613 mirror::Object* referent = obj->GetFieldObject<mirror::Object, kVerifyNone>(off);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700614 mirror::Object* moved_object = patcher_->RelocatedAddressOfPointer(referent);
Alex Light53cb16b2014-06-12 11:26:29 -0700615 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(off, moved_object);
616}
617
Mathieu Chartier31e88222016-10-14 18:43:19 -0700618void PatchOat::PatchVisitor::operator() (ObjPtr<mirror::Class> cls ATTRIBUTE_UNUSED,
619 ObjPtr<mirror::Reference> ref) const {
Alex Light53cb16b2014-06-12 11:26:29 -0700620 MemberOffset off = mirror::Reference::ReferentOffset();
621 mirror::Object* referent = ref->GetReferent();
Mathieu Chartiera13abba2016-04-21 10:23:16 -0700622 DCHECK(referent == nullptr ||
623 Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(referent)) << referent;
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
Alex Light53cb16b2014-06-12 11:26:29 -0700628// Called by BitmapCallback
629void PatchOat::VisitObject(mirror::Object* object) {
630 mirror::Object* copy = RelocatedCopyOf(object);
631 CHECK(copy != nullptr);
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700632 if (kUseBakerReadBarrier) {
633 object->AssertReadBarrierState();
Alex Light53cb16b2014-06-12 11:26:29 -0700634 }
635 PatchOat::PatchVisitor visitor(this, copy);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -0700636 object->VisitReferences<kVerifyNone>(visitor, visitor);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700637 if (object->IsClass<kVerifyNone>()) {
Andreas Gampe542451c2016-07-26 09:02:02 -0700638 const PointerSize pointer_size = InstructionSetPointerSize(isa_);
Mathieu Chartier4b00d342015-11-13 10:42:08 -0800639 mirror::Class* klass = object->AsClass();
640 mirror::Class* copy_klass = down_cast<mirror::Class*>(copy);
641 RelocatedPointerVisitor native_visitor(this);
642 klass->FixupNativePointers(copy_klass, pointer_size, native_visitor);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700643 auto* vtable = klass->GetVTable();
644 if (vtable != nullptr) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800645 vtable->Fixup(RelocatedCopyOfFollowImages(vtable), pointer_size, native_visitor);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700646 }
Mathieu Chartier6beced42016-11-15 15:51:31 -0800647 mirror::IfTable* iftable = klass->GetIfTable();
648 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
649 if (iftable->GetMethodArrayCount(i) > 0) {
650 auto* method_array = iftable->GetMethodArray(i);
651 CHECK(method_array != nullptr);
652 method_array->Fixup(RelocatedCopyOfFollowImages(method_array),
653 pointer_size,
654 native_visitor);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700655 }
656 }
Mathieu Chartier4b00d342015-11-13 10:42:08 -0800657 } else if (object->GetClass() == mirror::Method::StaticClass() ||
658 object->GetClass() == mirror::Constructor::StaticClass()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700659 // Need to go update the ArtMethod.
Neil Fuller0e844392016-09-08 13:43:31 +0100660 auto* dest = down_cast<mirror::Executable*>(copy);
661 auto* src = down_cast<mirror::Executable*>(object);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700662 dest->SetArtMethod(RelocatedAddressOfPointer(src->GetArtMethod()));
Alex Light53cb16b2014-06-12 11:26:29 -0700663 }
664}
665
Mathieu Chartiere401d142015-04-22 13:56:20 -0700666void PatchOat::FixupMethod(ArtMethod* object, ArtMethod* copy) {
Andreas Gampe542451c2016-07-26 09:02:02 -0700667 const PointerSize pointer_size = InstructionSetPointerSize(isa_);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700668 copy->CopyFrom(object, pointer_size);
Alex Light53cb16b2014-06-12 11:26:29 -0700669 // Just update the entry points if it looks like we should.
Alex Lighteefbe392014-07-08 09:53:18 -0700670 // TODO: sanity check all the pointers' values
Mathieu Chartiere401d142015-04-22 13:56:20 -0700671 copy->SetDeclaringClass(RelocatedAddressOfPointer(object->GetDeclaringClass()));
Vladimir Marko05792b92015-08-03 11:56:49 +0100672 copy->SetDexCacheResolvedMethods(
673 RelocatedAddressOfPointer(object->GetDexCacheResolvedMethods(pointer_size)), pointer_size);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700674 copy->SetEntryPointFromQuickCompiledCodePtrSize(RelocatedAddressOfPointer(
675 object->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size)), pointer_size);
Mathieu Chartiere42888f2016-04-14 10:49:19 -0700676 // No special handling for IMT conflict table since all pointers are moved by the same offset.
Andreas Gampe75f08852016-07-19 08:06:07 -0700677 copy->SetDataPtrSize(RelocatedAddressOfPointer(
678 object->GetDataPtrSize(pointer_size)), pointer_size);
Alex Light53cb16b2014-06-12 11:26:29 -0700679}
680
Alex Light53cb16b2014-06-12 11:26:29 -0700681static int orig_argc;
682static char** orig_argv;
683
684static std::string CommandLine() {
685 std::vector<std::string> command;
686 for (int i = 0; i < orig_argc; ++i) {
687 command.push_back(orig_argv[i]);
688 }
Andreas Gampe9186ced2016-12-12 14:28:21 -0800689 return android::base::Join(command, ' ');
Alex Light53cb16b2014-06-12 11:26:29 -0700690}
691
692static void UsageErrorV(const char* fmt, va_list ap) {
693 std::string error;
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800694 android::base::StringAppendV(&error, fmt, ap);
Alex Light53cb16b2014-06-12 11:26:29 -0700695 LOG(ERROR) << error;
696}
697
698static void UsageError(const char* fmt, ...) {
699 va_list ap;
700 va_start(ap, fmt);
701 UsageErrorV(fmt, ap);
702 va_end(ap);
703}
704
Andreas Gampe794ad762015-02-23 08:12:24 -0800705NO_RETURN static void Usage(const char *fmt, ...) {
Alex Light53cb16b2014-06-12 11:26:29 -0700706 va_list ap;
707 va_start(ap, fmt);
708 UsageErrorV(fmt, ap);
709 va_end(ap);
710
711 UsageError("Command: %s", CommandLine().c_str());
712 UsageError("Usage: patchoat [options]...");
713 UsageError("");
714 UsageError(" --instruction-set=<isa>: Specifies the instruction set the patched code is");
Richard Uhler4bc11d02017-02-01 09:53:54 +0000715 UsageError(" compiled for (required).");
Alex Light53cb16b2014-06-12 11:26:29 -0700716 UsageError("");
717 UsageError(" --input-image-location=<file.art>: Specifies the 'location' of the image file to");
Richard Uhler4bc11d02017-02-01 09:53:54 +0000718 UsageError(" be patched.");
Alex Light53cb16b2014-06-12 11:26:29 -0700719 UsageError("");
720 UsageError(" --output-image-file=<file.art>: Specifies the exact file to write the patched");
721 UsageError(" image file to.");
722 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700723 UsageError(" --base-offset-delta=<delta>: Specify the amount to change the old base-offset by.");
724 UsageError(" This value may be negative.");
725 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700726 UsageError(" --dump-timings: dump out patch timing information");
727 UsageError("");
728 UsageError(" --no-dump-timings: do not dump out patch timing information");
729 UsageError("");
730
731 exit(EXIT_FAILURE);
732}
733
Andreas Gampe6eb6a392016-02-10 20:18:37 -0800734static int patchoat_image(TimingLogger& timings,
735 InstructionSet isa,
736 const std::string& input_image_location,
737 const std::string& output_image_filename,
738 off_t base_delta,
739 bool base_delta_set,
740 bool debug) {
741 CHECK(!input_image_location.empty());
742 if (output_image_filename.empty()) {
743 Usage("Image patching requires --output-image-file");
744 }
745
746 if (!base_delta_set) {
747 Usage("Must supply a desired new offset or delta.");
748 }
749
750 if (!IsAligned<kPageSize>(base_delta)) {
751 Usage("Base offset/delta must be aligned to a pagesize (0x%08x) boundary.", kPageSize);
752 }
753
754 if (debug) {
755 LOG(INFO) << "moving offset by " << base_delta
756 << " (0x" << std::hex << base_delta << ") bytes or "
757 << std::dec << (base_delta/kPageSize) << " pages.";
758 }
759
760 TimingLogger::ScopedTiming pt("patch image and oat", &timings);
761
762 std::string output_directory =
Andreas Gampeca620d72016-11-08 08:09:33 -0800763 output_image_filename.substr(0, output_image_filename.find_last_of('/'));
Andreas Gampe6eb6a392016-02-10 20:18:37 -0800764 bool ret = PatchOat::Patch(input_image_location, base_delta, output_directory, isa, &timings);
765
766 if (kIsDebugBuild) {
767 LOG(INFO) << "Exiting with return ... " << ret;
768 }
769 return ret ? EXIT_SUCCESS : EXIT_FAILURE;
770}
771
Alex Lighteefbe392014-07-08 09:53:18 -0700772static int patchoat(int argc, char **argv) {
David Sehrf57589f2016-10-17 10:09:33 -0700773 InitLogging(argv, Runtime::Aborter);
Mathieu Chartier6e88ef62014-10-14 15:01:24 -0700774 MemMap::Init();
Alex Light53cb16b2014-06-12 11:26:29 -0700775 const bool debug = kIsDebugBuild;
776 orig_argc = argc;
777 orig_argv = argv;
778 TimingLogger timings("patcher", false, false);
779
Alex Light53cb16b2014-06-12 11:26:29 -0700780 // Skip over the command name.
781 argv++;
782 argc--;
783
784 if (argc == 0) {
785 Usage("No arguments specified");
786 }
787
788 timings.StartTiming("Patchoat");
789
790 // cmd line args
791 bool isa_set = false;
792 InstructionSet isa = kNone;
Alex Light53cb16b2014-06-12 11:26:29 -0700793 std::string input_image_location;
Alex Light53cb16b2014-06-12 11:26:29 -0700794 std::string output_image_filename;
Alex Light53cb16b2014-06-12 11:26:29 -0700795 off_t base_delta = 0;
796 bool base_delta_set = false;
Alex Light53cb16b2014-06-12 11:26:29 -0700797 bool dump_timings = kIsDebugBuild;
798
Ian Rogersd4c4d952014-10-16 20:31:53 -0700799 for (int i = 0; i < argc; ++i) {
Alex Light53cb16b2014-06-12 11:26:29 -0700800 const StringPiece option(argv[i]);
801 const bool log_options = false;
802 if (log_options) {
803 LOG(INFO) << "patchoat: option[" << i << "]=" << argv[i];
804 }
Alex Light53cb16b2014-06-12 11:26:29 -0700805 if (option.starts_with("--instruction-set=")) {
806 isa_set = true;
807 const char* isa_str = option.substr(strlen("--instruction-set=")).data();
Andreas Gampe20c89302014-08-19 17:28:06 -0700808 isa = GetInstructionSetFromString(isa_str);
809 if (isa == kNone) {
810 Usage("Unknown or invalid instruction set %s", isa_str);
Alex Light53cb16b2014-06-12 11:26:29 -0700811 }
Alex Light53cb16b2014-06-12 11:26:29 -0700812 } else if (option.starts_with("--input-image-location=")) {
813 input_image_location = option.substr(strlen("--input-image-location=")).data();
Alex Light53cb16b2014-06-12 11:26:29 -0700814 } else if (option.starts_with("--output-image-file=")) {
Alex Light53cb16b2014-06-12 11:26:29 -0700815 output_image_filename = option.substr(strlen("--output-image-file=")).data();
Alex Light53cb16b2014-06-12 11:26:29 -0700816 } else if (option.starts_with("--base-offset-delta=")) {
817 const char* base_delta_str = option.substr(strlen("--base-offset-delta=")).data();
818 base_delta_set = true;
819 if (!ParseInt(base_delta_str, &base_delta)) {
820 Usage("Failed to parse --base-offset-delta argument '%s' as an off_t", base_delta_str);
821 }
Alex Light53cb16b2014-06-12 11:26:29 -0700822 } else if (option == "--dump-timings") {
823 dump_timings = true;
824 } else if (option == "--no-dump-timings") {
825 dump_timings = false;
826 } else {
827 Usage("Unknown argument %s", option.data());
828 }
829 }
830
Andreas Gampe6eb6a392016-02-10 20:18:37 -0800831 // The instruction set is mandatory. This simplifies things...
832 if (!isa_set) {
833 Usage("Instruction set must be set.");
Alex Light53cb16b2014-06-12 11:26:29 -0700834 }
835
Richard Uhler4bc11d02017-02-01 09:53:54 +0000836 int ret = patchoat_image(timings,
837 isa,
838 input_image_location,
839 output_image_filename,
840 base_delta,
841 base_delta_set,
842 debug);
Alex Light53cb16b2014-06-12 11:26:29 -0700843
Andreas Gampe6eb6a392016-02-10 20:18:37 -0800844 timings.EndTiming();
845 if (dump_timings) {
846 LOG(INFO) << Dumpable<TimingLogger>(timings);
Alex Light53cb16b2014-06-12 11:26:29 -0700847 }
848
Andreas Gampe6eb6a392016-02-10 20:18:37 -0800849 return ret;
Alex Light53cb16b2014-06-12 11:26:29 -0700850}
851
852} // namespace art
853
854int main(int argc, char **argv) {
855 return art::patchoat(argc, argv);
856}