blob: 3df640902a43326e75f2d467967b58f1d41b39c2 [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"
Ian Rogersc7dd2952014-10-21 23:31:19 -070034#include "base/dumpable.h"
Chris Morin754b7572018-01-19 18:04:46 -080035#include "base/file_utils.h"
David Sehr67bf42e2018-02-26 16:43:04 -080036#include "base/leb128.h"
Andreas Gampe170331f2017-12-07 18:41:03 -080037#include "base/logging.h" // For InitLogging.
David Sehrc431b9d2018-03-02 12:01:51 -080038#include "base/mutex.h"
Andreas Gampeb8cc1752017-04-26 21:28:50 -070039#include "base/memory_tool.h"
David Sehrc431b9d2018-03-02 12:01:51 -080040#include "base/os.h"
Alex Lighta59dd802014-07-02 16:28:08 -070041#include "base/scoped_flock.h"
Alex Light53cb16b2014-06-12 11:26:29 -070042#include "base/stringpiece.h"
Ian Rogersd4c4d952014-10-16 20:31:53 -070043#include "base/unix_file/fd_file.h"
David Brazdil7b49e6c2016-09-01 11:06:18 +010044#include "base/unix_file/random_access_file_utils.h"
David Sehrc431b9d2018-03-02 12:01:51 -080045#include "base/utils.h"
Alex Light53cb16b2014-06-12 11:26:29 -070046#include "elf_file.h"
Tong Shen62d1ca32014-09-03 17:24:56 -070047#include "elf_file_impl.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070048#include "elf_utils.h"
Ian Rogerse63db272014-07-15 15:36:11 -070049#include "gc/space/image_space.h"
Mathieu Chartier4a26f172016-01-26 14:26:18 -080050#include "image-inl.h"
Andreas Gampeb2d18fa2017-06-06 20:46:10 -070051#include "intern_table.h"
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -070052#include "mirror/dex_cache.h"
Neil Fuller0e844392016-09-08 13:43:31 +010053#include "mirror/executable.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070054#include "mirror/method.h"
Alex Light53cb16b2014-06-12 11:26:29 -070055#include "mirror/object-inl.h"
Andreas Gampec6ea7d02017-02-01 16:46:28 -080056#include "mirror/object-refvisitor-inl.h"
Alex Light53cb16b2014-06-12 11:26:29 -070057#include "mirror/reference.h"
58#include "noop_compiler_callbacks.h"
59#include "offsets.h"
Alex Light53cb16b2014-06-12 11:26:29 -070060#include "runtime.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070061#include "scoped_thread_state_change-inl.h"
Alex Light53cb16b2014-06-12 11:26:29 -070062#include "thread.h"
Alex Light53cb16b2014-06-12 11:26:29 -070063
64namespace art {
65
Alex Klyubin3856af02017-10-23 13:53:13 -070066using android::base::StringPrintf;
67
Alex Light0eb76d22015-08-11 18:03:47 -070068static const OatHeader* GetOatHeader(const ElfFile* elf_file) {
69 uint64_t off = 0;
70 if (!elf_file->GetSectionOffsetAndSize(".rodata", &off, nullptr)) {
71 return nullptr;
72 }
73
74 OatHeader* oat_header = reinterpret_cast<OatHeader*>(elf_file->Begin() + off);
75 return oat_header;
76}
77
Richard Uhler4bc11d02017-02-01 09:53:54 +000078static File* CreateOrOpen(const char* name) {
Jeff Haodcdc85b2015-12-04 14:06:18 -080079 if (OS::FileExists(name)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -080080 return OS::OpenFileReadWrite(name);
81 } else {
Jeff Haodcdc85b2015-12-04 14:06:18 -080082 std::unique_ptr<File> f(OS::CreateEmptyFile(name));
83 if (f.get() != nullptr) {
84 if (fchmod(f->Fd(), 0644) != 0) {
85 PLOG(ERROR) << "Unable to make " << name << " world readable";
Dimitry Ivanov7a1c0142016-03-17 15:59:38 -070086 unlink(name);
Jeff Haodcdc85b2015-12-04 14:06:18 -080087 return nullptr;
88 }
89 }
90 return f.release();
91 }
92}
93
94// Either try to close the file (close=true), or erase it.
95static bool FinishFile(File* file, bool close) {
96 if (close) {
97 if (file->FlushCloseOrErase() != 0) {
98 PLOG(ERROR) << "Failed to flush and close file.";
99 return false;
100 }
101 return true;
102 } else {
103 file->Erase();
104 return false;
105 }
106}
107
David Brazdil7b49e6c2016-09-01 11:06:18 +0100108static bool SymlinkFile(const std::string& input_filename, const std::string& output_filename) {
109 if (input_filename == output_filename) {
110 // Input and output are the same, nothing to do.
111 return true;
112 }
113
114 // Unlink the original filename, since we are overwriting it.
115 unlink(output_filename.c_str());
116
117 // Create a symlink from the source file to the target path.
118 if (symlink(input_filename.c_str(), output_filename.c_str()) < 0) {
119 PLOG(ERROR) << "Failed to create symlink " << output_filename << " -> " << input_filename;
120 return false;
121 }
122
123 if (kIsDebugBuild) {
124 LOG(INFO) << "Created symlink " << output_filename << " -> " << input_filename;
125 }
126
127 return true;
128}
129
Alex Klyubin3856af02017-10-23 13:53:13 -0700130bool PatchOat::GeneratePatch(
131 const MemMap& original,
132 const MemMap& relocated,
133 std::vector<uint8_t>* output,
134 std::string* error_msg) {
135 // FORMAT of the patch (aka image relocation) file:
136 // * SHA-256 digest (32 bytes) of original/unrelocated file (e.g., the one from /system)
137 // * List of monotonically increasing offsets (max value defined by uint32_t) at which relocations
138 // occur.
139 // Each element is represented as the delta from the previous offset in the list (first element
140 // is a delta from 0). Each delta is encoded using unsigned LEB128: little-endian
141 // variable-length 7 bits per byte encoding, where all bytes have the highest bit (0x80) set
142 // except for the final byte which does not have that bit set. For example, 0x3f is offset 0x3f,
143 // whereas 0xbf 0x05 is offset (0x3f & 0x7f) | (0x5 << 7) which is 0x2bf. Most deltas end up
144 // being encoding using just one byte, achieving ~4x decrease in relocation file size compared
145 // to the encoding where offsets are stored verbatim, as uint32_t.
146
147 size_t original_size = original.Size();
148 size_t relocated_size = relocated.Size();
149 if (original_size != relocated_size) {
150 *error_msg =
151 StringPrintf(
152 "Original and relocated image sizes differ: %zu vs %zu", original_size, relocated_size);
153 return false;
154 }
155 if ((original_size % 4) != 0) {
156 *error_msg = StringPrintf("Image size not multiple of 4: %zu", original_size);
157 return false;
158 }
159 if (original_size > UINT32_MAX) {
160 *error_msg = StringPrintf("Image too large: %zu" , original_size);
161 return false;
162 }
163
164 const ImageHeader& relocated_header =
165 *reinterpret_cast<const ImageHeader*>(relocated.Begin());
166 // Offsets are supposed to differ between original and relocated by this value
167 off_t expected_diff = relocated_header.GetPatchDelta();
168 if (expected_diff == 0) {
169 // Can't identify offsets which are supposed to differ due to relocation
170 *error_msg = "Relocation delta is 0";
171 return false;
172 }
173
174 // Output the SHA-256 digest of the original
175 output->resize(SHA256_DIGEST_LENGTH);
176 const uint8_t* original_bytes = original.Begin();
177 SHA256(original_bytes, original_size, output->data());
178
179 // Output the list of offsets at which the original and patched images differ
180 size_t last_diff_offset = 0;
181 size_t diff_offset_count = 0;
182 const uint8_t* relocated_bytes = relocated.Begin();
183 for (size_t offset = 0; offset < original_size; offset += 4) {
184 uint32_t original_value = *reinterpret_cast<const uint32_t*>(original_bytes + offset);
185 uint32_t relocated_value = *reinterpret_cast<const uint32_t*>(relocated_bytes + offset);
186 off_t diff = relocated_value - original_value;
187 if (diff == 0) {
188 continue;
189 } else if (diff != expected_diff) {
190 *error_msg =
191 StringPrintf(
192 "Unexpected diff at offset %zu. Expected: %jd, but was: %jd",
193 offset,
194 (intmax_t) expected_diff,
195 (intmax_t) diff);
196 return false;
197 }
198
199 uint32_t offset_diff = offset - last_diff_offset;
200 last_diff_offset = offset;
201 diff_offset_count++;
202
203 EncodeUnsignedLeb128(output, offset_diff);
204 }
205
206 if (diff_offset_count == 0) {
207 *error_msg = "Original and patched images are identical";
208 return false;
209 }
210
211 return true;
212}
213
214static bool WriteRelFile(
215 const MemMap& original,
216 const MemMap& relocated,
217 const std::string& rel_filename,
218 std::string* error_msg) {
219 std::vector<uint8_t> output;
220 if (!PatchOat::GeneratePatch(original, relocated, &output, error_msg)) {
221 return false;
222 }
223
224 std::unique_ptr<File> rel_file(OS::CreateEmptyFileWriteOnly(rel_filename.c_str()));
225 if (rel_file.get() == nullptr) {
226 *error_msg = StringPrintf("Failed to create/open output file %s", rel_filename.c_str());
227 return false;
228 }
229 if (!rel_file->WriteFully(output.data(), output.size())) {
230 *error_msg = StringPrintf("Failed to write to %s", rel_filename.c_str());
231 return false;
232 }
233 if (rel_file->FlushCloseOrErase() != 0) {
234 *error_msg = StringPrintf("Failed to flush and close %s", rel_filename.c_str());
235 return false;
236 }
237
238 return true;
239}
240
Chris Morin754b7572018-01-19 18:04:46 -0800241static bool CheckImageIdenticalToOriginalExceptForRelocation(
242 const std::string& relocated_filename,
243 const std::string& original_filename,
244 std::string* error_msg) {
245 *error_msg = "";
246 std::string rel_filename = original_filename + ".rel";
247 std::unique_ptr<File> rel_file(OS::OpenFileForReading(rel_filename.c_str()));
248 if (rel_file.get() == nullptr) {
249 *error_msg = StringPrintf("Failed to open image relocation file %s", rel_filename.c_str());
250 return false;
251 }
252 int64_t rel_size = rel_file->GetLength();
253 if (rel_size < 0) {
254 *error_msg = StringPrintf("Error while getting size of image relocation file %s",
255 rel_filename.c_str());
256 return false;
257 }
258 std::unique_ptr<uint8_t[]> rel(new uint8_t[rel_size]);
259 if (!rel_file->ReadFully(rel.get(), rel_size)) {
260 *error_msg = StringPrintf("Failed to read image relocation file %s", rel_filename.c_str());
261 return false;
262 }
263
264 std::unique_ptr<File> image_file(OS::OpenFileForReading(relocated_filename.c_str()));
265 if (image_file.get() == nullptr) {
266 *error_msg = StringPrintf("Unable to open relocated image file %s",
267 relocated_filename.c_str());
268 return false;
269 }
270
271 int64_t image_size = image_file->GetLength();
272 if (image_size < 0) {
273 *error_msg = StringPrintf("Error while getting size of relocated image file %s",
274 relocated_filename.c_str());
275 return false;
276 }
277 if ((image_size % 4) != 0) {
278 *error_msg =
279 StringPrintf(
Orion Hodsonb348b3b2018-01-26 09:02:49 +0000280 "Relocated image file %s size not multiple of 4: %" PRId64,
Chris Morin754b7572018-01-19 18:04:46 -0800281 relocated_filename.c_str(), image_size);
282 return false;
283 }
Orion Hodsonb348b3b2018-01-26 09:02:49 +0000284 if (image_size > std::numeric_limits<uint32_t>::max()) {
Chris Morin754b7572018-01-19 18:04:46 -0800285 *error_msg =
286 StringPrintf(
Orion Hodsonb348b3b2018-01-26 09:02:49 +0000287 "Relocated image file %s too large: %" PRId64, relocated_filename.c_str(), image_size);
Chris Morin754b7572018-01-19 18:04:46 -0800288 return false;
289 }
290
291 std::unique_ptr<uint8_t[]> image(new uint8_t[image_size]);
292 if (!image_file->ReadFully(image.get(), image_size)) {
293 *error_msg = StringPrintf("Failed to read relocated image file %s", relocated_filename.c_str());
294 return false;
295 }
296
297 const uint8_t* original_image_digest = rel.get();
298 if (rel_size < SHA256_DIGEST_LENGTH) {
299 *error_msg = StringPrintf("Malformed image relocation file %s: too short",
300 rel_filename.c_str());
301 return false;
302 }
303
304 const ImageHeader& image_header = *reinterpret_cast<const ImageHeader*>(image.get());
305 off_t expected_diff = image_header.GetPatchDelta();
306
307 if (expected_diff == 0) {
308 *error_msg = StringPrintf("Unsuported patch delta of zero in %s",
309 relocated_filename.c_str());
310 return false;
311 }
312
313 // Relocated image is expected to differ from the original due to relocation.
314 // Unrelocate the image in memory to compensate.
315 uint8_t* image_start = image.get();
316 const uint8_t* rel_end = &rel[rel_size];
317 const uint8_t* rel_ptr = &rel[SHA256_DIGEST_LENGTH];
318 // The remaining .rel file consists of offsets at which relocation should've occurred.
319 // For each offset, we "unrelocate" the image by subtracting the expected relocation
320 // diff value (as specified in the image header).
321 //
322 // Each offset is encoded as a delta/diff relative to the previous offset. With the
323 // very first offset being encoded relative to offset 0.
324 // Deltas are encoded using little-endian 7 bits per byte encoding, with all bytes except
325 // the last one having the highest bit set.
326 uint32_t offset = 0;
327 while (rel_ptr != rel_end) {
328 uint32_t offset_delta = 0;
329 if (DecodeUnsignedLeb128Checked(&rel_ptr, rel_end, &offset_delta)) {
330 offset += offset_delta;
331 uint32_t *image_value = reinterpret_cast<uint32_t*>(image_start + offset);
332 *image_value -= expected_diff;
333 } else {
334 *error_msg =
335 StringPrintf(
336 "Malformed image relocation file %s: "
337 "last byte has it's most significant bit set",
338 rel_filename.c_str());
339 return false;
340 }
341 }
342
343 // Image in memory is now supposed to be identical to the original. We
344 // confirm this by comparing the digest of the in-memory image to the expected
345 // digest from relocation file.
346 uint8_t image_digest[SHA256_DIGEST_LENGTH];
347 SHA256(image.get(), image_size, image_digest);
348 if (memcmp(image_digest, original_image_digest, SHA256_DIGEST_LENGTH) != 0) {
349 *error_msg =
350 StringPrintf(
351 "Relocated image %s does not match the original %s after unrelocation",
352 relocated_filename.c_str(),
353 original_filename.c_str());
354 return false;
355 }
356
357 // Relocated image is identical to the original, once relocations are taken into account
358 return true;
359}
360
Chris Morinae6832f2018-02-09 19:12:35 -0800361static bool VerifySymlink(const std::string& intended_target, const std::string& link_name) {
362 std::string actual_target;
363 if (!android::base::Readlink(link_name, &actual_target)) {
364 PLOG(ERROR) << "Readlink on " << link_name << " failed.";
365 return false;
366 }
367 return actual_target == intended_target;
368}
369
370static bool VerifyVdexAndOatSymlinks(const std::string& input_image_filename,
371 const std::string& output_image_filename) {
372 return VerifySymlink(ImageHeader::GetVdexLocationFromImageLocation(input_image_filename),
373 ImageHeader::GetVdexLocationFromImageLocation(output_image_filename))
374 && VerifySymlink(ImageHeader::GetOatLocationFromImageLocation(input_image_filename),
375 ImageHeader::GetOatLocationFromImageLocation(output_image_filename));
376}
377
378bool PatchOat::CreateVdexAndOatSymlinks(const std::string& input_image_filename,
379 const std::string& output_image_filename) {
380 std::string input_vdex_filename =
381 ImageHeader::GetVdexLocationFromImageLocation(input_image_filename);
382 std::string input_oat_filename =
383 ImageHeader::GetOatLocationFromImageLocation(input_image_filename);
384
385 std::unique_ptr<File> input_oat_file(OS::OpenFileForReading(input_oat_filename.c_str()));
386 if (input_oat_file.get() == nullptr) {
387 LOG(ERROR) << "Unable to open input oat file at " << input_oat_filename;
388 return false;
389 }
390 std::string error_msg;
391 std::unique_ptr<ElfFile> elf(ElfFile::Open(input_oat_file.get(),
392 PROT_READ | PROT_WRITE,
393 MAP_PRIVATE,
394 &error_msg));
395 if (elf.get() == nullptr) {
396 LOG(ERROR) << "Unable to open oat file " << input_oat_filename << " : " << error_msg;
397 return false;
398 }
399
400 MaybePic is_oat_pic = IsOatPic(elf.get());
401 if (is_oat_pic >= ERROR_FIRST) {
402 // Error logged by IsOatPic
403 return false;
404 } else if (is_oat_pic == NOT_PIC) {
405 LOG(ERROR) << "patchoat cannot be used on non-PIC oat file: " << input_oat_filename;
406 return false;
407 }
408
409 CHECK(is_oat_pic == PIC);
410
411 std::string output_vdex_filename =
412 ImageHeader::GetVdexLocationFromImageLocation(output_image_filename);
413 std::string output_oat_filename =
414 ImageHeader::GetOatLocationFromImageLocation(output_image_filename);
415
416 return SymlinkFile(input_oat_filename, output_oat_filename) &&
417 SymlinkFile(input_vdex_filename, output_vdex_filename);
418}
419
Andreas Gampe6eb6a392016-02-10 20:18:37 -0800420bool PatchOat::Patch(const std::string& image_location,
421 off_t delta,
Alex Klyubin3856af02017-10-23 13:53:13 -0700422 const std::string& output_image_directory,
423 const std::string& output_image_relocation_directory,
Andreas Gampe6eb6a392016-02-10 20:18:37 -0800424 InstructionSet isa,
425 TimingLogger* timings) {
Alex Klyubin3856af02017-10-23 13:53:13 -0700426 bool output_image = !output_image_directory.empty();
427 bool output_image_relocation = !output_image_relocation_directory.empty();
428 if ((!output_image) && (!output_image_relocation)) {
429 // Nothing to do
430 return true;
431 }
432 if ((output_image_relocation) && (delta == 0)) {
433 LOG(ERROR) << "Cannot output image relocation information when requested relocation delta is 0";
434 return false;
435 }
436
Alex Light53cb16b2014-06-12 11:26:29 -0700437 CHECK(Runtime::Current() == nullptr);
Alex Light53cb16b2014-06-12 11:26:29 -0700438 CHECK(!image_location.empty()) << "image file must have a filename.";
439
Alex Lighteefbe392014-07-08 09:53:18 -0700440 TimingLogger::ScopedTiming t("Runtime Setup", timings);
Alex Light53cb16b2014-06-12 11:26:29 -0700441
Vladimir Marko33bff252017-11-01 14:35:42 +0000442 CHECK_NE(isa, InstructionSet::kNone);
Alex Light53cb16b2014-06-12 11:26:29 -0700443 const char* isa_name = GetInstructionSetString(isa);
Igor Murashkin46774762014-10-22 11:37:02 -0700444
Alex Light53cb16b2014-06-12 11:26:29 -0700445 // Set up the runtime
Ian Rogerse63db272014-07-15 15:36:11 -0700446 RuntimeOptions options;
Alex Light53cb16b2014-06-12 11:26:29 -0700447 NoopCompilerCallbacks callbacks;
448 options.push_back(std::make_pair("compilercallbacks", &callbacks));
449 std::string img = "-Ximage:" + image_location;
450 options.push_back(std::make_pair(img.c_str(), nullptr));
451 options.push_back(std::make_pair("imageinstructionset", reinterpret_cast<const void*>(isa_name)));
Calin Juravle01aaf6e2015-06-19 22:05:39 +0100452 options.push_back(std::make_pair("-Xno-sig-chain", nullptr));
Alex Light53cb16b2014-06-12 11:26:29 -0700453 if (!Runtime::Create(options, false)) {
454 LOG(ERROR) << "Unable to initialize runtime";
455 return false;
456 }
Andreas Gampeb8cc1752017-04-26 21:28:50 -0700457 std::unique_ptr<Runtime> runtime(Runtime::Current());
458
Alex Light53cb16b2014-06-12 11:26:29 -0700459 // Runtime::Create acquired the mutator_lock_ that is normally given away when we Runtime::Start,
460 // give it away now and then switch to a more manageable ScopedObjectAccess.
461 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
462 ScopedObjectAccess soa(Thread::Current());
463
Jeff Haodcdc85b2015-12-04 14:06:18 -0800464 std::vector<gc::space::ImageSpace*> spaces = Runtime::Current()->GetHeap()->GetBootImageSpaces();
Jeff Haodcdc85b2015-12-04 14:06:18 -0800465 std::map<gc::space::ImageSpace*, std::unique_ptr<MemMap>> space_to_memmap_map;
Alex Light53cb16b2014-06-12 11:26:29 -0700466
Jeff Haodcdc85b2015-12-04 14:06:18 -0800467 for (size_t i = 0; i < spaces.size(); ++i) {
Chris Morinae6832f2018-02-09 19:12:35 -0800468 t.NewTiming("Image Patching setup");
Jeff Haodcdc85b2015-12-04 14:06:18 -0800469 gc::space::ImageSpace* space = spaces[i];
470 std::string input_image_filename = space->GetImageFilename();
471 std::unique_ptr<File> input_image(OS::OpenFileForReading(input_image_filename.c_str()));
472 if (input_image.get() == nullptr) {
473 LOG(ERROR) << "Unable to open input image file at " << input_image_filename;
Igor Murashkin46774762014-10-22 11:37:02 -0700474 return false;
475 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800476
477 int64_t image_len = input_image->GetLength();
478 if (image_len < 0) {
479 LOG(ERROR) << "Error while getting image length";
480 return false;
481 }
482 ImageHeader image_header;
483 if (sizeof(image_header) != input_image->Read(reinterpret_cast<char*>(&image_header),
484 sizeof(image_header), 0)) {
485 LOG(ERROR) << "Unable to read image header from image file " << input_image->GetPath();
486 }
487
488 /*bool is_image_pic = */IsImagePic(image_header, input_image->GetPath());
489 // Nothing special to do right now since the image always needs to get patched.
490 // Perhaps in some far-off future we may have images with relative addresses that are true-PIC.
491
492 // Create the map where we will write the image patches to.
493 std::string error_msg;
494 std::unique_ptr<MemMap> image(MemMap::MapFile(image_len,
495 PROT_READ | PROT_WRITE,
496 MAP_PRIVATE,
497 input_image->Fd(),
498 0,
499 /*low_4gb*/false,
500 input_image->GetPath().c_str(),
501 &error_msg));
502 if (image.get() == nullptr) {
503 LOG(ERROR) << "Unable to map image file " << input_image->GetPath() << " : " << error_msg;
504 return false;
505 }
Chris Morinae6832f2018-02-09 19:12:35 -0800506
507
Jeff Haodcdc85b2015-12-04 14:06:18 -0800508 space_to_memmap_map.emplace(space, std::move(image));
Chris Morinae6832f2018-02-09 19:12:35 -0800509 PatchOat p = PatchOat(isa,
510 space_to_memmap_map.at(space).get(),
511 space->GetLiveBitmap(),
512 space->GetMemMap(),
513 delta,
514 &space_to_memmap_map,
515 timings);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800516
Richard Uhler4bc11d02017-02-01 09:53:54 +0000517 t.NewTiming("Patching image");
Jeff Haodcdc85b2015-12-04 14:06:18 -0800518 if (!p.PatchImage(i == 0)) {
519 LOG(ERROR) << "Failed to patch image file " << input_image_filename;
520 return false;
521 }
Alex Light53cb16b2014-06-12 11:26:29 -0700522
Alex Klyubin3856af02017-10-23 13:53:13 -0700523 // Write the patched image spaces.
Chris Morinae6832f2018-02-09 19:12:35 -0800524 if (output_image) {
525 std::string output_image_filename;
526 if (!GetDalvikCacheFilename(space->GetImageLocation().c_str(),
527 output_image_directory.c_str(),
528 &output_image_filename,
529 &error_msg)) {
530 LOG(ERROR) << "Failed to find relocated image file name: " << error_msg;
531 return false;
532 }
533
534 if (!CreateVdexAndOatSymlinks(input_image_filename, output_image_filename))
535 return false;
Jeff Haodcdc85b2015-12-04 14:06:18 -0800536
Alex Klyubin3856af02017-10-23 13:53:13 -0700537 t.NewTiming("Writing image");
Alex Klyubin3856af02017-10-23 13:53:13 -0700538 std::unique_ptr<File> output_image_file(CreateOrOpen(output_image_filename.c_str()));
539 if (output_image_file.get() == nullptr) {
540 LOG(ERROR) << "Failed to open output image file at " << output_image_filename;
541 return false;
542 }
543
Alex Klyubin3856af02017-10-23 13:53:13 -0700544 bool success = p.WriteImage(output_image_file.get());
545 success = FinishFile(output_image_file.get(), success);
546 if (!success) {
547 return false;
548 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800549 }
550
Chris Morinae6832f2018-02-09 19:12:35 -0800551 if (output_image_relocation) {
Alex Klyubin3856af02017-10-23 13:53:13 -0700552 t.NewTiming("Writing image relocation");
553 std::string original_image_filename(space->GetImageLocation() + ".rel");
554 std::string image_relocation_filename =
555 output_image_relocation_directory
556 + (android::base::StartsWith(original_image_filename, "/") ? "" : "/")
557 + original_image_filename.substr(original_image_filename.find_last_of("/"));
Chris Morinae6832f2018-02-09 19:12:35 -0800558 int64_t input_image_size = input_image->GetLength();
Alex Klyubin3856af02017-10-23 13:53:13 -0700559 if (input_image_size < 0) {
560 LOG(ERROR) << "Error while getting input image size";
561 return false;
562 }
Alex Klyubin3856af02017-10-23 13:53:13 -0700563 std::unique_ptr<MemMap> original(MemMap::MapFile(input_image_size,
564 PROT_READ,
565 MAP_PRIVATE,
Chris Morinae6832f2018-02-09 19:12:35 -0800566 input_image->Fd(),
Alex Klyubin3856af02017-10-23 13:53:13 -0700567 0,
568 /*low_4gb*/false,
Chris Morinae6832f2018-02-09 19:12:35 -0800569 input_image->GetPath().c_str(),
Alex Klyubin3856af02017-10-23 13:53:13 -0700570 &error_msg));
571 if (original.get() == nullptr) {
Chris Morinae6832f2018-02-09 19:12:35 -0800572 LOG(ERROR) << "Unable to map image file " << input_image->GetPath() << " : " << error_msg;
Alex Klyubin3856af02017-10-23 13:53:13 -0700573 return false;
574 }
575
Alex Klyubin3856af02017-10-23 13:53:13 -0700576 const MemMap* relocated = p.image_;
577
578 if (!WriteRelFile(*original, *relocated, image_relocation_filename, &error_msg)) {
579 LOG(ERROR) << "Failed to create image relocation file " << image_relocation_filename
580 << ": " << error_msg;
581 return false;
582 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800583 }
Alex Light53cb16b2014-06-12 11:26:29 -0700584 }
Andreas Gampeb8cc1752017-04-26 21:28:50 -0700585
586 if (!kIsDebugBuild && !(RUNNING_ON_MEMORY_TOOL && kMemoryToolDetectsLeaks)) {
587 // We want to just exit on non-debug builds, not bringing the runtime down
588 // in an orderly fashion. So release the following fields.
589 runtime.release();
590 }
591
Alex Light53cb16b2014-06-12 11:26:29 -0700592 return true;
593}
594
Chris Morin754b7572018-01-19 18:04:46 -0800595bool PatchOat::Verify(const std::string& image_location,
596 const std::string& output_image_directory,
597 InstructionSet isa,
598 TimingLogger* timings) {
599 if (image_location.empty()) {
600 LOG(ERROR) << "Original image file not provided";
601 return false;
602 }
603 if (output_image_directory.empty()) {
604 LOG(ERROR) << "Relocated image directory not provided";
605 return false;
606 }
607
608 TimingLogger::ScopedTiming t("Runtime Setup", timings);
609
610 CHECK_NE(isa, InstructionSet::kNone);
611 const char* isa_name = GetInstructionSetString(isa);
612
613 // Set up the runtime
614 RuntimeOptions options;
615 NoopCompilerCallbacks callbacks;
616 options.push_back(std::make_pair("compilercallbacks", &callbacks));
617 std::string img = "-Ximage:" + image_location;
618 options.push_back(std::make_pair(img.c_str(), nullptr));
619 options.push_back(std::make_pair("imageinstructionset", reinterpret_cast<const void*>(isa_name)));
620 options.push_back(std::make_pair("-Xno-sig-chain", nullptr));
621 if (!Runtime::Create(options, false)) {
622 LOG(ERROR) << "Unable to initialize runtime";
623 return false;
624 }
625 std::unique_ptr<Runtime> runtime(Runtime::Current());
626
627 // Runtime::Create acquired the mutator_lock_ that is normally given away when we Runtime::Start,
628 // give it away now and then switch to a more manageable ScopedObjectAccess.
629 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
630 ScopedObjectAccess soa(Thread::Current());
631
632 t.NewTiming("Image Verification setup");
633 std::vector<gc::space::ImageSpace*> spaces = Runtime::Current()->GetHeap()->GetBootImageSpaces();
634
635 // TODO: Check that no other .rel files exist in the original dir
636
637 bool success = true;
638 std::string image_location_dir = android::base::Dirname(image_location);
639 for (size_t i = 0; i < spaces.size(); ++i) {
640 gc::space::ImageSpace* space = spaces[i];
Chris Morin754b7572018-01-19 18:04:46 -0800641
642 std::string relocated_image_filename;
643 std::string error_msg;
Chris Morinae6832f2018-02-09 19:12:35 -0800644 if (!GetDalvikCacheFilename(space->GetImageLocation().c_str(),
Chris Morin754b7572018-01-19 18:04:46 -0800645 output_image_directory.c_str(), &relocated_image_filename, &error_msg)) {
646 LOG(ERROR) << "Failed to find relocated image file name: " << error_msg;
647 success = false;
648 break;
649 }
650 // location: /system/framework/boot.art
651 // isa: arm64
652 // basename: boot.art
653 // original: /system/framework/arm64/boot.art
654 // relocation: /system/framework/arm64/boot.art.rel
Chris Morinae6832f2018-02-09 19:12:35 -0800655 std::string original_image_filename =
656 GetSystemImageFilename(space->GetImageLocation().c_str(), isa);
Chris Morin754b7572018-01-19 18:04:46 -0800657
658 if (!CheckImageIdenticalToOriginalExceptForRelocation(
659 relocated_image_filename, original_image_filename, &error_msg)) {
660 LOG(ERROR) << error_msg;
661 success = false;
662 break;
663 }
Chris Morinae6832f2018-02-09 19:12:35 -0800664
665 if (!VerifyVdexAndOatSymlinks(original_image_filename, relocated_image_filename)) {
666 LOG(ERROR) << "Verification of vdex and oat symlinks for "
667 << space->GetImageLocation() << " failed.";
668 success = false;
669 break;
670 }
Chris Morin754b7572018-01-19 18:04:46 -0800671 }
672
673 if (!kIsDebugBuild && !(RUNNING_ON_MEMORY_TOOL && kMemoryToolDetectsLeaks)) {
674 // We want to just exit on non-debug builds, not bringing the runtime down
675 // in an orderly fashion. So release the following fields.
676 runtime.release();
677 }
678
679 return success;
680}
681
Alex Light53cb16b2014-06-12 11:26:29 -0700682bool PatchOat::WriteImage(File* out) {
Alex Lighteefbe392014-07-08 09:53:18 -0700683 TimingLogger::ScopedTiming t("Writing image File", timings_);
Alex Lighta59dd802014-07-02 16:28:08 -0700684 std::string error_msg;
685
Narayan Kamatha3d27eb2017-05-11 13:50:59 +0100686 // No error checking here, this is best effort. The locking may or may not
687 // succeed and we don't really care either way.
688 ScopedFlock img_flock = LockedFile::DupOf(out->Fd(), out->GetPath(),
689 true /* read_only_mode */, &error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -0700690
Alex Light53cb16b2014-06-12 11:26:29 -0700691 CHECK(image_ != nullptr);
692 CHECK(out != nullptr);
693 size_t expect = image_->Size();
694 if (out->WriteFully(reinterpret_cast<char*>(image_->Begin()), expect) &&
695 out->SetLength(expect) == 0) {
696 return true;
697 } else {
698 LOG(ERROR) << "Writing to image file " << out->GetPath() << " failed.";
699 return false;
700 }
701}
702
Igor Murashkin46774762014-10-22 11:37:02 -0700703bool PatchOat::IsImagePic(const ImageHeader& image_header, const std::string& image_path) {
704 if (!image_header.CompilePic()) {
705 if (kIsDebugBuild) {
706 LOG(INFO) << "image at location " << image_path << " was *not* compiled pic";
707 }
708 return false;
709 }
710
711 if (kIsDebugBuild) {
712 LOG(INFO) << "image at location " << image_path << " was compiled PIC";
713 }
714
715 return true;
716}
717
718PatchOat::MaybePic PatchOat::IsOatPic(const ElfFile* oat_in) {
719 if (oat_in == nullptr) {
720 LOG(ERROR) << "No ELF input oat fie available";
721 return ERROR_OAT_FILE;
722 }
723
Brian Carlstromf5b0f2c2016-10-14 01:04:26 -0700724 const std::string& file_path = oat_in->GetFilePath();
Igor Murashkin46774762014-10-22 11:37:02 -0700725
726 const OatHeader* oat_header = GetOatHeader(oat_in);
727 if (oat_header == nullptr) {
728 LOG(ERROR) << "Failed to find oat header in oat file " << file_path;
729 return ERROR_OAT_FILE;
730 }
731
732 if (!oat_header->IsValid()) {
733 LOG(ERROR) << "Elf file " << file_path << " has an invalid oat header";
734 return ERROR_OAT_FILE;
735 }
736
737 bool is_pic = oat_header->IsPic();
738 if (kIsDebugBuild) {
739 LOG(INFO) << "Oat file at " << file_path << " is " << (is_pic ? "PIC" : "not pic");
740 }
741
742 return is_pic ? PIC : NOT_PIC;
743}
744
Vladimir Markoad06b982016-11-17 16:38:59 +0000745class PatchOat::PatchOatArtFieldVisitor : public ArtFieldVisitor {
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700746 public:
747 explicit PatchOatArtFieldVisitor(PatchOat* patch_oat) : patch_oat_(patch_oat) {}
748
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700749 void Visit(ArtField* field) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700750 ArtField* const dest = patch_oat_->RelocatedCopyOf(field);
Mathieu Chartier3398c782016-09-30 10:27:43 -0700751 dest->SetDeclaringClass(
Mathieu Chartier1cc62e42016-10-03 18:01:28 -0700752 patch_oat_->RelocatedAddressOfPointer(field->GetDeclaringClass().Ptr()));
Mathieu Chartiere401d142015-04-22 13:56:20 -0700753 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700754
755 private:
756 PatchOat* const patch_oat_;
757};
758
759void PatchOat::PatchArtFields(const ImageHeader* image_header) {
760 PatchOatArtFieldVisitor visitor(this);
Mathieu Chartiere42888f2016-04-14 10:49:19 -0700761 image_header->VisitPackedArtFields(&visitor, heap_->Begin());
Mathieu Chartiere401d142015-04-22 13:56:20 -0700762}
763
Vladimir Markoad06b982016-11-17 16:38:59 +0000764class PatchOat::PatchOatArtMethodVisitor : public ArtMethodVisitor {
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700765 public:
766 explicit PatchOatArtMethodVisitor(PatchOat* patch_oat) : patch_oat_(patch_oat) {}
767
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700768 void Visit(ArtMethod* method) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700769 ArtMethod* const dest = patch_oat_->RelocatedCopyOf(method);
770 patch_oat_->FixupMethod(method, dest);
771 }
772
773 private:
774 PatchOat* const patch_oat_;
775};
776
Mathieu Chartiere401d142015-04-22 13:56:20 -0700777void PatchOat::PatchArtMethods(const ImageHeader* image_header) {
Andreas Gampe542451c2016-07-26 09:02:02 -0700778 const PointerSize pointer_size = InstructionSetPointerSize(isa_);
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700779 PatchOatArtMethodVisitor visitor(this);
Mathieu Chartiere42888f2016-04-14 10:49:19 -0700780 image_header->VisitPackedArtMethods(&visitor, heap_->Begin(), pointer_size);
781}
782
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +0000783void PatchOat::PatchImTables(const ImageHeader* image_header) {
Andreas Gampe542451c2016-07-26 09:02:02 -0700784 const PointerSize pointer_size = InstructionSetPointerSize(isa_);
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +0000785 // We can safely walk target image since the conflict tables are independent.
786 image_header->VisitPackedImTables(
787 [this](ArtMethod* method) {
788 return RelocatedAddressOfPointer(method);
789 },
790 image_->Begin(),
791 pointer_size);
792}
793
Mathieu Chartiere42888f2016-04-14 10:49:19 -0700794void PatchOat::PatchImtConflictTables(const ImageHeader* image_header) {
Andreas Gampe542451c2016-07-26 09:02:02 -0700795 const PointerSize pointer_size = InstructionSetPointerSize(isa_);
Mathieu Chartiere42888f2016-04-14 10:49:19 -0700796 // We can safely walk target image since the conflict tables are independent.
797 image_header->VisitPackedImtConflictTables(
798 [this](ArtMethod* method) {
799 return RelocatedAddressOfPointer(method);
800 },
801 image_->Begin(),
802 pointer_size);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700803}
804
Vladimir Markoad06b982016-11-17 16:38:59 +0000805class PatchOat::FixupRootVisitor : public RootVisitor {
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700806 public:
807 explicit FixupRootVisitor(const PatchOat* patch_oat) : patch_oat_(patch_oat) {
808 }
809
810 void VisitRoots(mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700811 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700812 for (size_t i = 0; i < count; ++i) {
813 *roots[i] = patch_oat_->RelocatedAddressOfPointer(*roots[i]);
814 }
815 }
816
817 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots, size_t count,
818 const RootInfo& info ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700819 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700820 for (size_t i = 0; i < count; ++i) {
821 roots[i]->Assign(patch_oat_->RelocatedAddressOfPointer(roots[i]->AsMirrorPtr()));
822 }
823 }
824
825 private:
826 const PatchOat* const patch_oat_;
827};
828
829void PatchOat::PatchInternedStrings(const ImageHeader* image_header) {
Vladimir Markocd87c3e2017-09-05 13:11:57 +0100830 const auto& section = image_header->GetInternedStringsSection();
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100831 if (section.Size() == 0) {
832 return;
833 }
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700834 InternTable temp_table;
835 // Note that we require that ReadFromMemory does not make an internal copy of the elements.
836 // This also relies on visit roots not doing any verification which could fail after we update
837 // the roots to be the image addresses.
Mathieu Chartierea0831f2015-12-29 13:17:37 -0800838 temp_table.AddTableFromMemory(image_->Begin() + section.Offset());
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700839 FixupRootVisitor visitor(this);
840 temp_table.VisitRoots(&visitor, kVisitRootFlagAllRoots);
841}
842
Mathieu Chartier208a5cb2015-12-02 15:44:07 -0800843void PatchOat::PatchClassTable(const ImageHeader* image_header) {
Vladimir Markocd87c3e2017-09-05 13:11:57 +0100844 const auto& section = image_header->GetClassTableSection();
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800845 if (section.Size() == 0) {
846 return;
847 }
Mathieu Chartier208a5cb2015-12-02 15:44:07 -0800848 // Note that we require that ReadFromMemory does not make an internal copy of the elements.
849 // This also relies on visit roots not doing any verification which could fail after we update
850 // the roots to be the image addresses.
851 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
852 ClassTable temp_table;
853 temp_table.ReadFromMemory(image_->Begin() + section.Offset());
854 FixupRootVisitor visitor(this);
Mathieu Chartier58c3f6a2016-12-01 14:21:11 -0800855 temp_table.VisitRoots(UnbufferedRootVisitor(&visitor, RootInfo(kRootUnknown)));
Mathieu Chartier208a5cb2015-12-02 15:44:07 -0800856}
857
858
Vladimir Markoad06b982016-11-17 16:38:59 +0000859class PatchOat::RelocatedPointerVisitor {
Mathieu Chartier4b00d342015-11-13 10:42:08 -0800860 public:
861 explicit RelocatedPointerVisitor(PatchOat* patch_oat) : patch_oat_(patch_oat) {}
862
863 template <typename T>
Mathieu Chartier8c19d242017-03-06 12:35:10 -0800864 T* operator()(T* ptr, void** dest_addr ATTRIBUTE_UNUSED = 0) const {
Mathieu Chartier4b00d342015-11-13 10:42:08 -0800865 return patch_oat_->RelocatedAddressOfPointer(ptr);
866 }
867
868 private:
869 PatchOat* const patch_oat_;
870};
871
Mathieu Chartierc7853442015-03-27 14:35:38 -0700872void PatchOat::PatchDexFileArrays(mirror::ObjectArray<mirror::Object>* img_roots) {
873 auto* dex_caches = down_cast<mirror::ObjectArray<mirror::DexCache>*>(
874 img_roots->Get(ImageHeader::kDexCaches));
Andreas Gampe542451c2016-07-26 09:02:02 -0700875 const PointerSize pointer_size = InstructionSetPointerSize(isa_);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700876 for (size_t i = 0, count = dex_caches->GetLength(); i < count; ++i) {
Vladimir Marko05792b92015-08-03 11:56:49 +0100877 auto* orig_dex_cache = dex_caches->GetWithoutChecks(i);
878 auto* copy_dex_cache = RelocatedCopyOf(orig_dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +0100879 // Though the DexCache array fields are usually treated as native pointers, we set the full
880 // 64-bit values here, clearing the top 32 bits for 32-bit targets. The zero-extension is
881 // done by casting to the unsigned type uintptr_t before casting to int64_t, i.e.
882 // static_cast<int64_t>(reinterpret_cast<uintptr_t>(image_begin_ + offset))).
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -0700883 mirror::StringDexCacheType* orig_strings = orig_dex_cache->GetStrings();
884 mirror::StringDexCacheType* relocated_strings = RelocatedAddressOfPointer(orig_strings);
Vladimir Marko05792b92015-08-03 11:56:49 +0100885 copy_dex_cache->SetField64<false>(
886 mirror::DexCache::StringsOffset(),
887 static_cast<int64_t>(reinterpret_cast<uintptr_t>(relocated_strings)));
888 if (orig_strings != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -0800889 orig_dex_cache->FixupStrings(RelocatedCopyOf(orig_strings), RelocatedPointerVisitor(this));
Mathieu Chartierc7853442015-03-27 14:35:38 -0700890 }
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000891 mirror::TypeDexCacheType* orig_types = orig_dex_cache->GetResolvedTypes();
892 mirror::TypeDexCacheType* relocated_types = RelocatedAddressOfPointer(orig_types);
Vladimir Marko05792b92015-08-03 11:56:49 +0100893 copy_dex_cache->SetField64<false>(
894 mirror::DexCache::ResolvedTypesOffset(),
895 static_cast<int64_t>(reinterpret_cast<uintptr_t>(relocated_types)));
896 if (orig_types != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -0800897 orig_dex_cache->FixupResolvedTypes(RelocatedCopyOf(orig_types),
898 RelocatedPointerVisitor(this));
Vladimir Marko05792b92015-08-03 11:56:49 +0100899 }
Vladimir Marko07bfbac2017-07-06 14:55:02 +0100900 mirror::MethodDexCacheType* orig_methods = orig_dex_cache->GetResolvedMethods();
901 mirror::MethodDexCacheType* relocated_methods = RelocatedAddressOfPointer(orig_methods);
Vladimir Marko05792b92015-08-03 11:56:49 +0100902 copy_dex_cache->SetField64<false>(
903 mirror::DexCache::ResolvedMethodsOffset(),
904 static_cast<int64_t>(reinterpret_cast<uintptr_t>(relocated_methods)));
905 if (orig_methods != nullptr) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +0100906 mirror::MethodDexCacheType* copy_methods = RelocatedCopyOf(orig_methods);
Vladimir Marko05792b92015-08-03 11:56:49 +0100907 for (size_t j = 0, num = orig_dex_cache->NumResolvedMethods(); j != num; ++j) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +0100908 mirror::MethodDexCachePair orig =
909 mirror::DexCache::GetNativePairPtrSize(orig_methods, j, pointer_size);
910 mirror::MethodDexCachePair copy(RelocatedAddressOfPointer(orig.object), orig.index);
911 mirror::DexCache::SetNativePairPtrSize(copy_methods, j, copy, pointer_size);
Vladimir Marko05792b92015-08-03 11:56:49 +0100912 }
913 }
Vladimir Markof44d36c2017-03-14 14:18:46 +0000914 mirror::FieldDexCacheType* orig_fields = orig_dex_cache->GetResolvedFields();
915 mirror::FieldDexCacheType* relocated_fields = RelocatedAddressOfPointer(orig_fields);
Vladimir Marko05792b92015-08-03 11:56:49 +0100916 copy_dex_cache->SetField64<false>(
917 mirror::DexCache::ResolvedFieldsOffset(),
918 static_cast<int64_t>(reinterpret_cast<uintptr_t>(relocated_fields)));
919 if (orig_fields != nullptr) {
Vladimir Markof44d36c2017-03-14 14:18:46 +0000920 mirror::FieldDexCacheType* copy_fields = RelocatedCopyOf(orig_fields);
Vladimir Marko05792b92015-08-03 11:56:49 +0100921 for (size_t j = 0, num = orig_dex_cache->NumResolvedFields(); j != num; ++j) {
Vladimir Markof44d36c2017-03-14 14:18:46 +0000922 mirror::FieldDexCachePair orig =
923 mirror::DexCache::GetNativePairPtrSize(orig_fields, j, pointer_size);
924 mirror::FieldDexCachePair copy(RelocatedAddressOfPointer(orig.object), orig.index);
925 mirror::DexCache::SetNativePairPtrSize(copy_fields, j, copy, pointer_size);
Vladimir Marko05792b92015-08-03 11:56:49 +0100926 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700927 }
Narayan Kamath7fe56582016-10-14 18:49:12 +0100928 mirror::MethodTypeDexCacheType* orig_method_types = orig_dex_cache->GetResolvedMethodTypes();
929 mirror::MethodTypeDexCacheType* relocated_method_types =
930 RelocatedAddressOfPointer(orig_method_types);
931 copy_dex_cache->SetField64<false>(
932 mirror::DexCache::ResolvedMethodTypesOffset(),
933 static_cast<int64_t>(reinterpret_cast<uintptr_t>(relocated_method_types)));
934 if (orig_method_types != nullptr) {
935 orig_dex_cache->FixupResolvedMethodTypes(RelocatedCopyOf(orig_method_types),
936 RelocatedPointerVisitor(this));
937 }
Orion Hodsonc069a302017-01-18 09:23:12 +0000938
939 GcRoot<mirror::CallSite>* orig_call_sites = orig_dex_cache->GetResolvedCallSites();
940 GcRoot<mirror::CallSite>* relocated_call_sites = RelocatedAddressOfPointer(orig_call_sites);
941 copy_dex_cache->SetField64<false>(
942 mirror::DexCache::ResolvedCallSitesOffset(),
943 static_cast<int64_t>(reinterpret_cast<uintptr_t>(relocated_call_sites)));
944 if (orig_call_sites != nullptr) {
945 orig_dex_cache->FixupResolvedCallSites(RelocatedCopyOf(orig_call_sites),
946 RelocatedPointerVisitor(this));
947 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700948 }
949}
950
Jeff Haodcdc85b2015-12-04 14:06:18 -0800951bool PatchOat::PatchImage(bool primary_image) {
Alex Light53cb16b2014-06-12 11:26:29 -0700952 ImageHeader* image_header = reinterpret_cast<ImageHeader*>(image_->Begin());
953 CHECK_GT(image_->Size(), sizeof(ImageHeader));
954 // These are the roots from the original file.
Mathieu Chartierc7853442015-03-27 14:35:38 -0700955 auto* img_roots = image_header->GetImageRoots();
Alex Light53cb16b2014-06-12 11:26:29 -0700956 image_header->RelocateImage(delta_);
957
Mathieu Chartierc7853442015-03-27 14:35:38 -0700958 PatchArtFields(image_header);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700959 PatchArtMethods(image_header);
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +0000960 PatchImTables(image_header);
Mathieu Chartiere42888f2016-04-14 10:49:19 -0700961 PatchImtConflictTables(image_header);
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700962 PatchInternedStrings(image_header);
Mathieu Chartier208a5cb2015-12-02 15:44:07 -0800963 PatchClassTable(image_header);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700964 // Patch dex file int/long arrays which point to ArtFields.
965 PatchDexFileArrays(img_roots);
966
Jeff Haodcdc85b2015-12-04 14:06:18 -0800967 if (primary_image) {
968 VisitObject(img_roots);
969 }
970
Alex Light53cb16b2014-06-12 11:26:29 -0700971 if (!image_header->IsValid()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800972 LOG(ERROR) << "relocation renders image header invalid";
Alex Light53cb16b2014-06-12 11:26:29 -0700973 return false;
974 }
975
976 {
Alex Lighteefbe392014-07-08 09:53:18 -0700977 TimingLogger::ScopedTiming t("Walk Bitmap", timings_);
Alex Light53cb16b2014-06-12 11:26:29 -0700978 // Walk the bitmap.
979 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Andreas Gampe0c183382017-07-13 22:26:24 -0700980 auto visitor = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
981 VisitObject(obj);
982 };
983 bitmap_->Walk(visitor);
Alex Light53cb16b2014-06-12 11:26:29 -0700984 }
985 return true;
986}
987
Alex Light53cb16b2014-06-12 11:26:29 -0700988
Mathieu Chartier31e88222016-10-14 18:43:19 -0700989void PatchOat::PatchVisitor::operator() (ObjPtr<mirror::Object> obj,
990 MemberOffset off,
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700991 bool is_static_unused ATTRIBUTE_UNUSED) const {
Alex Light53cb16b2014-06-12 11:26:29 -0700992 mirror::Object* referent = obj->GetFieldObject<mirror::Object, kVerifyNone>(off);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700993 mirror::Object* moved_object = patcher_->RelocatedAddressOfPointer(referent);
Alex Light53cb16b2014-06-12 11:26:29 -0700994 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(off, moved_object);
995}
996
Mathieu Chartier31e88222016-10-14 18:43:19 -0700997void PatchOat::PatchVisitor::operator() (ObjPtr<mirror::Class> cls ATTRIBUTE_UNUSED,
998 ObjPtr<mirror::Reference> ref) const {
Alex Light53cb16b2014-06-12 11:26:29 -0700999 MemberOffset off = mirror::Reference::ReferentOffset();
1000 mirror::Object* referent = ref->GetReferent();
Mathieu Chartiera13abba2016-04-21 10:23:16 -07001001 DCHECK(referent == nullptr ||
1002 Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(referent)) << referent;
Mathieu Chartierc7853442015-03-27 14:35:38 -07001003 mirror::Object* moved_object = patcher_->RelocatedAddressOfPointer(referent);
Alex Light53cb16b2014-06-12 11:26:29 -07001004 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(off, moved_object);
1005}
1006
Andreas Gampe0c183382017-07-13 22:26:24 -07001007// Called by PatchImage.
Alex Light53cb16b2014-06-12 11:26:29 -07001008void PatchOat::VisitObject(mirror::Object* object) {
1009 mirror::Object* copy = RelocatedCopyOf(object);
1010 CHECK(copy != nullptr);
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -07001011 if (kUseBakerReadBarrier) {
1012 object->AssertReadBarrierState();
Alex Light53cb16b2014-06-12 11:26:29 -07001013 }
1014 PatchOat::PatchVisitor visitor(this, copy);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07001015 object->VisitReferences<kVerifyNone>(visitor, visitor);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001016 if (object->IsClass<kVerifyNone>()) {
Andreas Gampe542451c2016-07-26 09:02:02 -07001017 const PointerSize pointer_size = InstructionSetPointerSize(isa_);
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001018 mirror::Class* klass = object->AsClass();
1019 mirror::Class* copy_klass = down_cast<mirror::Class*>(copy);
1020 RelocatedPointerVisitor native_visitor(this);
1021 klass->FixupNativePointers(copy_klass, pointer_size, native_visitor);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001022 auto* vtable = klass->GetVTable();
1023 if (vtable != nullptr) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001024 vtable->Fixup(RelocatedCopyOfFollowImages(vtable), pointer_size, native_visitor);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001025 }
Mathieu Chartier6beced42016-11-15 15:51:31 -08001026 mirror::IfTable* iftable = klass->GetIfTable();
1027 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
1028 if (iftable->GetMethodArrayCount(i) > 0) {
1029 auto* method_array = iftable->GetMethodArray(i);
1030 CHECK(method_array != nullptr);
1031 method_array->Fixup(RelocatedCopyOfFollowImages(method_array),
1032 pointer_size,
1033 native_visitor);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001034 }
1035 }
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001036 } else if (object->GetClass() == mirror::Method::StaticClass() ||
1037 object->GetClass() == mirror::Constructor::StaticClass()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001038 // Need to go update the ArtMethod.
Neil Fuller0e844392016-09-08 13:43:31 +01001039 auto* dest = down_cast<mirror::Executable*>(copy);
1040 auto* src = down_cast<mirror::Executable*>(object);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001041 dest->SetArtMethod(RelocatedAddressOfPointer(src->GetArtMethod()));
Alex Light53cb16b2014-06-12 11:26:29 -07001042 }
1043}
1044
Mathieu Chartiere401d142015-04-22 13:56:20 -07001045void PatchOat::FixupMethod(ArtMethod* object, ArtMethod* copy) {
Andreas Gampe542451c2016-07-26 09:02:02 -07001046 const PointerSize pointer_size = InstructionSetPointerSize(isa_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001047 copy->CopyFrom(object, pointer_size);
Alex Light53cb16b2014-06-12 11:26:29 -07001048 // Just update the entry points if it looks like we should.
Alex Lighteefbe392014-07-08 09:53:18 -07001049 // TODO: sanity check all the pointers' values
Mathieu Chartiere401d142015-04-22 13:56:20 -07001050 copy->SetDeclaringClass(RelocatedAddressOfPointer(object->GetDeclaringClass()));
Mathieu Chartiere401d142015-04-22 13:56:20 -07001051 copy->SetEntryPointFromQuickCompiledCodePtrSize(RelocatedAddressOfPointer(
1052 object->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size)), pointer_size);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001053 // No special handling for IMT conflict table since all pointers are moved by the same offset.
Andreas Gampe75f08852016-07-19 08:06:07 -07001054 copy->SetDataPtrSize(RelocatedAddressOfPointer(
1055 object->GetDataPtrSize(pointer_size)), pointer_size);
Alex Light53cb16b2014-06-12 11:26:29 -07001056}
1057
Alex Light53cb16b2014-06-12 11:26:29 -07001058static int orig_argc;
1059static char** orig_argv;
1060
1061static std::string CommandLine() {
1062 std::vector<std::string> command;
1063 for (int i = 0; i < orig_argc; ++i) {
1064 command.push_back(orig_argv[i]);
1065 }
Andreas Gampe9186ced2016-12-12 14:28:21 -08001066 return android::base::Join(command, ' ');
Alex Light53cb16b2014-06-12 11:26:29 -07001067}
1068
1069static void UsageErrorV(const char* fmt, va_list ap) {
1070 std::string error;
Andreas Gampe46ee31b2016-12-14 10:11:49 -08001071 android::base::StringAppendV(&error, fmt, ap);
Alex Light53cb16b2014-06-12 11:26:29 -07001072 LOG(ERROR) << error;
1073}
1074
1075static void UsageError(const char* fmt, ...) {
1076 va_list ap;
1077 va_start(ap, fmt);
1078 UsageErrorV(fmt, ap);
1079 va_end(ap);
1080}
1081
Andreas Gampe794ad762015-02-23 08:12:24 -08001082NO_RETURN static void Usage(const char *fmt, ...) {
Alex Light53cb16b2014-06-12 11:26:29 -07001083 va_list ap;
1084 va_start(ap, fmt);
1085 UsageErrorV(fmt, ap);
1086 va_end(ap);
1087
1088 UsageError("Command: %s", CommandLine().c_str());
1089 UsageError("Usage: patchoat [options]...");
1090 UsageError("");
1091 UsageError(" --instruction-set=<isa>: Specifies the instruction set the patched code is");
Richard Uhler4bc11d02017-02-01 09:53:54 +00001092 UsageError(" compiled for (required).");
Alex Light53cb16b2014-06-12 11:26:29 -07001093 UsageError("");
1094 UsageError(" --input-image-location=<file.art>: Specifies the 'location' of the image file to");
Richard Uhler4bc11d02017-02-01 09:53:54 +00001095 UsageError(" be patched.");
Alex Light53cb16b2014-06-12 11:26:29 -07001096 UsageError("");
Chris Morin88c6d262018-02-13 15:26:21 -08001097 UsageError(" --output-image-directory=<dir>: Specifies the directory to write the patched");
1098 UsageError(" image file(s) to.");
Alex Light53cb16b2014-06-12 11:26:29 -07001099 UsageError("");
Chris Morin88c6d262018-02-13 15:26:21 -08001100 UsageError(" --output-image-relocation-directory=<dir>: Specifies the directory to write");
Alex Klyubin3856af02017-10-23 13:53:13 -07001101 UsageError(" the image relocation information to.");
1102 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -07001103 UsageError(" --base-offset-delta=<delta>: Specify the amount to change the old base-offset by.");
1104 UsageError(" This value may be negative.");
1105 UsageError("");
Chris Morin754b7572018-01-19 18:04:46 -08001106 UsageError(" --verify: Verify an existing patched file instead of creating one.");
1107 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -07001108 UsageError(" --dump-timings: dump out patch timing information");
1109 UsageError("");
1110 UsageError(" --no-dump-timings: do not dump out patch timing information");
1111 UsageError("");
1112
1113 exit(EXIT_FAILURE);
1114}
1115
Chris Morin754b7572018-01-19 18:04:46 -08001116static int patchoat_patch_image(TimingLogger& timings,
1117 InstructionSet isa,
1118 const std::string& input_image_location,
1119 const std::string& output_image_directory,
Chris Morin88c6d262018-02-13 15:26:21 -08001120 const std::string& output_image_relocation_directory,
Chris Morin754b7572018-01-19 18:04:46 -08001121 off_t base_delta,
1122 bool base_delta_set,
1123 bool debug) {
Andreas Gampe6eb6a392016-02-10 20:18:37 -08001124 CHECK(!input_image_location.empty());
Chris Morin88c6d262018-02-13 15:26:21 -08001125 if ((output_image_directory.empty()) && (output_image_relocation_directory.empty())) {
1126 Usage("Image patching requires --output-image-directory or --output-image-relocation-directory");
Andreas Gampe6eb6a392016-02-10 20:18:37 -08001127 }
1128
1129 if (!base_delta_set) {
1130 Usage("Must supply a desired new offset or delta.");
1131 }
1132
1133 if (!IsAligned<kPageSize>(base_delta)) {
1134 Usage("Base offset/delta must be aligned to a pagesize (0x%08x) boundary.", kPageSize);
1135 }
1136
1137 if (debug) {
1138 LOG(INFO) << "moving offset by " << base_delta
1139 << " (0x" << std::hex << base_delta << ") bytes or "
1140 << std::dec << (base_delta/kPageSize) << " pages.";
1141 }
1142
1143 TimingLogger::ScopedTiming pt("patch image and oat", &timings);
1144
Alex Klyubin3856af02017-10-23 13:53:13 -07001145 bool ret =
1146 PatchOat::Patch(
1147 input_image_location,
1148 base_delta,
1149 output_image_directory,
1150 output_image_relocation_directory,
1151 isa,
1152 &timings);
Andreas Gampe6eb6a392016-02-10 20:18:37 -08001153
1154 if (kIsDebugBuild) {
1155 LOG(INFO) << "Exiting with return ... " << ret;
1156 }
1157 return ret ? EXIT_SUCCESS : EXIT_FAILURE;
1158}
1159
Chris Morin754b7572018-01-19 18:04:46 -08001160static int patchoat_verify_image(TimingLogger& timings,
1161 InstructionSet isa,
1162 const std::string& input_image_location,
1163 const std::string& output_image_directory) {
1164 CHECK(!input_image_location.empty());
1165 TimingLogger::ScopedTiming pt("verify image and oat", &timings);
1166
1167 bool ret =
1168 PatchOat::Verify(
1169 input_image_location,
1170 output_image_directory,
1171 isa,
1172 &timings);
1173
1174 if (kIsDebugBuild) {
1175 LOG(INFO) << "Exiting with return ... " << ret;
1176 }
1177 return ret ? EXIT_SUCCESS : EXIT_FAILURE;
1178}
1179
Alex Lighteefbe392014-07-08 09:53:18 -07001180static int patchoat(int argc, char **argv) {
David Sehrc431b9d2018-03-02 12:01:51 -08001181 Locks::Init();
Andreas Gampe51d80cc2017-06-21 21:05:13 -07001182 InitLogging(argv, Runtime::Abort);
Mathieu Chartier6e88ef62014-10-14 15:01:24 -07001183 MemMap::Init();
Alex Light53cb16b2014-06-12 11:26:29 -07001184 const bool debug = kIsDebugBuild;
1185 orig_argc = argc;
1186 orig_argv = argv;
1187 TimingLogger timings("patcher", false, false);
1188
Alex Light53cb16b2014-06-12 11:26:29 -07001189 // Skip over the command name.
1190 argv++;
1191 argc--;
1192
1193 if (argc == 0) {
1194 Usage("No arguments specified");
1195 }
1196
1197 timings.StartTiming("Patchoat");
1198
1199 // cmd line args
1200 bool isa_set = false;
Vladimir Marko33bff252017-11-01 14:35:42 +00001201 InstructionSet isa = InstructionSet::kNone;
Alex Light53cb16b2014-06-12 11:26:29 -07001202 std::string input_image_location;
Chris Morin88c6d262018-02-13 15:26:21 -08001203 std::string output_image_directory;
1204 std::string output_image_relocation_directory;
Alex Light53cb16b2014-06-12 11:26:29 -07001205 off_t base_delta = 0;
1206 bool base_delta_set = false;
Alex Light53cb16b2014-06-12 11:26:29 -07001207 bool dump_timings = kIsDebugBuild;
Chris Morin754b7572018-01-19 18:04:46 -08001208 bool verify = false;
Alex Light53cb16b2014-06-12 11:26:29 -07001209
Ian Rogersd4c4d952014-10-16 20:31:53 -07001210 for (int i = 0; i < argc; ++i) {
Alex Light53cb16b2014-06-12 11:26:29 -07001211 const StringPiece option(argv[i]);
1212 const bool log_options = false;
1213 if (log_options) {
1214 LOG(INFO) << "patchoat: option[" << i << "]=" << argv[i];
1215 }
Alex Light53cb16b2014-06-12 11:26:29 -07001216 if (option.starts_with("--instruction-set=")) {
1217 isa_set = true;
1218 const char* isa_str = option.substr(strlen("--instruction-set=")).data();
Andreas Gampe20c89302014-08-19 17:28:06 -07001219 isa = GetInstructionSetFromString(isa_str);
Vladimir Marko33bff252017-11-01 14:35:42 +00001220 if (isa == InstructionSet::kNone) {
Andreas Gampe20c89302014-08-19 17:28:06 -07001221 Usage("Unknown or invalid instruction set %s", isa_str);
Alex Light53cb16b2014-06-12 11:26:29 -07001222 }
Alex Light53cb16b2014-06-12 11:26:29 -07001223 } else if (option.starts_with("--input-image-location=")) {
1224 input_image_location = option.substr(strlen("--input-image-location=")).data();
Chris Morin88c6d262018-02-13 15:26:21 -08001225 } else if (option.starts_with("--output-image-directory=")) {
1226 output_image_directory = option.substr(strlen("--output-image-directory=")).data();
1227 } else if (option.starts_with("--output-image-relocation-directory=")) {
1228 output_image_relocation_directory =
1229 option.substr(strlen("--output-image-relocation-directory=")).data();
Alex Light53cb16b2014-06-12 11:26:29 -07001230 } else if (option.starts_with("--base-offset-delta=")) {
1231 const char* base_delta_str = option.substr(strlen("--base-offset-delta=")).data();
1232 base_delta_set = true;
1233 if (!ParseInt(base_delta_str, &base_delta)) {
1234 Usage("Failed to parse --base-offset-delta argument '%s' as an off_t", base_delta_str);
1235 }
Alex Light53cb16b2014-06-12 11:26:29 -07001236 } else if (option == "--dump-timings") {
1237 dump_timings = true;
1238 } else if (option == "--no-dump-timings") {
1239 dump_timings = false;
Chris Morin754b7572018-01-19 18:04:46 -08001240 } else if (option == "--verify") {
1241 verify = true;
Alex Light53cb16b2014-06-12 11:26:29 -07001242 } else {
1243 Usage("Unknown argument %s", option.data());
1244 }
1245 }
1246
Andreas Gampe6eb6a392016-02-10 20:18:37 -08001247 // The instruction set is mandatory. This simplifies things...
1248 if (!isa_set) {
1249 Usage("Instruction set must be set.");
Alex Light53cb16b2014-06-12 11:26:29 -07001250 }
1251
Chris Morin754b7572018-01-19 18:04:46 -08001252 int ret;
1253 if (verify) {
1254 ret = patchoat_verify_image(timings,
1255 isa,
1256 input_image_location,
1257 output_image_directory);
1258 } else {
1259 ret = patchoat_patch_image(timings,
1260 isa,
1261 input_image_location,
1262 output_image_directory,
Chris Morin88c6d262018-02-13 15:26:21 -08001263 output_image_relocation_directory,
Chris Morin754b7572018-01-19 18:04:46 -08001264 base_delta,
1265 base_delta_set,
1266 debug);
1267 }
Alex Light53cb16b2014-06-12 11:26:29 -07001268
Andreas Gampe6eb6a392016-02-10 20:18:37 -08001269 timings.EndTiming();
1270 if (dump_timings) {
1271 LOG(INFO) << Dumpable<TimingLogger>(timings);
Alex Light53cb16b2014-06-12 11:26:29 -07001272 }
1273
Andreas Gampe6eb6a392016-02-10 20:18:37 -08001274 return ret;
Alex Light53cb16b2014-06-12 11:26:29 -07001275}
1276
1277} // namespace art
1278
1279int main(int argc, char **argv) {
1280 return art::patchoat(argc, argv);
1281}