blob: a15f7b88d86c1fa3244fdeac1aedf79efbd9f923 [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
Alex Klyubin3856af02017-10-23 13:53:13 -070018#include <openssl/sha.h>
Alex Light53cb16b2014-06-12 11:26:29 -070019#include <stdio.h>
20#include <stdlib.h>
Alex Lighta59dd802014-07-02 16:28:08 -070021#include <sys/file.h>
Alex Light53cb16b2014-06-12 11:26:29 -070022#include <sys/stat.h>
Alex Lighta59dd802014-07-02 16:28:08 -070023#include <unistd.h>
Alex Light53cb16b2014-06-12 11:26:29 -070024
25#include <string>
26#include <vector>
27
Chris Morin754b7572018-01-19 18:04:46 -080028#include "android-base/file.h"
Andreas Gampe46ee31b2016-12-14 10:11:49 -080029#include "android-base/stringprintf.h"
Andreas Gampe9186ced2016-12-12 14:28:21 -080030#include "android-base/strings.h"
31
Mathieu Chartierc7853442015-03-27 14:35:38 -070032#include "art_field-inl.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070033#include "art_method-inl.h"
Vladimir Marko6121aa62018-07-06 10:04:35 +010034#include "base/bit_memory_region.h"
Ian Rogersc7dd2952014-10-21 23:31:19 -070035#include "base/dumpable.h"
Chris Morin754b7572018-01-19 18:04:46 -080036#include "base/file_utils.h"
David Sehr67bf42e2018-02-26 16:43:04 -080037#include "base/leb128.h"
Andreas Gampe170331f2017-12-07 18:41:03 -080038#include "base/logging.h" // For InitLogging.
David Sehrc431b9d2018-03-02 12:01:51 -080039#include "base/mutex.h"
Vladimir Marko6121aa62018-07-06 10:04:35 +010040#include "base/memory_region.h"
Andreas Gampeb8cc1752017-04-26 21:28:50 -070041#include "base/memory_tool.h"
David Sehrc431b9d2018-03-02 12:01:51 -080042#include "base/os.h"
Alex Lighta59dd802014-07-02 16:28:08 -070043#include "base/scoped_flock.h"
Alex Light53cb16b2014-06-12 11:26:29 -070044#include "base/stringpiece.h"
Ian Rogersd4c4d952014-10-16 20:31:53 -070045#include "base/unix_file/fd_file.h"
David Brazdil7b49e6c2016-09-01 11:06:18 +010046#include "base/unix_file/random_access_file_utils.h"
David Sehrc431b9d2018-03-02 12:01:51 -080047#include "base/utils.h"
Vladimir Marko679730e2018-05-25 15:06:48 +010048#include "class_root.h"
Alex Light53cb16b2014-06-12 11:26:29 -070049#include "elf_file.h"
Tong Shen62d1ca32014-09-03 17:24:56 -070050#include "elf_file_impl.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070051#include "elf_utils.h"
Ian Rogerse63db272014-07-15 15:36:11 -070052#include "gc/space/image_space.h"
Mathieu Chartier4a26f172016-01-26 14:26:18 -080053#include "image-inl.h"
Andreas Gampeb2d18fa2017-06-06 20:46:10 -070054#include "intern_table.h"
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -070055#include "mirror/dex_cache.h"
Neil Fuller0e844392016-09-08 13:43:31 +010056#include "mirror/executable.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070057#include "mirror/method.h"
Alex Light53cb16b2014-06-12 11:26:29 -070058#include "mirror/object-inl.h"
Andreas Gampec6ea7d02017-02-01 16:46:28 -080059#include "mirror/object-refvisitor-inl.h"
Alex Light53cb16b2014-06-12 11:26:29 -070060#include "mirror/reference.h"
61#include "noop_compiler_callbacks.h"
62#include "offsets.h"
Alex Light53cb16b2014-06-12 11:26:29 -070063#include "runtime.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070064#include "scoped_thread_state_change-inl.h"
Alex Light53cb16b2014-06-12 11:26:29 -070065#include "thread.h"
Alex Light53cb16b2014-06-12 11:26:29 -070066
67namespace art {
68
Alex Klyubin3856af02017-10-23 13:53:13 -070069using android::base::StringPrintf;
70
Andreas Gampec7d25082018-03-09 12:06:45 -080071namespace {
72
Alex Light0eb76d22015-08-11 18:03:47 -070073static const OatHeader* GetOatHeader(const ElfFile* elf_file) {
74 uint64_t off = 0;
75 if (!elf_file->GetSectionOffsetAndSize(".rodata", &off, nullptr)) {
76 return nullptr;
77 }
78
79 OatHeader* oat_header = reinterpret_cast<OatHeader*>(elf_file->Begin() + off);
80 return oat_header;
81}
82
Richard Uhler4bc11d02017-02-01 09:53:54 +000083static File* CreateOrOpen(const char* name) {
Jeff Haodcdc85b2015-12-04 14:06:18 -080084 if (OS::FileExists(name)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -080085 return OS::OpenFileReadWrite(name);
86 } else {
Jeff Haodcdc85b2015-12-04 14:06:18 -080087 std::unique_ptr<File> f(OS::CreateEmptyFile(name));
88 if (f.get() != nullptr) {
89 if (fchmod(f->Fd(), 0644) != 0) {
90 PLOG(ERROR) << "Unable to make " << name << " world readable";
Dimitry Ivanov7a1c0142016-03-17 15:59:38 -070091 unlink(name);
Jeff Haodcdc85b2015-12-04 14:06:18 -080092 return nullptr;
93 }
94 }
95 return f.release();
96 }
97}
98
99// Either try to close the file (close=true), or erase it.
100static bool FinishFile(File* file, bool close) {
101 if (close) {
102 if (file->FlushCloseOrErase() != 0) {
103 PLOG(ERROR) << "Failed to flush and close file.";
104 return false;
105 }
106 return true;
107 } else {
108 file->Erase();
109 return false;
110 }
111}
112
David Brazdil7b49e6c2016-09-01 11:06:18 +0100113static bool SymlinkFile(const std::string& input_filename, const std::string& output_filename) {
114 if (input_filename == output_filename) {
115 // Input and output are the same, nothing to do.
116 return true;
117 }
118
119 // Unlink the original filename, since we are overwriting it.
120 unlink(output_filename.c_str());
121
122 // Create a symlink from the source file to the target path.
123 if (symlink(input_filename.c_str(), output_filename.c_str()) < 0) {
124 PLOG(ERROR) << "Failed to create symlink " << output_filename << " -> " << input_filename;
125 return false;
126 }
127
128 if (kIsDebugBuild) {
129 LOG(INFO) << "Created symlink " << output_filename << " -> " << input_filename;
130 }
131
132 return true;
133}
134
Andreas Gampec7d25082018-03-09 12:06:45 -0800135// Holder class for runtime options and related objects.
136class PatchoatRuntimeOptionsHolder {
137 public:
138 PatchoatRuntimeOptionsHolder(const std::string& image_location, InstructionSet isa) {
139 options_.push_back(std::make_pair("compilercallbacks", &callbacks_));
140 img_ = "-Ximage:" + image_location;
141 options_.push_back(std::make_pair(img_.c_str(), nullptr));
142 isa_name_ = GetInstructionSetString(isa);
143 options_.push_back(std::make_pair("imageinstructionset",
144 reinterpret_cast<const void*>(isa_name_.c_str())));
145 options_.push_back(std::make_pair("-Xno-sig-chain", nullptr));
146 // We do not want the runtime to attempt to patch the image.
147 options_.push_back(std::make_pair("-Xnorelocate", nullptr));
148 // Don't try to compile.
149 options_.push_back(std::make_pair("-Xnoimage-dex2oat", nullptr));
150 // Do not accept broken image.
151 options_.push_back(std::make_pair("-Xno-dex-file-fallback", nullptr));
152 }
153
154 const RuntimeOptions& GetRuntimeOptions() {
155 return options_;
156 }
157
158 private:
159 RuntimeOptions options_;
160 NoopCompilerCallbacks callbacks_;
161 std::string isa_name_;
162 std::string img_;
163};
164
165} // namespace
166
Alex Klyubin3856af02017-10-23 13:53:13 -0700167bool PatchOat::GeneratePatch(
168 const MemMap& original,
169 const MemMap& relocated,
170 std::vector<uint8_t>* output,
171 std::string* error_msg) {
172 // FORMAT of the patch (aka image relocation) file:
173 // * SHA-256 digest (32 bytes) of original/unrelocated file (e.g., the one from /system)
174 // * List of monotonically increasing offsets (max value defined by uint32_t) at which relocations
175 // occur.
176 // Each element is represented as the delta from the previous offset in the list (first element
177 // is a delta from 0). Each delta is encoded using unsigned LEB128: little-endian
178 // variable-length 7 bits per byte encoding, where all bytes have the highest bit (0x80) set
179 // except for the final byte which does not have that bit set. For example, 0x3f is offset 0x3f,
180 // whereas 0xbf 0x05 is offset (0x3f & 0x7f) | (0x5 << 7) which is 0x2bf. Most deltas end up
181 // being encoding using just one byte, achieving ~4x decrease in relocation file size compared
182 // to the encoding where offsets are stored verbatim, as uint32_t.
183
184 size_t original_size = original.Size();
185 size_t relocated_size = relocated.Size();
186 if (original_size != relocated_size) {
187 *error_msg =
188 StringPrintf(
189 "Original and relocated image sizes differ: %zu vs %zu", original_size, relocated_size);
190 return false;
191 }
Alex Klyubin3856af02017-10-23 13:53:13 -0700192 if (original_size > UINT32_MAX) {
193 *error_msg = StringPrintf("Image too large: %zu" , original_size);
194 return false;
195 }
196
197 const ImageHeader& relocated_header =
198 *reinterpret_cast<const ImageHeader*>(relocated.Begin());
199 // Offsets are supposed to differ between original and relocated by this value
200 off_t expected_diff = relocated_header.GetPatchDelta();
201 if (expected_diff == 0) {
202 // Can't identify offsets which are supposed to differ due to relocation
203 *error_msg = "Relocation delta is 0";
204 return false;
205 }
206
Vladimir Marko6121aa62018-07-06 10:04:35 +0100207 const ImageHeader* image_header = reinterpret_cast<const ImageHeader*>(original.Begin());
208 if (image_header->GetStorageMode() != ImageHeader::kStorageModeUncompressed) {
209 *error_msg = "Unexpected compressed image.";
210 return false;
211 }
212 if (image_header->IsAppImage()) {
213 *error_msg = "Unexpected app image.";
214 return false;
215 }
216 if (image_header->GetPointerSize() != PointerSize::k32 &&
217 image_header->GetPointerSize() != PointerSize::k64) {
218 *error_msg = "Unexpected pointer size.";
219 return false;
220 }
221 static_assert(sizeof(GcRoot<mirror::Object>) == sizeof(mirror::HeapReference<mirror::Object>),
222 "Expecting heap GC roots and references to have the same size.");
223 DCHECK_LE(sizeof(GcRoot<mirror::Object>), static_cast<size_t>(image_header->GetPointerSize()));
224
225 const size_t image_bitmap_offset = RoundUp(sizeof(ImageHeader) + image_header->GetDataSize(),
226 kPageSize);
227 const size_t end_of_bitmap = image_bitmap_offset + image_header->GetImageBitmapSection().Size();
228 const ImageSection& relocation_section = image_header->GetImageRelocationsSection();
229 MemoryRegion relocations_data(original.Begin() + end_of_bitmap, relocation_section.Size());
230 size_t image_end = image_header->GetClassTableSection().End();
231 if (!IsAligned<sizeof(GcRoot<mirror::Object>)>(image_end)) {
232 *error_msg = StringPrintf("Unaligned image end: %zu", image_end);
233 return false;
234 }
235 size_t num_indexes = image_end / sizeof(GcRoot<mirror::Object>);
236 if (relocation_section.Size() != BitsToBytesRoundUp(num_indexes)) {
237 *error_msg = StringPrintf("Unexpected size of relocation section: %zu expected: %zu",
238 static_cast<size_t>(relocation_section.Size()),
239 BitsToBytesRoundUp(num_indexes));
240 return false;
241 }
242 BitMemoryRegion relocation_bitmap(relocations_data, /* bit_offset */ 0u, num_indexes);
243
Alex Klyubin3856af02017-10-23 13:53:13 -0700244 // Output the SHA-256 digest of the original
245 output->resize(SHA256_DIGEST_LENGTH);
246 const uint8_t* original_bytes = original.Begin();
247 SHA256(original_bytes, original_size, output->data());
248
Vladimir Marko6121aa62018-07-06 10:04:35 +0100249 // Check the list of offsets at which the original and patched images differ.
Alex Klyubin3856af02017-10-23 13:53:13 -0700250 size_t diff_offset_count = 0;
251 const uint8_t* relocated_bytes = relocated.Begin();
Vladimir Marko6121aa62018-07-06 10:04:35 +0100252 for (size_t index = 0; index != num_indexes; ++index) {
253 size_t offset = index * sizeof(GcRoot<mirror::Object>);
Alex Klyubin3856af02017-10-23 13:53:13 -0700254 uint32_t original_value = *reinterpret_cast<const uint32_t*>(original_bytes + offset);
255 uint32_t relocated_value = *reinterpret_cast<const uint32_t*>(relocated_bytes + offset);
256 off_t diff = relocated_value - original_value;
257 if (diff == 0) {
Vladimir Marko6121aa62018-07-06 10:04:35 +0100258 CHECK(!relocation_bitmap.LoadBit(index));
Alex Klyubin3856af02017-10-23 13:53:13 -0700259 continue;
260 } else if (diff != expected_diff) {
261 *error_msg =
262 StringPrintf(
263 "Unexpected diff at offset %zu. Expected: %jd, but was: %jd",
264 offset,
265 (intmax_t) expected_diff,
266 (intmax_t) diff);
267 return false;
268 }
Vladimir Marko6121aa62018-07-06 10:04:35 +0100269 CHECK(relocation_bitmap.LoadBit(index));
Alex Klyubin3856af02017-10-23 13:53:13 -0700270 diff_offset_count++;
Alex Klyubin3856af02017-10-23 13:53:13 -0700271 }
Vladimir Marko6121aa62018-07-06 10:04:35 +0100272 size_t tail_bytes = original_size - image_end;
273 CHECK_EQ(memcmp(original_bytes + image_end, relocated_bytes + image_end, tail_bytes), 0);
Alex Klyubin3856af02017-10-23 13:53:13 -0700274
275 if (diff_offset_count == 0) {
276 *error_msg = "Original and patched images are identical";
277 return false;
278 }
279
280 return true;
281}
282
283static bool WriteRelFile(
284 const MemMap& original,
285 const MemMap& relocated,
286 const std::string& rel_filename,
287 std::string* error_msg) {
288 std::vector<uint8_t> output;
289 if (!PatchOat::GeneratePatch(original, relocated, &output, error_msg)) {
290 return false;
291 }
292
293 std::unique_ptr<File> rel_file(OS::CreateEmptyFileWriteOnly(rel_filename.c_str()));
294 if (rel_file.get() == nullptr) {
295 *error_msg = StringPrintf("Failed to create/open output file %s", rel_filename.c_str());
296 return false;
297 }
298 if (!rel_file->WriteFully(output.data(), output.size())) {
299 *error_msg = StringPrintf("Failed to write to %s", rel_filename.c_str());
300 return false;
301 }
302 if (rel_file->FlushCloseOrErase() != 0) {
303 *error_msg = StringPrintf("Failed to flush and close %s", rel_filename.c_str());
304 return false;
305 }
306
307 return true;
308}
309
Chris Morin754b7572018-01-19 18:04:46 -0800310static bool CheckImageIdenticalToOriginalExceptForRelocation(
311 const std::string& relocated_filename,
312 const std::string& original_filename,
313 std::string* error_msg) {
314 *error_msg = "";
315 std::string rel_filename = original_filename + ".rel";
316 std::unique_ptr<File> rel_file(OS::OpenFileForReading(rel_filename.c_str()));
317 if (rel_file.get() == nullptr) {
318 *error_msg = StringPrintf("Failed to open image relocation file %s", rel_filename.c_str());
319 return false;
320 }
321 int64_t rel_size = rel_file->GetLength();
322 if (rel_size < 0) {
323 *error_msg = StringPrintf("Error while getting size of image relocation file %s",
324 rel_filename.c_str());
325 return false;
326 }
Vladimir Marko6121aa62018-07-06 10:04:35 +0100327 if (rel_size != SHA256_DIGEST_LENGTH) {
328 *error_msg = StringPrintf("Unexpected size of image relocation file %s: %" PRId64
329 ", expected %zu",
330 rel_filename.c_str(),
331 rel_size,
332 static_cast<size_t>(SHA256_DIGEST_LENGTH));
333 return false;
334 }
Chris Morin754b7572018-01-19 18:04:46 -0800335 std::unique_ptr<uint8_t[]> rel(new uint8_t[rel_size]);
336 if (!rel_file->ReadFully(rel.get(), rel_size)) {
337 *error_msg = StringPrintf("Failed to read image relocation file %s", rel_filename.c_str());
338 return false;
339 }
340
341 std::unique_ptr<File> image_file(OS::OpenFileForReading(relocated_filename.c_str()));
342 if (image_file.get() == nullptr) {
343 *error_msg = StringPrintf("Unable to open relocated image file %s",
344 relocated_filename.c_str());
345 return false;
346 }
347
348 int64_t image_size = image_file->GetLength();
349 if (image_size < 0) {
350 *error_msg = StringPrintf("Error while getting size of relocated image file %s",
351 relocated_filename.c_str());
352 return false;
353 }
Vladimir Marko6121aa62018-07-06 10:04:35 +0100354 if (static_cast<uint64_t>(image_size) < sizeof(ImageHeader)) {
Chris Morin754b7572018-01-19 18:04:46 -0800355 *error_msg =
356 StringPrintf(
Vladimir Marko6121aa62018-07-06 10:04:35 +0100357 "Relocated image file %s too small: %" PRId64,
Chris Morin754b7572018-01-19 18:04:46 -0800358 relocated_filename.c_str(), image_size);
359 return false;
360 }
Orion Hodsonb348b3b2018-01-26 09:02:49 +0000361 if (image_size > std::numeric_limits<uint32_t>::max()) {
Chris Morin754b7572018-01-19 18:04:46 -0800362 *error_msg =
363 StringPrintf(
Orion Hodsonb348b3b2018-01-26 09:02:49 +0000364 "Relocated image file %s too large: %" PRId64, relocated_filename.c_str(), image_size);
Chris Morin754b7572018-01-19 18:04:46 -0800365 return false;
366 }
367
368 std::unique_ptr<uint8_t[]> image(new uint8_t[image_size]);
369 if (!image_file->ReadFully(image.get(), image_size)) {
370 *error_msg = StringPrintf("Failed to read relocated image file %s", relocated_filename.c_str());
371 return false;
372 }
373
Vladimir Marko6121aa62018-07-06 10:04:35 +0100374 const ImageHeader& image_header = *reinterpret_cast<const ImageHeader*>(image.get());
375 if (image_header.GetStorageMode() != ImageHeader::kStorageModeUncompressed) {
376 *error_msg = StringPrintf("Unsuported compressed image file %s",
377 relocated_filename.c_str());
378 return false;
379 }
380 size_t image_end = image_header.GetClassTableSection().End();
381 if (image_end > static_cast<uint64_t>(image_size) || !IsAligned<4u>(image_end)) {
382 *error_msg = StringPrintf("Heap size too big or unaligned in image file %s: %zu",
383 relocated_filename.c_str(),
384 image_end);
385 return false;
386 }
387 size_t number_of_relocation_locations = image_end / 4u;
388 const ImageSection& relocation_section = image_header.GetImageRelocationsSection();
389 if (relocation_section.Size() != BitsToBytesRoundUp(number_of_relocation_locations)) {
390 *error_msg = StringPrintf("Unexpected size of relocation section in image file %s: %zu"
391 " expected: %zu",
392 relocated_filename.c_str(),
393 static_cast<size_t>(relocation_section.Size()),
394 BitsToBytesRoundUp(number_of_relocation_locations));
395 return false;
396 }
397 if (relocation_section.End() != image_size) {
398 *error_msg = StringPrintf("Relocation section does not end at file end in image file %s: %zu"
399 " expected: %" PRId64,
400 relocated_filename.c_str(),
401 static_cast<size_t>(relocation_section.End()),
402 image_size);
Chris Morin754b7572018-01-19 18:04:46 -0800403 return false;
404 }
405
Chris Morin754b7572018-01-19 18:04:46 -0800406 off_t expected_diff = image_header.GetPatchDelta();
Chris Morin754b7572018-01-19 18:04:46 -0800407 if (expected_diff == 0) {
408 *error_msg = StringPrintf("Unsuported patch delta of zero in %s",
409 relocated_filename.c_str());
410 return false;
411 }
412
413 // Relocated image is expected to differ from the original due to relocation.
414 // Unrelocate the image in memory to compensate.
Vladimir Marko6121aa62018-07-06 10:04:35 +0100415 MemoryRegion relocations(image.get() + relocation_section.Offset(), relocation_section.Size());
416 BitMemoryRegion relocation_bitmask(relocations,
417 /* bit_offset */ 0u,
418 number_of_relocation_locations);
419 for (size_t index = 0; index != number_of_relocation_locations; ++index) {
420 if (relocation_bitmask.LoadBit(index)) {
421 uint32_t* image_value = reinterpret_cast<uint32_t*>(image.get() + index * 4u);
Chris Morin754b7572018-01-19 18:04:46 -0800422 *image_value -= expected_diff;
Chris Morin754b7572018-01-19 18:04:46 -0800423 }
424 }
425
426 // Image in memory is now supposed to be identical to the original. We
427 // confirm this by comparing the digest of the in-memory image to the expected
428 // digest from relocation file.
429 uint8_t image_digest[SHA256_DIGEST_LENGTH];
430 SHA256(image.get(), image_size, image_digest);
Vladimir Marko6121aa62018-07-06 10:04:35 +0100431 if (memcmp(image_digest, rel.get(), SHA256_DIGEST_LENGTH) != 0) {
Chris Morin754b7572018-01-19 18:04:46 -0800432 *error_msg =
433 StringPrintf(
434 "Relocated image %s does not match the original %s after unrelocation",
435 relocated_filename.c_str(),
436 original_filename.c_str());
437 return false;
438 }
439
440 // Relocated image is identical to the original, once relocations are taken into account
441 return true;
442}
443
Chris Morinae6832f2018-02-09 19:12:35 -0800444static bool VerifySymlink(const std::string& intended_target, const std::string& link_name) {
445 std::string actual_target;
446 if (!android::base::Readlink(link_name, &actual_target)) {
447 PLOG(ERROR) << "Readlink on " << link_name << " failed.";
448 return false;
449 }
450 return actual_target == intended_target;
451}
452
453static bool VerifyVdexAndOatSymlinks(const std::string& input_image_filename,
454 const std::string& output_image_filename) {
455 return VerifySymlink(ImageHeader::GetVdexLocationFromImageLocation(input_image_filename),
456 ImageHeader::GetVdexLocationFromImageLocation(output_image_filename))
457 && VerifySymlink(ImageHeader::GetOatLocationFromImageLocation(input_image_filename),
458 ImageHeader::GetOatLocationFromImageLocation(output_image_filename));
459}
460
461bool PatchOat::CreateVdexAndOatSymlinks(const std::string& input_image_filename,
462 const std::string& output_image_filename) {
463 std::string input_vdex_filename =
464 ImageHeader::GetVdexLocationFromImageLocation(input_image_filename);
465 std::string input_oat_filename =
466 ImageHeader::GetOatLocationFromImageLocation(input_image_filename);
467
468 std::unique_ptr<File> input_oat_file(OS::OpenFileForReading(input_oat_filename.c_str()));
469 if (input_oat_file.get() == nullptr) {
470 LOG(ERROR) << "Unable to open input oat file at " << input_oat_filename;
471 return false;
472 }
473 std::string error_msg;
474 std::unique_ptr<ElfFile> elf(ElfFile::Open(input_oat_file.get(),
475 PROT_READ | PROT_WRITE,
476 MAP_PRIVATE,
477 &error_msg));
478 if (elf.get() == nullptr) {
479 LOG(ERROR) << "Unable to open oat file " << input_oat_filename << " : " << error_msg;
480 return false;
481 }
482
483 MaybePic is_oat_pic = IsOatPic(elf.get());
484 if (is_oat_pic >= ERROR_FIRST) {
485 // Error logged by IsOatPic
486 return false;
487 } else if (is_oat_pic == NOT_PIC) {
488 LOG(ERROR) << "patchoat cannot be used on non-PIC oat file: " << input_oat_filename;
489 return false;
490 }
491
492 CHECK(is_oat_pic == PIC);
493
494 std::string output_vdex_filename =
495 ImageHeader::GetVdexLocationFromImageLocation(output_image_filename);
496 std::string output_oat_filename =
497 ImageHeader::GetOatLocationFromImageLocation(output_image_filename);
498
499 return SymlinkFile(input_oat_filename, output_oat_filename) &&
500 SymlinkFile(input_vdex_filename, output_vdex_filename);
501}
502
Andreas Gampe6eb6a392016-02-10 20:18:37 -0800503bool PatchOat::Patch(const std::string& image_location,
504 off_t delta,
Alex Klyubin3856af02017-10-23 13:53:13 -0700505 const std::string& output_image_directory,
506 const std::string& output_image_relocation_directory,
Andreas Gampe6eb6a392016-02-10 20:18:37 -0800507 InstructionSet isa,
508 TimingLogger* timings) {
Alex Klyubin3856af02017-10-23 13:53:13 -0700509 bool output_image = !output_image_directory.empty();
510 bool output_image_relocation = !output_image_relocation_directory.empty();
511 if ((!output_image) && (!output_image_relocation)) {
512 // Nothing to do
513 return true;
514 }
515 if ((output_image_relocation) && (delta == 0)) {
516 LOG(ERROR) << "Cannot output image relocation information when requested relocation delta is 0";
517 return false;
518 }
519
Alex Light53cb16b2014-06-12 11:26:29 -0700520 CHECK(Runtime::Current() == nullptr);
Alex Light53cb16b2014-06-12 11:26:29 -0700521 CHECK(!image_location.empty()) << "image file must have a filename.";
522
Alex Lighteefbe392014-07-08 09:53:18 -0700523 TimingLogger::ScopedTiming t("Runtime Setup", timings);
Alex Light53cb16b2014-06-12 11:26:29 -0700524
Vladimir Marko33bff252017-11-01 14:35:42 +0000525 CHECK_NE(isa, InstructionSet::kNone);
Igor Murashkin46774762014-10-22 11:37:02 -0700526
Alex Light53cb16b2014-06-12 11:26:29 -0700527 // Set up the runtime
Andreas Gampec7d25082018-03-09 12:06:45 -0800528 PatchoatRuntimeOptionsHolder options_holder(image_location, isa);
529 if (!Runtime::Create(options_holder.GetRuntimeOptions(), false)) {
Alex Light53cb16b2014-06-12 11:26:29 -0700530 LOG(ERROR) << "Unable to initialize runtime";
531 return false;
532 }
Andreas Gampeb8cc1752017-04-26 21:28:50 -0700533 std::unique_ptr<Runtime> runtime(Runtime::Current());
534
Alex Light53cb16b2014-06-12 11:26:29 -0700535 // Runtime::Create acquired the mutator_lock_ that is normally given away when we Runtime::Start,
536 // give it away now and then switch to a more manageable ScopedObjectAccess.
537 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
538 ScopedObjectAccess soa(Thread::Current());
539
Jeff Haodcdc85b2015-12-04 14:06:18 -0800540 std::vector<gc::space::ImageSpace*> spaces = Runtime::Current()->GetHeap()->GetBootImageSpaces();
Jeff Haodcdc85b2015-12-04 14:06:18 -0800541 std::map<gc::space::ImageSpace*, std::unique_ptr<MemMap>> space_to_memmap_map;
Alex Light53cb16b2014-06-12 11:26:29 -0700542
Jeff Haodcdc85b2015-12-04 14:06:18 -0800543 for (size_t i = 0; i < spaces.size(); ++i) {
Chris Morinae6832f2018-02-09 19:12:35 -0800544 t.NewTiming("Image Patching setup");
Jeff Haodcdc85b2015-12-04 14:06:18 -0800545 gc::space::ImageSpace* space = spaces[i];
546 std::string input_image_filename = space->GetImageFilename();
547 std::unique_ptr<File> input_image(OS::OpenFileForReading(input_image_filename.c_str()));
548 if (input_image.get() == nullptr) {
549 LOG(ERROR) << "Unable to open input image file at " << input_image_filename;
Igor Murashkin46774762014-10-22 11:37:02 -0700550 return false;
551 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800552
553 int64_t image_len = input_image->GetLength();
554 if (image_len < 0) {
555 LOG(ERROR) << "Error while getting image length";
556 return false;
557 }
558 ImageHeader image_header;
559 if (sizeof(image_header) != input_image->Read(reinterpret_cast<char*>(&image_header),
560 sizeof(image_header), 0)) {
561 LOG(ERROR) << "Unable to read image header from image file " << input_image->GetPath();
562 }
563
564 /*bool is_image_pic = */IsImagePic(image_header, input_image->GetPath());
565 // Nothing special to do right now since the image always needs to get patched.
566 // Perhaps in some far-off future we may have images with relative addresses that are true-PIC.
567
568 // Create the map where we will write the image patches to.
569 std::string error_msg;
570 std::unique_ptr<MemMap> image(MemMap::MapFile(image_len,
571 PROT_READ | PROT_WRITE,
572 MAP_PRIVATE,
573 input_image->Fd(),
574 0,
575 /*low_4gb*/false,
576 input_image->GetPath().c_str(),
577 &error_msg));
578 if (image.get() == nullptr) {
579 LOG(ERROR) << "Unable to map image file " << input_image->GetPath() << " : " << error_msg;
580 return false;
581 }
Chris Morinae6832f2018-02-09 19:12:35 -0800582
583
Jeff Haodcdc85b2015-12-04 14:06:18 -0800584 space_to_memmap_map.emplace(space, std::move(image));
Chris Morinae6832f2018-02-09 19:12:35 -0800585 PatchOat p = PatchOat(isa,
Vladimir Marko35d5b8a2018-07-03 09:18:32 +0100586 space_to_memmap_map[space].get(),
Chris Morinae6832f2018-02-09 19:12:35 -0800587 space->GetLiveBitmap(),
588 space->GetMemMap(),
589 delta,
590 &space_to_memmap_map,
591 timings);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800592
Richard Uhler4bc11d02017-02-01 09:53:54 +0000593 t.NewTiming("Patching image");
Jeff Haodcdc85b2015-12-04 14:06:18 -0800594 if (!p.PatchImage(i == 0)) {
595 LOG(ERROR) << "Failed to patch image file " << input_image_filename;
596 return false;
597 }
Alex Light53cb16b2014-06-12 11:26:29 -0700598
Alex Klyubin3856af02017-10-23 13:53:13 -0700599 // Write the patched image spaces.
Chris Morinae6832f2018-02-09 19:12:35 -0800600 if (output_image) {
601 std::string output_image_filename;
602 if (!GetDalvikCacheFilename(space->GetImageLocation().c_str(),
603 output_image_directory.c_str(),
604 &output_image_filename,
605 &error_msg)) {
606 LOG(ERROR) << "Failed to find relocated image file name: " << error_msg;
607 return false;
608 }
609
610 if (!CreateVdexAndOatSymlinks(input_image_filename, output_image_filename))
611 return false;
Jeff Haodcdc85b2015-12-04 14:06:18 -0800612
Alex Klyubin3856af02017-10-23 13:53:13 -0700613 t.NewTiming("Writing image");
Alex Klyubin3856af02017-10-23 13:53:13 -0700614 std::unique_ptr<File> output_image_file(CreateOrOpen(output_image_filename.c_str()));
615 if (output_image_file.get() == nullptr) {
616 LOG(ERROR) << "Failed to open output image file at " << output_image_filename;
617 return false;
618 }
619
Alex Klyubin3856af02017-10-23 13:53:13 -0700620 bool success = p.WriteImage(output_image_file.get());
621 success = FinishFile(output_image_file.get(), success);
622 if (!success) {
623 return false;
624 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800625 }
626
Chris Morinae6832f2018-02-09 19:12:35 -0800627 if (output_image_relocation) {
Alex Klyubin3856af02017-10-23 13:53:13 -0700628 t.NewTiming("Writing image relocation");
629 std::string original_image_filename(space->GetImageLocation() + ".rel");
630 std::string image_relocation_filename =
631 output_image_relocation_directory
632 + (android::base::StartsWith(original_image_filename, "/") ? "" : "/")
633 + original_image_filename.substr(original_image_filename.find_last_of("/"));
Chris Morinae6832f2018-02-09 19:12:35 -0800634 int64_t input_image_size = input_image->GetLength();
Alex Klyubin3856af02017-10-23 13:53:13 -0700635 if (input_image_size < 0) {
636 LOG(ERROR) << "Error while getting input image size";
637 return false;
638 }
Alex Klyubin3856af02017-10-23 13:53:13 -0700639 std::unique_ptr<MemMap> original(MemMap::MapFile(input_image_size,
640 PROT_READ,
641 MAP_PRIVATE,
Chris Morinae6832f2018-02-09 19:12:35 -0800642 input_image->Fd(),
Alex Klyubin3856af02017-10-23 13:53:13 -0700643 0,
644 /*low_4gb*/false,
Chris Morinae6832f2018-02-09 19:12:35 -0800645 input_image->GetPath().c_str(),
Alex Klyubin3856af02017-10-23 13:53:13 -0700646 &error_msg));
647 if (original.get() == nullptr) {
Chris Morinae6832f2018-02-09 19:12:35 -0800648 LOG(ERROR) << "Unable to map image file " << input_image->GetPath() << " : " << error_msg;
Alex Klyubin3856af02017-10-23 13:53:13 -0700649 return false;
650 }
651
Alex Klyubin3856af02017-10-23 13:53:13 -0700652 const MemMap* relocated = p.image_;
653
654 if (!WriteRelFile(*original, *relocated, image_relocation_filename, &error_msg)) {
655 LOG(ERROR) << "Failed to create image relocation file " << image_relocation_filename
656 << ": " << error_msg;
657 return false;
658 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800659 }
Alex Light53cb16b2014-06-12 11:26:29 -0700660 }
Andreas Gampeb8cc1752017-04-26 21:28:50 -0700661
Roland Levillain05e34f42018-05-24 13:19:05 +0000662 if (!kIsDebugBuild && !(kRunningOnMemoryTool && kMemoryToolDetectsLeaks)) {
Andreas Gampeb8cc1752017-04-26 21:28:50 -0700663 // We want to just exit on non-debug builds, not bringing the runtime down
664 // in an orderly fashion. So release the following fields.
665 runtime.release();
666 }
667
Alex Light53cb16b2014-06-12 11:26:29 -0700668 return true;
669}
670
Chris Morin754b7572018-01-19 18:04:46 -0800671bool PatchOat::Verify(const std::string& image_location,
672 const std::string& output_image_directory,
673 InstructionSet isa,
674 TimingLogger* timings) {
675 if (image_location.empty()) {
676 LOG(ERROR) << "Original image file not provided";
677 return false;
678 }
679 if (output_image_directory.empty()) {
680 LOG(ERROR) << "Relocated image directory not provided";
681 return false;
682 }
683
684 TimingLogger::ScopedTiming t("Runtime Setup", timings);
685
686 CHECK_NE(isa, InstructionSet::kNone);
Chris Morin754b7572018-01-19 18:04:46 -0800687
688 // Set up the runtime
Andreas Gampec7d25082018-03-09 12:06:45 -0800689 PatchoatRuntimeOptionsHolder options_holder(image_location, isa);
690 if (!Runtime::Create(options_holder.GetRuntimeOptions(), false)) {
Chris Morin754b7572018-01-19 18:04:46 -0800691 LOG(ERROR) << "Unable to initialize runtime";
692 return false;
693 }
694 std::unique_ptr<Runtime> runtime(Runtime::Current());
695
696 // Runtime::Create acquired the mutator_lock_ that is normally given away when we Runtime::Start,
697 // give it away now and then switch to a more manageable ScopedObjectAccess.
698 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
699 ScopedObjectAccess soa(Thread::Current());
700
701 t.NewTiming("Image Verification setup");
702 std::vector<gc::space::ImageSpace*> spaces = Runtime::Current()->GetHeap()->GetBootImageSpaces();
703
704 // TODO: Check that no other .rel files exist in the original dir
705
706 bool success = true;
707 std::string image_location_dir = android::base::Dirname(image_location);
708 for (size_t i = 0; i < spaces.size(); ++i) {
709 gc::space::ImageSpace* space = spaces[i];
Chris Morin754b7572018-01-19 18:04:46 -0800710
711 std::string relocated_image_filename;
712 std::string error_msg;
Chris Morinae6832f2018-02-09 19:12:35 -0800713 if (!GetDalvikCacheFilename(space->GetImageLocation().c_str(),
Chris Morin754b7572018-01-19 18:04:46 -0800714 output_image_directory.c_str(), &relocated_image_filename, &error_msg)) {
715 LOG(ERROR) << "Failed to find relocated image file name: " << error_msg;
716 success = false;
717 break;
718 }
719 // location: /system/framework/boot.art
720 // isa: arm64
721 // basename: boot.art
722 // original: /system/framework/arm64/boot.art
723 // relocation: /system/framework/arm64/boot.art.rel
Chris Morinae6832f2018-02-09 19:12:35 -0800724 std::string original_image_filename =
725 GetSystemImageFilename(space->GetImageLocation().c_str(), isa);
Chris Morin754b7572018-01-19 18:04:46 -0800726
727 if (!CheckImageIdenticalToOriginalExceptForRelocation(
728 relocated_image_filename, original_image_filename, &error_msg)) {
729 LOG(ERROR) << error_msg;
730 success = false;
731 break;
732 }
Chris Morinae6832f2018-02-09 19:12:35 -0800733
734 if (!VerifyVdexAndOatSymlinks(original_image_filename, relocated_image_filename)) {
735 LOG(ERROR) << "Verification of vdex and oat symlinks for "
736 << space->GetImageLocation() << " failed.";
737 success = false;
738 break;
739 }
Chris Morin754b7572018-01-19 18:04:46 -0800740 }
741
Roland Levillain05e34f42018-05-24 13:19:05 +0000742 if (!kIsDebugBuild && !(kRunningOnMemoryTool && kMemoryToolDetectsLeaks)) {
Chris Morin754b7572018-01-19 18:04:46 -0800743 // We want to just exit on non-debug builds, not bringing the runtime down
744 // in an orderly fashion. So release the following fields.
745 runtime.release();
746 }
747
748 return success;
749}
750
Alex Light53cb16b2014-06-12 11:26:29 -0700751bool PatchOat::WriteImage(File* out) {
Greg Kaiser4eb17792018-04-06 14:26:23 -0700752 CHECK(out != nullptr);
Alex Lighteefbe392014-07-08 09:53:18 -0700753 TimingLogger::ScopedTiming t("Writing image File", timings_);
Alex Lighta59dd802014-07-02 16:28:08 -0700754 std::string error_msg;
755
Narayan Kamatha3d27eb2017-05-11 13:50:59 +0100756 // No error checking here, this is best effort. The locking may or may not
757 // succeed and we don't really care either way.
758 ScopedFlock img_flock = LockedFile::DupOf(out->Fd(), out->GetPath(),
759 true /* read_only_mode */, &error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -0700760
Alex Light53cb16b2014-06-12 11:26:29 -0700761 CHECK(image_ != nullptr);
Alex Light53cb16b2014-06-12 11:26:29 -0700762 size_t expect = image_->Size();
763 if (out->WriteFully(reinterpret_cast<char*>(image_->Begin()), expect) &&
764 out->SetLength(expect) == 0) {
765 return true;
766 } else {
767 LOG(ERROR) << "Writing to image file " << out->GetPath() << " failed.";
768 return false;
769 }
770}
771
Igor Murashkin46774762014-10-22 11:37:02 -0700772bool PatchOat::IsImagePic(const ImageHeader& image_header, const std::string& image_path) {
773 if (!image_header.CompilePic()) {
774 if (kIsDebugBuild) {
775 LOG(INFO) << "image at location " << image_path << " was *not* compiled pic";
776 }
777 return false;
778 }
779
780 if (kIsDebugBuild) {
781 LOG(INFO) << "image at location " << image_path << " was compiled PIC";
782 }
783
784 return true;
785}
786
787PatchOat::MaybePic PatchOat::IsOatPic(const ElfFile* oat_in) {
788 if (oat_in == nullptr) {
789 LOG(ERROR) << "No ELF input oat fie available";
790 return ERROR_OAT_FILE;
791 }
792
Brian Carlstromf5b0f2c2016-10-14 01:04:26 -0700793 const std::string& file_path = oat_in->GetFilePath();
Igor Murashkin46774762014-10-22 11:37:02 -0700794
795 const OatHeader* oat_header = GetOatHeader(oat_in);
796 if (oat_header == nullptr) {
797 LOG(ERROR) << "Failed to find oat header in oat file " << file_path;
798 return ERROR_OAT_FILE;
799 }
800
801 if (!oat_header->IsValid()) {
802 LOG(ERROR) << "Elf file " << file_path << " has an invalid oat header";
803 return ERROR_OAT_FILE;
804 }
805
806 bool is_pic = oat_header->IsPic();
807 if (kIsDebugBuild) {
808 LOG(INFO) << "Oat file at " << file_path << " is " << (is_pic ? "PIC" : "not pic");
809 }
810
811 return is_pic ? PIC : NOT_PIC;
812}
813
Vladimir Markoad06b982016-11-17 16:38:59 +0000814class PatchOat::PatchOatArtFieldVisitor : public ArtFieldVisitor {
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700815 public:
816 explicit PatchOatArtFieldVisitor(PatchOat* patch_oat) : patch_oat_(patch_oat) {}
817
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700818 void Visit(ArtField* field) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700819 ArtField* const dest = patch_oat_->RelocatedCopyOf(field);
Mathieu Chartier3398c782016-09-30 10:27:43 -0700820 dest->SetDeclaringClass(
Mathieu Chartier1cc62e42016-10-03 18:01:28 -0700821 patch_oat_->RelocatedAddressOfPointer(field->GetDeclaringClass().Ptr()));
Mathieu Chartiere401d142015-04-22 13:56:20 -0700822 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700823
824 private:
825 PatchOat* const patch_oat_;
826};
827
828void PatchOat::PatchArtFields(const ImageHeader* image_header) {
829 PatchOatArtFieldVisitor visitor(this);
Mathieu Chartiere42888f2016-04-14 10:49:19 -0700830 image_header->VisitPackedArtFields(&visitor, heap_->Begin());
Mathieu Chartiere401d142015-04-22 13:56:20 -0700831}
832
Vladimir Markoad06b982016-11-17 16:38:59 +0000833class PatchOat::PatchOatArtMethodVisitor : public ArtMethodVisitor {
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700834 public:
835 explicit PatchOatArtMethodVisitor(PatchOat* patch_oat) : patch_oat_(patch_oat) {}
836
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700837 void Visit(ArtMethod* method) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700838 ArtMethod* const dest = patch_oat_->RelocatedCopyOf(method);
839 patch_oat_->FixupMethod(method, dest);
840 }
841
842 private:
843 PatchOat* const patch_oat_;
844};
845
Mathieu Chartiere401d142015-04-22 13:56:20 -0700846void PatchOat::PatchArtMethods(const ImageHeader* image_header) {
Andreas Gampe542451c2016-07-26 09:02:02 -0700847 const PointerSize pointer_size = InstructionSetPointerSize(isa_);
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700848 PatchOatArtMethodVisitor visitor(this);
Mathieu Chartiere42888f2016-04-14 10:49:19 -0700849 image_header->VisitPackedArtMethods(&visitor, heap_->Begin(), pointer_size);
850}
851
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +0000852void PatchOat::PatchImTables(const ImageHeader* image_header) {
Andreas Gampe542451c2016-07-26 09:02:02 -0700853 const PointerSize pointer_size = InstructionSetPointerSize(isa_);
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +0000854 // We can safely walk target image since the conflict tables are independent.
855 image_header->VisitPackedImTables(
856 [this](ArtMethod* method) {
857 return RelocatedAddressOfPointer(method);
858 },
859 image_->Begin(),
860 pointer_size);
861}
862
Mathieu Chartiere42888f2016-04-14 10:49:19 -0700863void PatchOat::PatchImtConflictTables(const ImageHeader* image_header) {
Andreas Gampe542451c2016-07-26 09:02:02 -0700864 const PointerSize pointer_size = InstructionSetPointerSize(isa_);
Mathieu Chartiere42888f2016-04-14 10:49:19 -0700865 // We can safely walk target image since the conflict tables are independent.
866 image_header->VisitPackedImtConflictTables(
867 [this](ArtMethod* method) {
868 return RelocatedAddressOfPointer(method);
869 },
870 image_->Begin(),
871 pointer_size);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700872}
873
Vladimir Markoad06b982016-11-17 16:38:59 +0000874class PatchOat::FixupRootVisitor : public RootVisitor {
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700875 public:
876 explicit FixupRootVisitor(const PatchOat* patch_oat) : patch_oat_(patch_oat) {
877 }
878
879 void VisitRoots(mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700880 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700881 for (size_t i = 0; i < count; ++i) {
882 *roots[i] = patch_oat_->RelocatedAddressOfPointer(*roots[i]);
883 }
884 }
885
886 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots, size_t count,
887 const RootInfo& info ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700888 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700889 for (size_t i = 0; i < count; ++i) {
890 roots[i]->Assign(patch_oat_->RelocatedAddressOfPointer(roots[i]->AsMirrorPtr()));
891 }
892 }
893
894 private:
895 const PatchOat* const patch_oat_;
896};
897
898void PatchOat::PatchInternedStrings(const ImageHeader* image_header) {
Vladimir Markocd87c3e2017-09-05 13:11:57 +0100899 const auto& section = image_header->GetInternedStringsSection();
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100900 if (section.Size() == 0) {
901 return;
902 }
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700903 InternTable temp_table;
904 // Note that we require that ReadFromMemory does not make an internal copy of the elements.
905 // This also relies on visit roots not doing any verification which could fail after we update
906 // the roots to be the image addresses.
Mathieu Chartierea0831f2015-12-29 13:17:37 -0800907 temp_table.AddTableFromMemory(image_->Begin() + section.Offset());
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700908 FixupRootVisitor visitor(this);
909 temp_table.VisitRoots(&visitor, kVisitRootFlagAllRoots);
910}
911
Mathieu Chartier208a5cb2015-12-02 15:44:07 -0800912void PatchOat::PatchClassTable(const ImageHeader* image_header) {
Vladimir Markocd87c3e2017-09-05 13:11:57 +0100913 const auto& section = image_header->GetClassTableSection();
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800914 if (section.Size() == 0) {
915 return;
916 }
Mathieu Chartier208a5cb2015-12-02 15:44:07 -0800917 // Note that we require that ReadFromMemory does not make an internal copy of the elements.
918 // This also relies on visit roots not doing any verification which could fail after we update
919 // the roots to be the image addresses.
920 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
921 ClassTable temp_table;
922 temp_table.ReadFromMemory(image_->Begin() + section.Offset());
923 FixupRootVisitor visitor(this);
Mathieu Chartier58c3f6a2016-12-01 14:21:11 -0800924 temp_table.VisitRoots(UnbufferedRootVisitor(&visitor, RootInfo(kRootUnknown)));
Mathieu Chartier208a5cb2015-12-02 15:44:07 -0800925}
926
927
Vladimir Markoad06b982016-11-17 16:38:59 +0000928class PatchOat::RelocatedPointerVisitor {
Mathieu Chartier4b00d342015-11-13 10:42:08 -0800929 public:
930 explicit RelocatedPointerVisitor(PatchOat* patch_oat) : patch_oat_(patch_oat) {}
931
932 template <typename T>
Vladimir Markoca8de0a2018-07-04 11:56:08 +0100933 T* operator()(T* ptr, void** dest_addr ATTRIBUTE_UNUSED = nullptr) const {
Mathieu Chartier4b00d342015-11-13 10:42:08 -0800934 return patch_oat_->RelocatedAddressOfPointer(ptr);
935 }
936
937 private:
938 PatchOat* const patch_oat_;
939};
940
Mathieu Chartierc7853442015-03-27 14:35:38 -0700941void PatchOat::PatchDexFileArrays(mirror::ObjectArray<mirror::Object>* img_roots) {
942 auto* dex_caches = down_cast<mirror::ObjectArray<mirror::DexCache>*>(
943 img_roots->Get(ImageHeader::kDexCaches));
Andreas Gampe542451c2016-07-26 09:02:02 -0700944 const PointerSize pointer_size = InstructionSetPointerSize(isa_);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700945 for (size_t i = 0, count = dex_caches->GetLength(); i < count; ++i) {
Vladimir Marko05792b92015-08-03 11:56:49 +0100946 auto* orig_dex_cache = dex_caches->GetWithoutChecks(i);
947 auto* copy_dex_cache = RelocatedCopyOf(orig_dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +0100948 // Though the DexCache array fields are usually treated as native pointers, we set the full
949 // 64-bit values here, clearing the top 32 bits for 32-bit targets. The zero-extension is
950 // done by casting to the unsigned type uintptr_t before casting to int64_t, i.e.
951 // static_cast<int64_t>(reinterpret_cast<uintptr_t>(image_begin_ + offset))).
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -0700952 mirror::StringDexCacheType* orig_strings = orig_dex_cache->GetStrings();
953 mirror::StringDexCacheType* relocated_strings = RelocatedAddressOfPointer(orig_strings);
Vladimir Marko05792b92015-08-03 11:56:49 +0100954 copy_dex_cache->SetField64<false>(
955 mirror::DexCache::StringsOffset(),
956 static_cast<int64_t>(reinterpret_cast<uintptr_t>(relocated_strings)));
957 if (orig_strings != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -0800958 orig_dex_cache->FixupStrings(RelocatedCopyOf(orig_strings), RelocatedPointerVisitor(this));
Mathieu Chartierc7853442015-03-27 14:35:38 -0700959 }
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000960 mirror::TypeDexCacheType* orig_types = orig_dex_cache->GetResolvedTypes();
961 mirror::TypeDexCacheType* relocated_types = RelocatedAddressOfPointer(orig_types);
Vladimir Marko05792b92015-08-03 11:56:49 +0100962 copy_dex_cache->SetField64<false>(
963 mirror::DexCache::ResolvedTypesOffset(),
964 static_cast<int64_t>(reinterpret_cast<uintptr_t>(relocated_types)));
965 if (orig_types != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -0800966 orig_dex_cache->FixupResolvedTypes(RelocatedCopyOf(orig_types),
967 RelocatedPointerVisitor(this));
Vladimir Marko05792b92015-08-03 11:56:49 +0100968 }
Vladimir Marko07bfbac2017-07-06 14:55:02 +0100969 mirror::MethodDexCacheType* orig_methods = orig_dex_cache->GetResolvedMethods();
970 mirror::MethodDexCacheType* relocated_methods = RelocatedAddressOfPointer(orig_methods);
Vladimir Marko05792b92015-08-03 11:56:49 +0100971 copy_dex_cache->SetField64<false>(
972 mirror::DexCache::ResolvedMethodsOffset(),
973 static_cast<int64_t>(reinterpret_cast<uintptr_t>(relocated_methods)));
974 if (orig_methods != nullptr) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +0100975 mirror::MethodDexCacheType* copy_methods = RelocatedCopyOf(orig_methods);
Vladimir Marko05792b92015-08-03 11:56:49 +0100976 for (size_t j = 0, num = orig_dex_cache->NumResolvedMethods(); j != num; ++j) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +0100977 mirror::MethodDexCachePair orig =
978 mirror::DexCache::GetNativePairPtrSize(orig_methods, j, pointer_size);
979 mirror::MethodDexCachePair copy(RelocatedAddressOfPointer(orig.object), orig.index);
980 mirror::DexCache::SetNativePairPtrSize(copy_methods, j, copy, pointer_size);
Vladimir Marko05792b92015-08-03 11:56:49 +0100981 }
982 }
Vladimir Markof44d36c2017-03-14 14:18:46 +0000983 mirror::FieldDexCacheType* orig_fields = orig_dex_cache->GetResolvedFields();
984 mirror::FieldDexCacheType* relocated_fields = RelocatedAddressOfPointer(orig_fields);
Vladimir Marko05792b92015-08-03 11:56:49 +0100985 copy_dex_cache->SetField64<false>(
986 mirror::DexCache::ResolvedFieldsOffset(),
987 static_cast<int64_t>(reinterpret_cast<uintptr_t>(relocated_fields)));
988 if (orig_fields != nullptr) {
Vladimir Markof44d36c2017-03-14 14:18:46 +0000989 mirror::FieldDexCacheType* copy_fields = RelocatedCopyOf(orig_fields);
Vladimir Marko05792b92015-08-03 11:56:49 +0100990 for (size_t j = 0, num = orig_dex_cache->NumResolvedFields(); j != num; ++j) {
Vladimir Markof44d36c2017-03-14 14:18:46 +0000991 mirror::FieldDexCachePair orig =
992 mirror::DexCache::GetNativePairPtrSize(orig_fields, j, pointer_size);
993 mirror::FieldDexCachePair copy(RelocatedAddressOfPointer(orig.object), orig.index);
994 mirror::DexCache::SetNativePairPtrSize(copy_fields, j, copy, pointer_size);
Vladimir Marko05792b92015-08-03 11:56:49 +0100995 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700996 }
Narayan Kamath7fe56582016-10-14 18:49:12 +0100997 mirror::MethodTypeDexCacheType* orig_method_types = orig_dex_cache->GetResolvedMethodTypes();
998 mirror::MethodTypeDexCacheType* relocated_method_types =
999 RelocatedAddressOfPointer(orig_method_types);
1000 copy_dex_cache->SetField64<false>(
1001 mirror::DexCache::ResolvedMethodTypesOffset(),
1002 static_cast<int64_t>(reinterpret_cast<uintptr_t>(relocated_method_types)));
1003 if (orig_method_types != nullptr) {
1004 orig_dex_cache->FixupResolvedMethodTypes(RelocatedCopyOf(orig_method_types),
1005 RelocatedPointerVisitor(this));
1006 }
Orion Hodsonc069a302017-01-18 09:23:12 +00001007
1008 GcRoot<mirror::CallSite>* orig_call_sites = orig_dex_cache->GetResolvedCallSites();
1009 GcRoot<mirror::CallSite>* relocated_call_sites = RelocatedAddressOfPointer(orig_call_sites);
1010 copy_dex_cache->SetField64<false>(
1011 mirror::DexCache::ResolvedCallSitesOffset(),
1012 static_cast<int64_t>(reinterpret_cast<uintptr_t>(relocated_call_sites)));
1013 if (orig_call_sites != nullptr) {
1014 orig_dex_cache->FixupResolvedCallSites(RelocatedCopyOf(orig_call_sites),
1015 RelocatedPointerVisitor(this));
1016 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001017 }
1018}
1019
Jeff Haodcdc85b2015-12-04 14:06:18 -08001020bool PatchOat::PatchImage(bool primary_image) {
Alex Light53cb16b2014-06-12 11:26:29 -07001021 ImageHeader* image_header = reinterpret_cast<ImageHeader*>(image_->Begin());
1022 CHECK_GT(image_->Size(), sizeof(ImageHeader));
1023 // These are the roots from the original file.
Vladimir Markoc13fbd82018-06-04 16:16:28 +01001024 mirror::ObjectArray<mirror::Object>* img_roots = image_header->GetImageRoots().Ptr();
Alex Light53cb16b2014-06-12 11:26:29 -07001025 image_header->RelocateImage(delta_);
1026
Mathieu Chartierc7853442015-03-27 14:35:38 -07001027 PatchArtFields(image_header);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001028 PatchArtMethods(image_header);
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001029 PatchImTables(image_header);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001030 PatchImtConflictTables(image_header);
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001031 PatchInternedStrings(image_header);
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001032 PatchClassTable(image_header);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001033 // Patch dex file int/long arrays which point to ArtFields.
1034 PatchDexFileArrays(img_roots);
1035
Jeff Haodcdc85b2015-12-04 14:06:18 -08001036 if (primary_image) {
1037 VisitObject(img_roots);
1038 }
1039
Alex Light53cb16b2014-06-12 11:26:29 -07001040 if (!image_header->IsValid()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001041 LOG(ERROR) << "relocation renders image header invalid";
Alex Light53cb16b2014-06-12 11:26:29 -07001042 return false;
1043 }
1044
1045 {
Alex Lighteefbe392014-07-08 09:53:18 -07001046 TimingLogger::ScopedTiming t("Walk Bitmap", timings_);
Alex Light53cb16b2014-06-12 11:26:29 -07001047 // Walk the bitmap.
1048 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Andreas Gampe0c183382017-07-13 22:26:24 -07001049 auto visitor = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
1050 VisitObject(obj);
1051 };
1052 bitmap_->Walk(visitor);
Alex Light53cb16b2014-06-12 11:26:29 -07001053 }
1054 return true;
1055}
1056
Alex Light53cb16b2014-06-12 11:26:29 -07001057
Mathieu Chartier31e88222016-10-14 18:43:19 -07001058void PatchOat::PatchVisitor::operator() (ObjPtr<mirror::Object> obj,
1059 MemberOffset off,
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001060 bool is_static_unused ATTRIBUTE_UNUSED) const {
Alex Light53cb16b2014-06-12 11:26:29 -07001061 mirror::Object* referent = obj->GetFieldObject<mirror::Object, kVerifyNone>(off);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001062 mirror::Object* moved_object = patcher_->RelocatedAddressOfPointer(referent);
Alex Light53cb16b2014-06-12 11:26:29 -07001063 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(off, moved_object);
1064}
1065
Mathieu Chartier31e88222016-10-14 18:43:19 -07001066void PatchOat::PatchVisitor::operator() (ObjPtr<mirror::Class> cls ATTRIBUTE_UNUSED,
1067 ObjPtr<mirror::Reference> ref) const {
Alex Light53cb16b2014-06-12 11:26:29 -07001068 MemberOffset off = mirror::Reference::ReferentOffset();
1069 mirror::Object* referent = ref->GetReferent();
Mathieu Chartiera13abba2016-04-21 10:23:16 -07001070 DCHECK(referent == nullptr ||
1071 Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(referent)) << referent;
Mathieu Chartierc7853442015-03-27 14:35:38 -07001072 mirror::Object* moved_object = patcher_->RelocatedAddressOfPointer(referent);
Alex Light53cb16b2014-06-12 11:26:29 -07001073 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(off, moved_object);
1074}
1075
Andreas Gampe0c183382017-07-13 22:26:24 -07001076// Called by PatchImage.
Alex Light53cb16b2014-06-12 11:26:29 -07001077void PatchOat::VisitObject(mirror::Object* object) {
1078 mirror::Object* copy = RelocatedCopyOf(object);
1079 CHECK(copy != nullptr);
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001080 if (kUseBakerReadBarrier) {
1081 object->AssertReadBarrierState();
Alex Light53cb16b2014-06-12 11:26:29 -07001082 }
1083 PatchOat::PatchVisitor visitor(this, copy);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07001084 object->VisitReferences<kVerifyNone>(visitor, visitor);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001085 if (object->IsClass<kVerifyNone>()) {
Andreas Gampe542451c2016-07-26 09:02:02 -07001086 const PointerSize pointer_size = InstructionSetPointerSize(isa_);
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001087 mirror::Class* klass = object->AsClass();
1088 mirror::Class* copy_klass = down_cast<mirror::Class*>(copy);
1089 RelocatedPointerVisitor native_visitor(this);
1090 klass->FixupNativePointers(copy_klass, pointer_size, native_visitor);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001091 auto* vtable = klass->GetVTable();
1092 if (vtable != nullptr) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001093 vtable->Fixup(RelocatedCopyOfFollowImages(vtable), pointer_size, native_visitor);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001094 }
Mathieu Chartier6beced42016-11-15 15:51:31 -08001095 mirror::IfTable* iftable = klass->GetIfTable();
1096 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
1097 if (iftable->GetMethodArrayCount(i) > 0) {
1098 auto* method_array = iftable->GetMethodArray(i);
1099 CHECK(method_array != nullptr);
1100 method_array->Fixup(RelocatedCopyOfFollowImages(method_array),
1101 pointer_size,
1102 native_visitor);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001103 }
1104 }
Vladimir Marko679730e2018-05-25 15:06:48 +01001105 } else if (object->GetClass() == GetClassRoot<mirror::Method>() ||
1106 object->GetClass() == GetClassRoot<mirror::Constructor>()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001107 // Need to go update the ArtMethod.
Neil Fuller0e844392016-09-08 13:43:31 +01001108 auto* dest = down_cast<mirror::Executable*>(copy);
1109 auto* src = down_cast<mirror::Executable*>(object);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001110 dest->SetArtMethod(RelocatedAddressOfPointer(src->GetArtMethod()));
Alex Light53cb16b2014-06-12 11:26:29 -07001111 }
1112}
1113
Mathieu Chartiere401d142015-04-22 13:56:20 -07001114void PatchOat::FixupMethod(ArtMethod* object, ArtMethod* copy) {
Andreas Gampe542451c2016-07-26 09:02:02 -07001115 const PointerSize pointer_size = InstructionSetPointerSize(isa_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001116 copy->CopyFrom(object, pointer_size);
Alex Light53cb16b2014-06-12 11:26:29 -07001117 // Just update the entry points if it looks like we should.
Alex Lighteefbe392014-07-08 09:53:18 -07001118 // TODO: sanity check all the pointers' values
Vladimir Markod93e3742018-07-18 10:58:13 +01001119 copy->SetDeclaringClass(RelocatedAddressOfPointer(object->GetDeclaringClass().Ptr()));
Mathieu Chartiere401d142015-04-22 13:56:20 -07001120 copy->SetEntryPointFromQuickCompiledCodePtrSize(RelocatedAddressOfPointer(
1121 object->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size)), pointer_size);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001122 // No special handling for IMT conflict table since all pointers are moved by the same offset.
Andreas Gampe75f08852016-07-19 08:06:07 -07001123 copy->SetDataPtrSize(RelocatedAddressOfPointer(
1124 object->GetDataPtrSize(pointer_size)), pointer_size);
Alex Light53cb16b2014-06-12 11:26:29 -07001125}
1126
Alex Light53cb16b2014-06-12 11:26:29 -07001127static int orig_argc;
1128static char** orig_argv;
1129
1130static std::string CommandLine() {
1131 std::vector<std::string> command;
1132 for (int i = 0; i < orig_argc; ++i) {
1133 command.push_back(orig_argv[i]);
1134 }
Andreas Gampe9186ced2016-12-12 14:28:21 -08001135 return android::base::Join(command, ' ');
Alex Light53cb16b2014-06-12 11:26:29 -07001136}
1137
1138static void UsageErrorV(const char* fmt, va_list ap) {
1139 std::string error;
Andreas Gampe46ee31b2016-12-14 10:11:49 -08001140 android::base::StringAppendV(&error, fmt, ap);
Alex Light53cb16b2014-06-12 11:26:29 -07001141 LOG(ERROR) << error;
1142}
1143
1144static void UsageError(const char* fmt, ...) {
1145 va_list ap;
1146 va_start(ap, fmt);
1147 UsageErrorV(fmt, ap);
1148 va_end(ap);
1149}
1150
Andreas Gampe794ad762015-02-23 08:12:24 -08001151NO_RETURN static void Usage(const char *fmt, ...) {
Alex Light53cb16b2014-06-12 11:26:29 -07001152 va_list ap;
1153 va_start(ap, fmt);
1154 UsageErrorV(fmt, ap);
1155 va_end(ap);
1156
1157 UsageError("Command: %s", CommandLine().c_str());
1158 UsageError("Usage: patchoat [options]...");
1159 UsageError("");
1160 UsageError(" --instruction-set=<isa>: Specifies the instruction set the patched code is");
Richard Uhler4bc11d02017-02-01 09:53:54 +00001161 UsageError(" compiled for (required).");
Alex Light53cb16b2014-06-12 11:26:29 -07001162 UsageError("");
1163 UsageError(" --input-image-location=<file.art>: Specifies the 'location' of the image file to");
Richard Uhler4bc11d02017-02-01 09:53:54 +00001164 UsageError(" be patched.");
Alex Light53cb16b2014-06-12 11:26:29 -07001165 UsageError("");
Chris Morin88c6d262018-02-13 15:26:21 -08001166 UsageError(" --output-image-directory=<dir>: Specifies the directory to write the patched");
1167 UsageError(" image file(s) to.");
Alex Light53cb16b2014-06-12 11:26:29 -07001168 UsageError("");
Chris Morin88c6d262018-02-13 15:26:21 -08001169 UsageError(" --output-image-relocation-directory=<dir>: Specifies the directory to write");
Alex Klyubin3856af02017-10-23 13:53:13 -07001170 UsageError(" the image relocation information to.");
1171 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -07001172 UsageError(" --base-offset-delta=<delta>: Specify the amount to change the old base-offset by.");
1173 UsageError(" This value may be negative.");
1174 UsageError("");
Chris Morin754b7572018-01-19 18:04:46 -08001175 UsageError(" --verify: Verify an existing patched file instead of creating one.");
1176 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -07001177 UsageError(" --dump-timings: dump out patch timing information");
1178 UsageError("");
1179 UsageError(" --no-dump-timings: do not dump out patch timing information");
1180 UsageError("");
1181
1182 exit(EXIT_FAILURE);
1183}
1184
Chris Morin754b7572018-01-19 18:04:46 -08001185static int patchoat_patch_image(TimingLogger& timings,
1186 InstructionSet isa,
1187 const std::string& input_image_location,
1188 const std::string& output_image_directory,
Chris Morin88c6d262018-02-13 15:26:21 -08001189 const std::string& output_image_relocation_directory,
Chris Morin754b7572018-01-19 18:04:46 -08001190 off_t base_delta,
1191 bool base_delta_set,
1192 bool debug) {
Andreas Gampe6eb6a392016-02-10 20:18:37 -08001193 CHECK(!input_image_location.empty());
Chris Morin88c6d262018-02-13 15:26:21 -08001194 if ((output_image_directory.empty()) && (output_image_relocation_directory.empty())) {
1195 Usage("Image patching requires --output-image-directory or --output-image-relocation-directory");
Andreas Gampe6eb6a392016-02-10 20:18:37 -08001196 }
1197
1198 if (!base_delta_set) {
1199 Usage("Must supply a desired new offset or delta.");
1200 }
1201
1202 if (!IsAligned<kPageSize>(base_delta)) {
1203 Usage("Base offset/delta must be aligned to a pagesize (0x%08x) boundary.", kPageSize);
1204 }
1205
1206 if (debug) {
1207 LOG(INFO) << "moving offset by " << base_delta
1208 << " (0x" << std::hex << base_delta << ") bytes or "
1209 << std::dec << (base_delta/kPageSize) << " pages.";
1210 }
1211
1212 TimingLogger::ScopedTiming pt("patch image and oat", &timings);
1213
Alex Klyubin3856af02017-10-23 13:53:13 -07001214 bool ret =
1215 PatchOat::Patch(
1216 input_image_location,
1217 base_delta,
1218 output_image_directory,
1219 output_image_relocation_directory,
1220 isa,
1221 &timings);
Andreas Gampe6eb6a392016-02-10 20:18:37 -08001222
1223 if (kIsDebugBuild) {
1224 LOG(INFO) << "Exiting with return ... " << ret;
1225 }
1226 return ret ? EXIT_SUCCESS : EXIT_FAILURE;
1227}
1228
Chris Morin754b7572018-01-19 18:04:46 -08001229static int patchoat_verify_image(TimingLogger& timings,
1230 InstructionSet isa,
1231 const std::string& input_image_location,
1232 const std::string& output_image_directory) {
1233 CHECK(!input_image_location.empty());
1234 TimingLogger::ScopedTiming pt("verify image and oat", &timings);
1235
1236 bool ret =
1237 PatchOat::Verify(
1238 input_image_location,
1239 output_image_directory,
1240 isa,
1241 &timings);
1242
1243 if (kIsDebugBuild) {
1244 LOG(INFO) << "Exiting with return ... " << ret;
1245 }
1246 return ret ? EXIT_SUCCESS : EXIT_FAILURE;
1247}
1248
Alex Lighteefbe392014-07-08 09:53:18 -07001249static int patchoat(int argc, char **argv) {
David Sehrc431b9d2018-03-02 12:01:51 -08001250 Locks::Init();
Andreas Gampe51d80cc2017-06-21 21:05:13 -07001251 InitLogging(argv, Runtime::Abort);
Mathieu Chartier6e88ef62014-10-14 15:01:24 -07001252 MemMap::Init();
Alex Light53cb16b2014-06-12 11:26:29 -07001253 const bool debug = kIsDebugBuild;
1254 orig_argc = argc;
1255 orig_argv = argv;
1256 TimingLogger timings("patcher", false, false);
1257
Alex Light53cb16b2014-06-12 11:26:29 -07001258 // Skip over the command name.
1259 argv++;
1260 argc--;
1261
1262 if (argc == 0) {
1263 Usage("No arguments specified");
1264 }
1265
1266 timings.StartTiming("Patchoat");
1267
1268 // cmd line args
1269 bool isa_set = false;
Vladimir Marko33bff252017-11-01 14:35:42 +00001270 InstructionSet isa = InstructionSet::kNone;
Alex Light53cb16b2014-06-12 11:26:29 -07001271 std::string input_image_location;
Chris Morin88c6d262018-02-13 15:26:21 -08001272 std::string output_image_directory;
1273 std::string output_image_relocation_directory;
Alex Light53cb16b2014-06-12 11:26:29 -07001274 off_t base_delta = 0;
1275 bool base_delta_set = false;
Alex Light53cb16b2014-06-12 11:26:29 -07001276 bool dump_timings = kIsDebugBuild;
Chris Morin754b7572018-01-19 18:04:46 -08001277 bool verify = false;
Alex Light53cb16b2014-06-12 11:26:29 -07001278
Ian Rogersd4c4d952014-10-16 20:31:53 -07001279 for (int i = 0; i < argc; ++i) {
Alex Light53cb16b2014-06-12 11:26:29 -07001280 const StringPiece option(argv[i]);
1281 const bool log_options = false;
1282 if (log_options) {
1283 LOG(INFO) << "patchoat: option[" << i << "]=" << argv[i];
1284 }
Alex Light53cb16b2014-06-12 11:26:29 -07001285 if (option.starts_with("--instruction-set=")) {
1286 isa_set = true;
1287 const char* isa_str = option.substr(strlen("--instruction-set=")).data();
Andreas Gampe20c89302014-08-19 17:28:06 -07001288 isa = GetInstructionSetFromString(isa_str);
Vladimir Marko33bff252017-11-01 14:35:42 +00001289 if (isa == InstructionSet::kNone) {
Andreas Gampe20c89302014-08-19 17:28:06 -07001290 Usage("Unknown or invalid instruction set %s", isa_str);
Alex Light53cb16b2014-06-12 11:26:29 -07001291 }
Alex Light53cb16b2014-06-12 11:26:29 -07001292 } else if (option.starts_with("--input-image-location=")) {
1293 input_image_location = option.substr(strlen("--input-image-location=")).data();
Chris Morin88c6d262018-02-13 15:26:21 -08001294 } else if (option.starts_with("--output-image-directory=")) {
1295 output_image_directory = option.substr(strlen("--output-image-directory=")).data();
1296 } else if (option.starts_with("--output-image-relocation-directory=")) {
1297 output_image_relocation_directory =
1298 option.substr(strlen("--output-image-relocation-directory=")).data();
Alex Light53cb16b2014-06-12 11:26:29 -07001299 } else if (option.starts_with("--base-offset-delta=")) {
1300 const char* base_delta_str = option.substr(strlen("--base-offset-delta=")).data();
1301 base_delta_set = true;
1302 if (!ParseInt(base_delta_str, &base_delta)) {
1303 Usage("Failed to parse --base-offset-delta argument '%s' as an off_t", base_delta_str);
1304 }
Alex Light53cb16b2014-06-12 11:26:29 -07001305 } else if (option == "--dump-timings") {
1306 dump_timings = true;
1307 } else if (option == "--no-dump-timings") {
1308 dump_timings = false;
Chris Morin754b7572018-01-19 18:04:46 -08001309 } else if (option == "--verify") {
1310 verify = true;
Alex Light53cb16b2014-06-12 11:26:29 -07001311 } else {
1312 Usage("Unknown argument %s", option.data());
1313 }
1314 }
1315
Andreas Gampe6eb6a392016-02-10 20:18:37 -08001316 // The instruction set is mandatory. This simplifies things...
1317 if (!isa_set) {
1318 Usage("Instruction set must be set.");
Alex Light53cb16b2014-06-12 11:26:29 -07001319 }
1320
Chris Morin754b7572018-01-19 18:04:46 -08001321 int ret;
1322 if (verify) {
1323 ret = patchoat_verify_image(timings,
1324 isa,
1325 input_image_location,
1326 output_image_directory);
1327 } else {
1328 ret = patchoat_patch_image(timings,
1329 isa,
1330 input_image_location,
1331 output_image_directory,
Chris Morin88c6d262018-02-13 15:26:21 -08001332 output_image_relocation_directory,
Chris Morin754b7572018-01-19 18:04:46 -08001333 base_delta,
1334 base_delta_set,
1335 debug);
1336 }
Alex Light53cb16b2014-06-12 11:26:29 -07001337
Andreas Gampe6eb6a392016-02-10 20:18:37 -08001338 timings.EndTiming();
1339 if (dump_timings) {
1340 LOG(INFO) << Dumpable<TimingLogger>(timings);
Alex Light53cb16b2014-06-12 11:26:29 -07001341 }
1342
Andreas Gampe6eb6a392016-02-10 20:18:37 -08001343 return ret;
Alex Light53cb16b2014-06-12 11:26:29 -07001344}
1345
1346} // namespace art
1347
1348int main(int argc, char **argv) {
1349 return art::patchoat(argc, argv);
1350}