blob: 149960ee2c13d3a6182586048226275ad3679f78 [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"
Andreas Gampeb2d18fa2017-06-06 20:46:10 -070043#include "intern_table.h"
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -070044#include "mirror/dex_cache.h"
Neil Fuller0e844392016-09-08 13:43:31 +010045#include "mirror/executable.h"
Alex Light53cb16b2014-06-12 11:26:29 -070046#include "mirror/object-inl.h"
Andreas Gampec6ea7d02017-02-01 16:46:28 -080047#include "mirror/object-refvisitor-inl.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070048#include "mirror/method.h"
Alex Light53cb16b2014-06-12 11:26:29 -070049#include "mirror/reference.h"
50#include "noop_compiler_callbacks.h"
51#include "offsets.h"
52#include "os.h"
53#include "runtime.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070054#include "scoped_thread_state_change-inl.h"
Alex Light53cb16b2014-06-12 11:26:29 -070055#include "thread.h"
56#include "utils.h"
57
58namespace art {
59
Alex Light0eb76d22015-08-11 18:03:47 -070060static const OatHeader* GetOatHeader(const ElfFile* elf_file) {
61 uint64_t off = 0;
62 if (!elf_file->GetSectionOffsetAndSize(".rodata", &off, nullptr)) {
63 return nullptr;
64 }
65
66 OatHeader* oat_header = reinterpret_cast<OatHeader*>(elf_file->Begin() + off);
67 return oat_header;
68}
69
Richard Uhler4bc11d02017-02-01 09:53:54 +000070static File* CreateOrOpen(const char* name) {
Jeff Haodcdc85b2015-12-04 14:06:18 -080071 if (OS::FileExists(name)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -080072 return OS::OpenFileReadWrite(name);
73 } else {
Jeff Haodcdc85b2015-12-04 14:06:18 -080074 std::unique_ptr<File> f(OS::CreateEmptyFile(name));
75 if (f.get() != nullptr) {
76 if (fchmod(f->Fd(), 0644) != 0) {
77 PLOG(ERROR) << "Unable to make " << name << " world readable";
Dimitry Ivanov7a1c0142016-03-17 15:59:38 -070078 unlink(name);
Jeff Haodcdc85b2015-12-04 14:06:18 -080079 return nullptr;
80 }
81 }
82 return f.release();
83 }
84}
85
86// Either try to close the file (close=true), or erase it.
87static bool FinishFile(File* file, bool close) {
88 if (close) {
89 if (file->FlushCloseOrErase() != 0) {
90 PLOG(ERROR) << "Failed to flush and close file.";
91 return false;
92 }
93 return true;
94 } else {
95 file->Erase();
96 return false;
97 }
98}
99
David Brazdil7b49e6c2016-09-01 11:06:18 +0100100static bool SymlinkFile(const std::string& input_filename, const std::string& output_filename) {
101 if (input_filename == output_filename) {
102 // Input and output are the same, nothing to do.
103 return true;
104 }
105
106 // Unlink the original filename, since we are overwriting it.
107 unlink(output_filename.c_str());
108
109 // Create a symlink from the source file to the target path.
110 if (symlink(input_filename.c_str(), output_filename.c_str()) < 0) {
111 PLOG(ERROR) << "Failed to create symlink " << output_filename << " -> " << input_filename;
112 return false;
113 }
114
115 if (kIsDebugBuild) {
116 LOG(INFO) << "Created symlink " << output_filename << " -> " << input_filename;
117 }
118
119 return true;
120}
121
Andreas Gampe6eb6a392016-02-10 20:18:37 -0800122bool PatchOat::Patch(const std::string& image_location,
123 off_t delta,
124 const std::string& output_directory,
125 InstructionSet isa,
126 TimingLogger* timings) {
Alex Light53cb16b2014-06-12 11:26:29 -0700127 CHECK(Runtime::Current() == nullptr);
Alex Light53cb16b2014-06-12 11:26:29 -0700128 CHECK(!image_location.empty()) << "image file must have a filename.";
129
Alex Lighteefbe392014-07-08 09:53:18 -0700130 TimingLogger::ScopedTiming t("Runtime Setup", timings);
Alex Light53cb16b2014-06-12 11:26:29 -0700131
Andreas Gampe6eb6a392016-02-10 20:18:37 -0800132 CHECK_NE(isa, kNone);
Alex Light53cb16b2014-06-12 11:26:29 -0700133 const char* isa_name = GetInstructionSetString(isa);
Igor Murashkin46774762014-10-22 11:37:02 -0700134
Alex Light53cb16b2014-06-12 11:26:29 -0700135 // Set up the runtime
Ian Rogerse63db272014-07-15 15:36:11 -0700136 RuntimeOptions options;
Alex Light53cb16b2014-06-12 11:26:29 -0700137 NoopCompilerCallbacks callbacks;
138 options.push_back(std::make_pair("compilercallbacks", &callbacks));
139 std::string img = "-Ximage:" + image_location;
140 options.push_back(std::make_pair(img.c_str(), nullptr));
141 options.push_back(std::make_pair("imageinstructionset", reinterpret_cast<const void*>(isa_name)));
Calin Juravle01aaf6e2015-06-19 22:05:39 +0100142 options.push_back(std::make_pair("-Xno-sig-chain", nullptr));
Alex Light53cb16b2014-06-12 11:26:29 -0700143 if (!Runtime::Create(options, false)) {
144 LOG(ERROR) << "Unable to initialize runtime";
145 return false;
146 }
Andreas Gampeb8cc1752017-04-26 21:28:50 -0700147 std::unique_ptr<Runtime> runtime(Runtime::Current());
148
Alex Light53cb16b2014-06-12 11:26:29 -0700149 // Runtime::Create acquired the mutator_lock_ that is normally given away when we Runtime::Start,
150 // give it away now and then switch to a more manageable ScopedObjectAccess.
151 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
152 ScopedObjectAccess soa(Thread::Current());
153
Richard Uhler4bc11d02017-02-01 09:53:54 +0000154 t.NewTiming("Image Patching setup");
Jeff Haodcdc85b2015-12-04 14:06:18 -0800155 std::vector<gc::space::ImageSpace*> spaces = Runtime::Current()->GetHeap()->GetBootImageSpaces();
156 std::map<gc::space::ImageSpace*, std::unique_ptr<File>> space_to_file_map;
157 std::map<gc::space::ImageSpace*, std::unique_ptr<MemMap>> space_to_memmap_map;
158 std::map<gc::space::ImageSpace*, PatchOat> space_to_patchoat_map;
Alex Light53cb16b2014-06-12 11:26:29 -0700159
Jeff Haodcdc85b2015-12-04 14:06:18 -0800160 for (size_t i = 0; i < spaces.size(); ++i) {
161 gc::space::ImageSpace* space = spaces[i];
162 std::string input_image_filename = space->GetImageFilename();
163 std::unique_ptr<File> input_image(OS::OpenFileForReading(input_image_filename.c_str()));
164 if (input_image.get() == nullptr) {
165 LOG(ERROR) << "Unable to open input image file at " << input_image_filename;
Igor Murashkin46774762014-10-22 11:37:02 -0700166 return false;
167 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800168
169 int64_t image_len = input_image->GetLength();
170 if (image_len < 0) {
171 LOG(ERROR) << "Error while getting image length";
172 return false;
173 }
174 ImageHeader image_header;
175 if (sizeof(image_header) != input_image->Read(reinterpret_cast<char*>(&image_header),
176 sizeof(image_header), 0)) {
177 LOG(ERROR) << "Unable to read image header from image file " << input_image->GetPath();
178 }
179
180 /*bool is_image_pic = */IsImagePic(image_header, input_image->GetPath());
181 // Nothing special to do right now since the image always needs to get patched.
182 // Perhaps in some far-off future we may have images with relative addresses that are true-PIC.
183
184 // Create the map where we will write the image patches to.
185 std::string error_msg;
186 std::unique_ptr<MemMap> image(MemMap::MapFile(image_len,
187 PROT_READ | PROT_WRITE,
188 MAP_PRIVATE,
189 input_image->Fd(),
190 0,
191 /*low_4gb*/false,
192 input_image->GetPath().c_str(),
193 &error_msg));
194 if (image.get() == nullptr) {
195 LOG(ERROR) << "Unable to map image file " << input_image->GetPath() << " : " << error_msg;
196 return false;
197 }
198 space_to_file_map.emplace(space, std::move(input_image));
199 space_to_memmap_map.emplace(space, std::move(image));
Igor Murashkin46774762014-10-22 11:37:02 -0700200 }
201
Richard Uhler4bc11d02017-02-01 09:53:54 +0000202 // Symlink PIC oat and vdex files and patch the image spaces in memory.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800203 for (size_t i = 0; i < spaces.size(); ++i) {
204 gc::space::ImageSpace* space = spaces[i];
205 std::string input_image_filename = space->GetImageFilename();
David Brazdil7b49e6c2016-09-01 11:06:18 +0100206 std::string input_vdex_filename =
207 ImageHeader::GetVdexLocationFromImageLocation(input_image_filename);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800208 std::string input_oat_filename =
209 ImageHeader::GetOatLocationFromImageLocation(input_image_filename);
210 std::unique_ptr<File> input_oat_file(OS::OpenFileForReading(input_oat_filename.c_str()));
211 if (input_oat_file.get() == nullptr) {
212 LOG(ERROR) << "Unable to open input oat file at " << input_oat_filename;
213 return false;
214 }
215 std::string error_msg;
216 std::unique_ptr<ElfFile> elf(ElfFile::Open(input_oat_file.get(),
217 PROT_READ | PROT_WRITE, MAP_PRIVATE, &error_msg));
218 if (elf.get() == nullptr) {
219 LOG(ERROR) << "Unable to open oat file " << input_oat_file->GetPath() << " : " << error_msg;
220 return false;
221 }
222
Jeff Haodcdc85b2015-12-04 14:06:18 -0800223 MaybePic is_oat_pic = IsOatPic(elf.get());
224 if (is_oat_pic >= ERROR_FIRST) {
225 // Error logged by IsOatPic
226 return false;
Richard Uhler4bc11d02017-02-01 09:53:54 +0000227 } else if (is_oat_pic == NOT_PIC) {
228 LOG(ERROR) << "patchoat cannot be used on non-PIC oat file: " << input_oat_file->GetPath();
229 return false;
230 } else {
231 CHECK(is_oat_pic == PIC);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800232
Richard Uhler4bc11d02017-02-01 09:53:54 +0000233 // Create a symlink.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800234 std::string converted_image_filename = space->GetImageLocation();
235 std::replace(converted_image_filename.begin() + 1, converted_image_filename.end(), '/', '@');
236 std::string output_image_filename = output_directory +
Andreas Gampe9186ced2016-12-12 14:28:21 -0800237 (android::base::StartsWith(converted_image_filename, "/") ? "" : "/") +
238 converted_image_filename;
David Brazdil7b49e6c2016-09-01 11:06:18 +0100239 std::string output_vdex_filename =
240 ImageHeader::GetVdexLocationFromImageLocation(output_image_filename);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800241 std::string output_oat_filename =
242 ImageHeader::GetOatLocationFromImageLocation(output_image_filename);
243
244 if (!ReplaceOatFileWithSymlink(input_oat_file->GetPath(),
Richard Uhler4bc11d02017-02-01 09:53:54 +0000245 output_oat_filename) ||
David Brazdil7b49e6c2016-09-01 11:06:18 +0100246 !SymlinkFile(input_vdex_filename, output_vdex_filename)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800247 // Errors already logged by above call.
248 return false;
249 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800250 }
251
252 PatchOat& p = space_to_patchoat_map.emplace(space,
253 PatchOat(
254 isa,
Jeff Haodcdc85b2015-12-04 14:06:18 -0800255 space_to_memmap_map.find(space)->second.get(),
256 space->GetLiveBitmap(),
257 space->GetMemMap(),
258 delta,
259 &space_to_memmap_map,
260 timings)).first->second;
261
Richard Uhler4bc11d02017-02-01 09:53:54 +0000262 t.NewTiming("Patching image");
Jeff Haodcdc85b2015-12-04 14:06:18 -0800263 if (!p.PatchImage(i == 0)) {
264 LOG(ERROR) << "Failed to patch image file " << input_image_filename;
265 return false;
266 }
Alex Light53cb16b2014-06-12 11:26:29 -0700267 }
268
Richard Uhler4bc11d02017-02-01 09:53:54 +0000269 // Write the patched image spaces.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800270 for (size_t i = 0; i < spaces.size(); ++i) {
271 gc::space::ImageSpace* space = spaces[i];
Jeff Haodcdc85b2015-12-04 14:06:18 -0800272
Richard Uhler4bc11d02017-02-01 09:53:54 +0000273 t.NewTiming("Writing image");
Jeff Haodcdc85b2015-12-04 14:06:18 -0800274 std::string converted_image_filename = space->GetImageLocation();
275 std::replace(converted_image_filename.begin() + 1, converted_image_filename.end(), '/', '@');
276 std::string output_image_filename = output_directory +
Andreas Gampe9186ced2016-12-12 14:28:21 -0800277 (android::base::StartsWith(converted_image_filename, "/") ? "" : "/") +
278 converted_image_filename;
Richard Uhler4bc11d02017-02-01 09:53:54 +0000279 std::unique_ptr<File> output_image_file(CreateOrOpen(output_image_filename.c_str()));
Jeff Haodcdc85b2015-12-04 14:06:18 -0800280 if (output_image_file.get() == nullptr) {
281 LOG(ERROR) << "Failed to open output image file at " << output_image_filename;
282 return false;
283 }
284
285 PatchOat& p = space_to_patchoat_map.find(space)->second;
286
Serdjuk, Nikolay Yd12f9c12016-03-22 10:06:33 +0600287 bool success = p.WriteImage(output_image_file.get());
288 success = FinishFile(output_image_file.get(), success);
289 if (!success) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800290 return false;
291 }
Alex Light53cb16b2014-06-12 11:26:29 -0700292 }
Andreas Gampeb8cc1752017-04-26 21:28:50 -0700293
294 if (!kIsDebugBuild && !(RUNNING_ON_MEMORY_TOOL && kMemoryToolDetectsLeaks)) {
295 // We want to just exit on non-debug builds, not bringing the runtime down
296 // in an orderly fashion. So release the following fields.
297 runtime.release();
298 }
299
Alex Light53cb16b2014-06-12 11:26:29 -0700300 return true;
301}
302
Alex Light53cb16b2014-06-12 11:26:29 -0700303bool PatchOat::WriteImage(File* out) {
Alex Lighteefbe392014-07-08 09:53:18 -0700304 TimingLogger::ScopedTiming t("Writing image File", timings_);
Alex Lighta59dd802014-07-02 16:28:08 -0700305 std::string error_msg;
306
Narayan Kamatha3d27eb2017-05-11 13:50:59 +0100307 // No error checking here, this is best effort. The locking may or may not
308 // succeed and we don't really care either way.
309 ScopedFlock img_flock = LockedFile::DupOf(out->Fd(), out->GetPath(),
310 true /* read_only_mode */, &error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -0700311
Alex Light53cb16b2014-06-12 11:26:29 -0700312 CHECK(image_ != nullptr);
313 CHECK(out != nullptr);
314 size_t expect = image_->Size();
315 if (out->WriteFully(reinterpret_cast<char*>(image_->Begin()), expect) &&
316 out->SetLength(expect) == 0) {
317 return true;
318 } else {
319 LOG(ERROR) << "Writing to image file " << out->GetPath() << " failed.";
320 return false;
321 }
322}
323
Igor Murashkin46774762014-10-22 11:37:02 -0700324bool PatchOat::IsImagePic(const ImageHeader& image_header, const std::string& image_path) {
325 if (!image_header.CompilePic()) {
326 if (kIsDebugBuild) {
327 LOG(INFO) << "image at location " << image_path << " was *not* compiled pic";
328 }
329 return false;
330 }
331
332 if (kIsDebugBuild) {
333 LOG(INFO) << "image at location " << image_path << " was compiled PIC";
334 }
335
336 return true;
337}
338
339PatchOat::MaybePic PatchOat::IsOatPic(const ElfFile* oat_in) {
340 if (oat_in == nullptr) {
341 LOG(ERROR) << "No ELF input oat fie available";
342 return ERROR_OAT_FILE;
343 }
344
Brian Carlstromf5b0f2c2016-10-14 01:04:26 -0700345 const std::string& file_path = oat_in->GetFilePath();
Igor Murashkin46774762014-10-22 11:37:02 -0700346
347 const OatHeader* oat_header = GetOatHeader(oat_in);
348 if (oat_header == nullptr) {
349 LOG(ERROR) << "Failed to find oat header in oat file " << file_path;
350 return ERROR_OAT_FILE;
351 }
352
353 if (!oat_header->IsValid()) {
354 LOG(ERROR) << "Elf file " << file_path << " has an invalid oat header";
355 return ERROR_OAT_FILE;
356 }
357
358 bool is_pic = oat_header->IsPic();
359 if (kIsDebugBuild) {
360 LOG(INFO) << "Oat file at " << file_path << " is " << (is_pic ? "PIC" : "not pic");
361 }
362
363 return is_pic ? PIC : NOT_PIC;
364}
365
366bool PatchOat::ReplaceOatFileWithSymlink(const std::string& input_oat_filename,
Richard Uhler4bc11d02017-02-01 09:53:54 +0000367 const std::string& output_oat_filename) {
Igor Murashkin46774762014-10-22 11:37:02 -0700368 // Delete the original file, since we won't need it.
Dimitry Ivanov7a1c0142016-03-17 15:59:38 -0700369 unlink(output_oat_filename.c_str());
Igor Murashkin46774762014-10-22 11:37:02 -0700370
371 // Create a symlink from the old oat to the new oat
372 if (symlink(input_oat_filename.c_str(), output_oat_filename.c_str()) < 0) {
373 int err = errno;
374 LOG(ERROR) << "Failed to create symlink at " << output_oat_filename
375 << " error(" << err << "): " << strerror(err);
376 return false;
377 }
378
379 if (kIsDebugBuild) {
380 LOG(INFO) << "Created symlink " << output_oat_filename << " -> " << input_oat_filename;
381 }
382
383 return true;
384}
385
Vladimir Markoad06b982016-11-17 16:38:59 +0000386class PatchOat::PatchOatArtFieldVisitor : public ArtFieldVisitor {
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700387 public:
388 explicit PatchOatArtFieldVisitor(PatchOat* patch_oat) : patch_oat_(patch_oat) {}
389
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700390 void Visit(ArtField* field) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700391 ArtField* const dest = patch_oat_->RelocatedCopyOf(field);
Mathieu Chartier3398c782016-09-30 10:27:43 -0700392 dest->SetDeclaringClass(
Mathieu Chartier1cc62e42016-10-03 18:01:28 -0700393 patch_oat_->RelocatedAddressOfPointer(field->GetDeclaringClass().Ptr()));
Mathieu Chartiere401d142015-04-22 13:56:20 -0700394 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700395
396 private:
397 PatchOat* const patch_oat_;
398};
399
400void PatchOat::PatchArtFields(const ImageHeader* image_header) {
401 PatchOatArtFieldVisitor visitor(this);
Mathieu Chartiere42888f2016-04-14 10:49:19 -0700402 image_header->VisitPackedArtFields(&visitor, heap_->Begin());
Mathieu Chartiere401d142015-04-22 13:56:20 -0700403}
404
Vladimir Markoad06b982016-11-17 16:38:59 +0000405class PatchOat::PatchOatArtMethodVisitor : public ArtMethodVisitor {
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700406 public:
407 explicit PatchOatArtMethodVisitor(PatchOat* patch_oat) : patch_oat_(patch_oat) {}
408
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700409 void Visit(ArtMethod* method) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700410 ArtMethod* const dest = patch_oat_->RelocatedCopyOf(method);
411 patch_oat_->FixupMethod(method, dest);
412 }
413
414 private:
415 PatchOat* const patch_oat_;
416};
417
Mathieu Chartiere401d142015-04-22 13:56:20 -0700418void PatchOat::PatchArtMethods(const ImageHeader* image_header) {
Andreas Gampe542451c2016-07-26 09:02:02 -0700419 const PointerSize pointer_size = InstructionSetPointerSize(isa_);
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700420 PatchOatArtMethodVisitor visitor(this);
Mathieu Chartiere42888f2016-04-14 10:49:19 -0700421 image_header->VisitPackedArtMethods(&visitor, heap_->Begin(), pointer_size);
422}
423
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +0000424void PatchOat::PatchImTables(const ImageHeader* image_header) {
Andreas Gampe542451c2016-07-26 09:02:02 -0700425 const PointerSize pointer_size = InstructionSetPointerSize(isa_);
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +0000426 // We can safely walk target image since the conflict tables are independent.
427 image_header->VisitPackedImTables(
428 [this](ArtMethod* method) {
429 return RelocatedAddressOfPointer(method);
430 },
431 image_->Begin(),
432 pointer_size);
433}
434
Mathieu Chartiere42888f2016-04-14 10:49:19 -0700435void PatchOat::PatchImtConflictTables(const ImageHeader* image_header) {
Andreas Gampe542451c2016-07-26 09:02:02 -0700436 const PointerSize pointer_size = InstructionSetPointerSize(isa_);
Mathieu Chartiere42888f2016-04-14 10:49:19 -0700437 // We can safely walk target image since the conflict tables are independent.
438 image_header->VisitPackedImtConflictTables(
439 [this](ArtMethod* method) {
440 return RelocatedAddressOfPointer(method);
441 },
442 image_->Begin(),
443 pointer_size);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700444}
445
Vladimir Markoad06b982016-11-17 16:38:59 +0000446class PatchOat::FixupRootVisitor : public RootVisitor {
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700447 public:
448 explicit FixupRootVisitor(const PatchOat* patch_oat) : patch_oat_(patch_oat) {
449 }
450
451 void VisitRoots(mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700452 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700453 for (size_t i = 0; i < count; ++i) {
454 *roots[i] = patch_oat_->RelocatedAddressOfPointer(*roots[i]);
455 }
456 }
457
458 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots, size_t count,
459 const RootInfo& info ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700460 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700461 for (size_t i = 0; i < count; ++i) {
462 roots[i]->Assign(patch_oat_->RelocatedAddressOfPointer(roots[i]->AsMirrorPtr()));
463 }
464 }
465
466 private:
467 const PatchOat* const patch_oat_;
468};
469
470void PatchOat::PatchInternedStrings(const ImageHeader* image_header) {
471 const auto& section = image_header->GetImageSection(ImageHeader::kSectionInternedStrings);
472 InternTable temp_table;
473 // 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.
Mathieu Chartierea0831f2015-12-29 13:17:37 -0800476 temp_table.AddTableFromMemory(image_->Begin() + section.Offset());
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700477 FixupRootVisitor visitor(this);
478 temp_table.VisitRoots(&visitor, kVisitRootFlagAllRoots);
479}
480
Mathieu Chartier208a5cb2015-12-02 15:44:07 -0800481void PatchOat::PatchClassTable(const ImageHeader* image_header) {
482 const auto& section = image_header->GetImageSection(ImageHeader::kSectionClassTable);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800483 if (section.Size() == 0) {
484 return;
485 }
Mathieu Chartier208a5cb2015-12-02 15:44:07 -0800486 // Note that we require that ReadFromMemory does not make an internal copy of the elements.
487 // This also relies on visit roots not doing any verification which could fail after we update
488 // the roots to be the image addresses.
489 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
490 ClassTable temp_table;
491 temp_table.ReadFromMemory(image_->Begin() + section.Offset());
492 FixupRootVisitor visitor(this);
Mathieu Chartier58c3f6a2016-12-01 14:21:11 -0800493 temp_table.VisitRoots(UnbufferedRootVisitor(&visitor, RootInfo(kRootUnknown)));
Mathieu Chartier208a5cb2015-12-02 15:44:07 -0800494}
495
496
Vladimir Markoad06b982016-11-17 16:38:59 +0000497class PatchOat::RelocatedPointerVisitor {
Mathieu Chartier4b00d342015-11-13 10:42:08 -0800498 public:
499 explicit RelocatedPointerVisitor(PatchOat* patch_oat) : patch_oat_(patch_oat) {}
500
501 template <typename T>
Mathieu Chartier8c19d242017-03-06 12:35:10 -0800502 T* operator()(T* ptr, void** dest_addr ATTRIBUTE_UNUSED = 0) const {
Mathieu Chartier4b00d342015-11-13 10:42:08 -0800503 return patch_oat_->RelocatedAddressOfPointer(ptr);
504 }
505
506 private:
507 PatchOat* const patch_oat_;
508};
509
Mathieu Chartierc7853442015-03-27 14:35:38 -0700510void PatchOat::PatchDexFileArrays(mirror::ObjectArray<mirror::Object>* img_roots) {
511 auto* dex_caches = down_cast<mirror::ObjectArray<mirror::DexCache>*>(
512 img_roots->Get(ImageHeader::kDexCaches));
Andreas Gampe542451c2016-07-26 09:02:02 -0700513 const PointerSize pointer_size = InstructionSetPointerSize(isa_);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700514 for (size_t i = 0, count = dex_caches->GetLength(); i < count; ++i) {
Vladimir Marko05792b92015-08-03 11:56:49 +0100515 auto* orig_dex_cache = dex_caches->GetWithoutChecks(i);
516 auto* copy_dex_cache = RelocatedCopyOf(orig_dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +0100517 // Though the DexCache array fields are usually treated as native pointers, we set the full
518 // 64-bit values here, clearing the top 32 bits for 32-bit targets. The zero-extension is
519 // done by casting to the unsigned type uintptr_t before casting to int64_t, i.e.
520 // static_cast<int64_t>(reinterpret_cast<uintptr_t>(image_begin_ + offset))).
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -0700521 mirror::StringDexCacheType* orig_strings = orig_dex_cache->GetStrings();
522 mirror::StringDexCacheType* relocated_strings = RelocatedAddressOfPointer(orig_strings);
Vladimir Marko05792b92015-08-03 11:56:49 +0100523 copy_dex_cache->SetField64<false>(
524 mirror::DexCache::StringsOffset(),
525 static_cast<int64_t>(reinterpret_cast<uintptr_t>(relocated_strings)));
526 if (orig_strings != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -0800527 orig_dex_cache->FixupStrings(RelocatedCopyOf(orig_strings), RelocatedPointerVisitor(this));
Mathieu Chartierc7853442015-03-27 14:35:38 -0700528 }
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000529 mirror::TypeDexCacheType* orig_types = orig_dex_cache->GetResolvedTypes();
530 mirror::TypeDexCacheType* relocated_types = RelocatedAddressOfPointer(orig_types);
Vladimir Marko05792b92015-08-03 11:56:49 +0100531 copy_dex_cache->SetField64<false>(
532 mirror::DexCache::ResolvedTypesOffset(),
533 static_cast<int64_t>(reinterpret_cast<uintptr_t>(relocated_types)));
534 if (orig_types != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -0800535 orig_dex_cache->FixupResolvedTypes(RelocatedCopyOf(orig_types),
536 RelocatedPointerVisitor(this));
Vladimir Marko05792b92015-08-03 11:56:49 +0100537 }
538 ArtMethod** orig_methods = orig_dex_cache->GetResolvedMethods();
539 ArtMethod** relocated_methods = RelocatedAddressOfPointer(orig_methods);
540 copy_dex_cache->SetField64<false>(
541 mirror::DexCache::ResolvedMethodsOffset(),
542 static_cast<int64_t>(reinterpret_cast<uintptr_t>(relocated_methods)));
543 if (orig_methods != nullptr) {
544 ArtMethod** copy_methods = RelocatedCopyOf(orig_methods);
545 for (size_t j = 0, num = orig_dex_cache->NumResolvedMethods(); j != num; ++j) {
546 ArtMethod* orig = mirror::DexCache::GetElementPtrSize(orig_methods, j, pointer_size);
547 ArtMethod* copy = RelocatedAddressOfPointer(orig);
548 mirror::DexCache::SetElementPtrSize(copy_methods, j, copy, pointer_size);
549 }
550 }
Vladimir Markof44d36c2017-03-14 14:18:46 +0000551 mirror::FieldDexCacheType* orig_fields = orig_dex_cache->GetResolvedFields();
552 mirror::FieldDexCacheType* relocated_fields = RelocatedAddressOfPointer(orig_fields);
Vladimir Marko05792b92015-08-03 11:56:49 +0100553 copy_dex_cache->SetField64<false>(
554 mirror::DexCache::ResolvedFieldsOffset(),
555 static_cast<int64_t>(reinterpret_cast<uintptr_t>(relocated_fields)));
556 if (orig_fields != nullptr) {
Vladimir Markof44d36c2017-03-14 14:18:46 +0000557 mirror::FieldDexCacheType* copy_fields = RelocatedCopyOf(orig_fields);
Vladimir Marko05792b92015-08-03 11:56:49 +0100558 for (size_t j = 0, num = orig_dex_cache->NumResolvedFields(); j != num; ++j) {
Vladimir Markof44d36c2017-03-14 14:18:46 +0000559 mirror::FieldDexCachePair orig =
560 mirror::DexCache::GetNativePairPtrSize(orig_fields, j, pointer_size);
561 mirror::FieldDexCachePair copy(RelocatedAddressOfPointer(orig.object), orig.index);
562 mirror::DexCache::SetNativePairPtrSize(copy_fields, j, copy, pointer_size);
Vladimir Marko05792b92015-08-03 11:56:49 +0100563 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700564 }
Narayan Kamath7fe56582016-10-14 18:49:12 +0100565 mirror::MethodTypeDexCacheType* orig_method_types = orig_dex_cache->GetResolvedMethodTypes();
566 mirror::MethodTypeDexCacheType* relocated_method_types =
567 RelocatedAddressOfPointer(orig_method_types);
568 copy_dex_cache->SetField64<false>(
569 mirror::DexCache::ResolvedMethodTypesOffset(),
570 static_cast<int64_t>(reinterpret_cast<uintptr_t>(relocated_method_types)));
571 if (orig_method_types != nullptr) {
572 orig_dex_cache->FixupResolvedMethodTypes(RelocatedCopyOf(orig_method_types),
573 RelocatedPointerVisitor(this));
574 }
Orion Hodsonc069a302017-01-18 09:23:12 +0000575
576 GcRoot<mirror::CallSite>* orig_call_sites = orig_dex_cache->GetResolvedCallSites();
577 GcRoot<mirror::CallSite>* relocated_call_sites = RelocatedAddressOfPointer(orig_call_sites);
578 copy_dex_cache->SetField64<false>(
579 mirror::DexCache::ResolvedCallSitesOffset(),
580 static_cast<int64_t>(reinterpret_cast<uintptr_t>(relocated_call_sites)));
581 if (orig_call_sites != nullptr) {
582 orig_dex_cache->FixupResolvedCallSites(RelocatedCopyOf(orig_call_sites),
583 RelocatedPointerVisitor(this));
584 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700585 }
586}
587
Jeff Haodcdc85b2015-12-04 14:06:18 -0800588bool PatchOat::PatchImage(bool primary_image) {
Alex Light53cb16b2014-06-12 11:26:29 -0700589 ImageHeader* image_header = reinterpret_cast<ImageHeader*>(image_->Begin());
590 CHECK_GT(image_->Size(), sizeof(ImageHeader));
591 // These are the roots from the original file.
Mathieu Chartierc7853442015-03-27 14:35:38 -0700592 auto* img_roots = image_header->GetImageRoots();
Alex Light53cb16b2014-06-12 11:26:29 -0700593 image_header->RelocateImage(delta_);
594
Mathieu Chartierc7853442015-03-27 14:35:38 -0700595 PatchArtFields(image_header);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700596 PatchArtMethods(image_header);
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +0000597 PatchImTables(image_header);
Mathieu Chartiere42888f2016-04-14 10:49:19 -0700598 PatchImtConflictTables(image_header);
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700599 PatchInternedStrings(image_header);
Mathieu Chartier208a5cb2015-12-02 15:44:07 -0800600 PatchClassTable(image_header);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700601 // Patch dex file int/long arrays which point to ArtFields.
602 PatchDexFileArrays(img_roots);
603
Jeff Haodcdc85b2015-12-04 14:06:18 -0800604 if (primary_image) {
605 VisitObject(img_roots);
606 }
607
Alex Light53cb16b2014-06-12 11:26:29 -0700608 if (!image_header->IsValid()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800609 LOG(ERROR) << "relocation renders image header invalid";
Alex Light53cb16b2014-06-12 11:26:29 -0700610 return false;
611 }
612
613 {
Alex Lighteefbe392014-07-08 09:53:18 -0700614 TimingLogger::ScopedTiming t("Walk Bitmap", timings_);
Alex Light53cb16b2014-06-12 11:26:29 -0700615 // Walk the bitmap.
616 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
617 bitmap_->Walk(PatchOat::BitmapCallback, this);
618 }
619 return true;
620}
621
Alex Light53cb16b2014-06-12 11:26:29 -0700622
Mathieu Chartier31e88222016-10-14 18:43:19 -0700623void PatchOat::PatchVisitor::operator() (ObjPtr<mirror::Object> obj,
624 MemberOffset off,
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700625 bool is_static_unused ATTRIBUTE_UNUSED) const {
Alex Light53cb16b2014-06-12 11:26:29 -0700626 mirror::Object* referent = obj->GetFieldObject<mirror::Object, kVerifyNone>(off);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700627 mirror::Object* moved_object = patcher_->RelocatedAddressOfPointer(referent);
Alex Light53cb16b2014-06-12 11:26:29 -0700628 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(off, moved_object);
629}
630
Mathieu Chartier31e88222016-10-14 18:43:19 -0700631void PatchOat::PatchVisitor::operator() (ObjPtr<mirror::Class> cls ATTRIBUTE_UNUSED,
632 ObjPtr<mirror::Reference> ref) const {
Alex Light53cb16b2014-06-12 11:26:29 -0700633 MemberOffset off = mirror::Reference::ReferentOffset();
634 mirror::Object* referent = ref->GetReferent();
Mathieu Chartiera13abba2016-04-21 10:23:16 -0700635 DCHECK(referent == nullptr ||
636 Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(referent)) << referent;
Mathieu Chartierc7853442015-03-27 14:35:38 -0700637 mirror::Object* moved_object = patcher_->RelocatedAddressOfPointer(referent);
Alex Light53cb16b2014-06-12 11:26:29 -0700638 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(off, moved_object);
639}
640
Alex Light53cb16b2014-06-12 11:26:29 -0700641// Called by BitmapCallback
642void PatchOat::VisitObject(mirror::Object* object) {
643 mirror::Object* copy = RelocatedCopyOf(object);
644 CHECK(copy != nullptr);
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700645 if (kUseBakerReadBarrier) {
646 object->AssertReadBarrierState();
Alex Light53cb16b2014-06-12 11:26:29 -0700647 }
648 PatchOat::PatchVisitor visitor(this, copy);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -0700649 object->VisitReferences<kVerifyNone>(visitor, visitor);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700650 if (object->IsClass<kVerifyNone>()) {
Andreas Gampe542451c2016-07-26 09:02:02 -0700651 const PointerSize pointer_size = InstructionSetPointerSize(isa_);
Mathieu Chartier4b00d342015-11-13 10:42:08 -0800652 mirror::Class* klass = object->AsClass();
653 mirror::Class* copy_klass = down_cast<mirror::Class*>(copy);
654 RelocatedPointerVisitor native_visitor(this);
655 klass->FixupNativePointers(copy_klass, pointer_size, native_visitor);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700656 auto* vtable = klass->GetVTable();
657 if (vtable != nullptr) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800658 vtable->Fixup(RelocatedCopyOfFollowImages(vtable), pointer_size, native_visitor);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700659 }
Mathieu Chartier6beced42016-11-15 15:51:31 -0800660 mirror::IfTable* iftable = klass->GetIfTable();
661 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
662 if (iftable->GetMethodArrayCount(i) > 0) {
663 auto* method_array = iftable->GetMethodArray(i);
664 CHECK(method_array != nullptr);
665 method_array->Fixup(RelocatedCopyOfFollowImages(method_array),
666 pointer_size,
667 native_visitor);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700668 }
669 }
Mathieu Chartier4b00d342015-11-13 10:42:08 -0800670 } else if (object->GetClass() == mirror::Method::StaticClass() ||
671 object->GetClass() == mirror::Constructor::StaticClass()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700672 // Need to go update the ArtMethod.
Neil Fuller0e844392016-09-08 13:43:31 +0100673 auto* dest = down_cast<mirror::Executable*>(copy);
674 auto* src = down_cast<mirror::Executable*>(object);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700675 dest->SetArtMethod(RelocatedAddressOfPointer(src->GetArtMethod()));
Alex Light53cb16b2014-06-12 11:26:29 -0700676 }
677}
678
Mathieu Chartiere401d142015-04-22 13:56:20 -0700679void PatchOat::FixupMethod(ArtMethod* object, ArtMethod* copy) {
Andreas Gampe542451c2016-07-26 09:02:02 -0700680 const PointerSize pointer_size = InstructionSetPointerSize(isa_);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700681 copy->CopyFrom(object, pointer_size);
Alex Light53cb16b2014-06-12 11:26:29 -0700682 // Just update the entry points if it looks like we should.
Alex Lighteefbe392014-07-08 09:53:18 -0700683 // TODO: sanity check all the pointers' values
Mathieu Chartiere401d142015-04-22 13:56:20 -0700684 copy->SetDeclaringClass(RelocatedAddressOfPointer(object->GetDeclaringClass()));
Vladimir Marko05792b92015-08-03 11:56:49 +0100685 copy->SetDexCacheResolvedMethods(
686 RelocatedAddressOfPointer(object->GetDexCacheResolvedMethods(pointer_size)), pointer_size);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700687 copy->SetEntryPointFromQuickCompiledCodePtrSize(RelocatedAddressOfPointer(
688 object->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size)), pointer_size);
Mathieu Chartiere42888f2016-04-14 10:49:19 -0700689 // No special handling for IMT conflict table since all pointers are moved by the same offset.
Andreas Gampe75f08852016-07-19 08:06:07 -0700690 copy->SetDataPtrSize(RelocatedAddressOfPointer(
691 object->GetDataPtrSize(pointer_size)), pointer_size);
Alex Light53cb16b2014-06-12 11:26:29 -0700692}
693
Alex Light53cb16b2014-06-12 11:26:29 -0700694static int orig_argc;
695static char** orig_argv;
696
697static std::string CommandLine() {
698 std::vector<std::string> command;
699 for (int i = 0; i < orig_argc; ++i) {
700 command.push_back(orig_argv[i]);
701 }
Andreas Gampe9186ced2016-12-12 14:28:21 -0800702 return android::base::Join(command, ' ');
Alex Light53cb16b2014-06-12 11:26:29 -0700703}
704
705static void UsageErrorV(const char* fmt, va_list ap) {
706 std::string error;
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800707 android::base::StringAppendV(&error, fmt, ap);
Alex Light53cb16b2014-06-12 11:26:29 -0700708 LOG(ERROR) << error;
709}
710
711static void UsageError(const char* fmt, ...) {
712 va_list ap;
713 va_start(ap, fmt);
714 UsageErrorV(fmt, ap);
715 va_end(ap);
716}
717
Andreas Gampe794ad762015-02-23 08:12:24 -0800718NO_RETURN static void Usage(const char *fmt, ...) {
Alex Light53cb16b2014-06-12 11:26:29 -0700719 va_list ap;
720 va_start(ap, fmt);
721 UsageErrorV(fmt, ap);
722 va_end(ap);
723
724 UsageError("Command: %s", CommandLine().c_str());
725 UsageError("Usage: patchoat [options]...");
726 UsageError("");
727 UsageError(" --instruction-set=<isa>: Specifies the instruction set the patched code is");
Richard Uhler4bc11d02017-02-01 09:53:54 +0000728 UsageError(" compiled for (required).");
Alex Light53cb16b2014-06-12 11:26:29 -0700729 UsageError("");
730 UsageError(" --input-image-location=<file.art>: Specifies the 'location' of the image file to");
Richard Uhler4bc11d02017-02-01 09:53:54 +0000731 UsageError(" be patched.");
Alex Light53cb16b2014-06-12 11:26:29 -0700732 UsageError("");
733 UsageError(" --output-image-file=<file.art>: Specifies the exact file to write the patched");
734 UsageError(" image file to.");
735 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700736 UsageError(" --base-offset-delta=<delta>: Specify the amount to change the old base-offset by.");
737 UsageError(" This value may be negative.");
738 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700739 UsageError(" --dump-timings: dump out patch timing information");
740 UsageError("");
741 UsageError(" --no-dump-timings: do not dump out patch timing information");
742 UsageError("");
743
744 exit(EXIT_FAILURE);
745}
746
Andreas Gampe6eb6a392016-02-10 20:18:37 -0800747static int patchoat_image(TimingLogger& timings,
748 InstructionSet isa,
749 const std::string& input_image_location,
750 const std::string& output_image_filename,
751 off_t base_delta,
752 bool base_delta_set,
753 bool debug) {
754 CHECK(!input_image_location.empty());
755 if (output_image_filename.empty()) {
756 Usage("Image patching requires --output-image-file");
757 }
758
759 if (!base_delta_set) {
760 Usage("Must supply a desired new offset or delta.");
761 }
762
763 if (!IsAligned<kPageSize>(base_delta)) {
764 Usage("Base offset/delta must be aligned to a pagesize (0x%08x) boundary.", kPageSize);
765 }
766
767 if (debug) {
768 LOG(INFO) << "moving offset by " << base_delta
769 << " (0x" << std::hex << base_delta << ") bytes or "
770 << std::dec << (base_delta/kPageSize) << " pages.";
771 }
772
773 TimingLogger::ScopedTiming pt("patch image and oat", &timings);
774
775 std::string output_directory =
Andreas Gampeca620d72016-11-08 08:09:33 -0800776 output_image_filename.substr(0, output_image_filename.find_last_of('/'));
Andreas Gampe6eb6a392016-02-10 20:18:37 -0800777 bool ret = PatchOat::Patch(input_image_location, base_delta, output_directory, isa, &timings);
778
779 if (kIsDebugBuild) {
780 LOG(INFO) << "Exiting with return ... " << ret;
781 }
782 return ret ? EXIT_SUCCESS : EXIT_FAILURE;
783}
784
Alex Lighteefbe392014-07-08 09:53:18 -0700785static int patchoat(int argc, char **argv) {
Andreas Gampe51d80cc2017-06-21 21:05:13 -0700786 InitLogging(argv, Runtime::Abort);
Mathieu Chartier6e88ef62014-10-14 15:01:24 -0700787 MemMap::Init();
Alex Light53cb16b2014-06-12 11:26:29 -0700788 const bool debug = kIsDebugBuild;
789 orig_argc = argc;
790 orig_argv = argv;
791 TimingLogger timings("patcher", false, false);
792
Alex Light53cb16b2014-06-12 11:26:29 -0700793 // Skip over the command name.
794 argv++;
795 argc--;
796
797 if (argc == 0) {
798 Usage("No arguments specified");
799 }
800
801 timings.StartTiming("Patchoat");
802
803 // cmd line args
804 bool isa_set = false;
805 InstructionSet isa = kNone;
Alex Light53cb16b2014-06-12 11:26:29 -0700806 std::string input_image_location;
Alex Light53cb16b2014-06-12 11:26:29 -0700807 std::string output_image_filename;
Alex Light53cb16b2014-06-12 11:26:29 -0700808 off_t base_delta = 0;
809 bool base_delta_set = false;
Alex Light53cb16b2014-06-12 11:26:29 -0700810 bool dump_timings = kIsDebugBuild;
811
Ian Rogersd4c4d952014-10-16 20:31:53 -0700812 for (int i = 0; i < argc; ++i) {
Alex Light53cb16b2014-06-12 11:26:29 -0700813 const StringPiece option(argv[i]);
814 const bool log_options = false;
815 if (log_options) {
816 LOG(INFO) << "patchoat: option[" << i << "]=" << argv[i];
817 }
Alex Light53cb16b2014-06-12 11:26:29 -0700818 if (option.starts_with("--instruction-set=")) {
819 isa_set = true;
820 const char* isa_str = option.substr(strlen("--instruction-set=")).data();
Andreas Gampe20c89302014-08-19 17:28:06 -0700821 isa = GetInstructionSetFromString(isa_str);
822 if (isa == kNone) {
823 Usage("Unknown or invalid instruction set %s", isa_str);
Alex Light53cb16b2014-06-12 11:26:29 -0700824 }
Alex Light53cb16b2014-06-12 11:26:29 -0700825 } else if (option.starts_with("--input-image-location=")) {
826 input_image_location = option.substr(strlen("--input-image-location=")).data();
Alex Light53cb16b2014-06-12 11:26:29 -0700827 } else if (option.starts_with("--output-image-file=")) {
Alex Light53cb16b2014-06-12 11:26:29 -0700828 output_image_filename = option.substr(strlen("--output-image-file=")).data();
Alex Light53cb16b2014-06-12 11:26:29 -0700829 } else if (option.starts_with("--base-offset-delta=")) {
830 const char* base_delta_str = option.substr(strlen("--base-offset-delta=")).data();
831 base_delta_set = true;
832 if (!ParseInt(base_delta_str, &base_delta)) {
833 Usage("Failed to parse --base-offset-delta argument '%s' as an off_t", base_delta_str);
834 }
Alex Light53cb16b2014-06-12 11:26:29 -0700835 } else if (option == "--dump-timings") {
836 dump_timings = true;
837 } else if (option == "--no-dump-timings") {
838 dump_timings = false;
839 } else {
840 Usage("Unknown argument %s", option.data());
841 }
842 }
843
Andreas Gampe6eb6a392016-02-10 20:18:37 -0800844 // The instruction set is mandatory. This simplifies things...
845 if (!isa_set) {
846 Usage("Instruction set must be set.");
Alex Light53cb16b2014-06-12 11:26:29 -0700847 }
848
Richard Uhler4bc11d02017-02-01 09:53:54 +0000849 int ret = patchoat_image(timings,
850 isa,
851 input_image_location,
852 output_image_filename,
853 base_delta,
854 base_delta_set,
855 debug);
Alex Light53cb16b2014-06-12 11:26:29 -0700856
Andreas Gampe6eb6a392016-02-10 20:18:37 -0800857 timings.EndTiming();
858 if (dump_timings) {
859 LOG(INFO) << Dumpable<TimingLogger>(timings);
Alex Light53cb16b2014-06-12 11:26:29 -0700860 }
861
Andreas Gampe6eb6a392016-02-10 20:18:37 -0800862 return ret;
Alex Light53cb16b2014-06-12 11:26:29 -0700863}
864
865} // namespace art
866
867int main(int argc, char **argv) {
868 return art::patchoat(argc, argv);
869}