blob: 6c9cf864b3e99da3e1913d1ba778e7a34b2c0c1b [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 Klyubinfbe5f2f2017-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
Andreas Gampe46ee31b2016-12-14 10:11:49 -080028#include "android-base/stringprintf.h"
Andreas Gampe9186ced2016-12-12 14:28:21 -080029#include "android-base/strings.h"
30
Mathieu Chartierc7853442015-03-27 14:35:38 -070031#include "art_field-inl.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070032#include "art_method-inl.h"
Ian Rogersc7dd2952014-10-21 23:31:19 -070033#include "base/dumpable.h"
Andreas Gampe170331f2017-12-07 18:41:03 -080034#include "base/logging.h" // For InitLogging.
Andreas Gampeb8cc1752017-04-26 21:28:50 -070035#include "base/memory_tool.h"
Alex Lighta59dd802014-07-02 16:28:08 -070036#include "base/scoped_flock.h"
Alex Light53cb16b2014-06-12 11:26:29 -070037#include "base/stringpiece.h"
Ian Rogersd4c4d952014-10-16 20:31:53 -070038#include "base/unix_file/fd_file.h"
David Brazdil7b49e6c2016-09-01 11:06:18 +010039#include "base/unix_file/random_access_file_utils.h"
Alex Light53cb16b2014-06-12 11:26:29 -070040#include "elf_file.h"
Tong Shen62d1ca32014-09-03 17:24:56 -070041#include "elf_file_impl.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070042#include "elf_utils.h"
Ian Rogerse63db272014-07-15 15:36:11 -070043#include "gc/space/image_space.h"
Mathieu Chartier4a26f172016-01-26 14:26:18 -080044#include "image-inl.h"
Andreas Gampeb2d18fa2017-06-06 20:46:10 -070045#include "intern_table.h"
Alex Klyubinfbe5f2f2017-10-23 13:53:13 -070046#include "leb128.h"
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -070047#include "mirror/dex_cache.h"
Neil Fuller0e844392016-09-08 13:43:31 +010048#include "mirror/executable.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070049#include "mirror/method.h"
Alex Light53cb16b2014-06-12 11:26:29 -070050#include "mirror/object-inl.h"
Andreas Gampec6ea7d02017-02-01 16:46:28 -080051#include "mirror/object-refvisitor-inl.h"
Alex Light53cb16b2014-06-12 11:26:29 -070052#include "mirror/reference.h"
53#include "noop_compiler_callbacks.h"
54#include "offsets.h"
55#include "os.h"
56#include "runtime.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070057#include "scoped_thread_state_change-inl.h"
Alex Light53cb16b2014-06-12 11:26:29 -070058#include "thread.h"
59#include "utils.h"
60
61namespace art {
62
Alex Klyubinfbe5f2f2017-10-23 13:53:13 -070063using android::base::StringPrintf;
64
Alex Light0eb76d22015-08-11 18:03:47 -070065static const OatHeader* GetOatHeader(const ElfFile* elf_file) {
66 uint64_t off = 0;
67 if (!elf_file->GetSectionOffsetAndSize(".rodata", &off, nullptr)) {
68 return nullptr;
69 }
70
71 OatHeader* oat_header = reinterpret_cast<OatHeader*>(elf_file->Begin() + off);
72 return oat_header;
73}
74
Richard Uhler4bc11d02017-02-01 09:53:54 +000075static File* CreateOrOpen(const char* name) {
Jeff Haodcdc85b2015-12-04 14:06:18 -080076 if (OS::FileExists(name)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -080077 return OS::OpenFileReadWrite(name);
78 } else {
Jeff Haodcdc85b2015-12-04 14:06:18 -080079 std::unique_ptr<File> f(OS::CreateEmptyFile(name));
80 if (f.get() != nullptr) {
81 if (fchmod(f->Fd(), 0644) != 0) {
82 PLOG(ERROR) << "Unable to make " << name << " world readable";
Dimitry Ivanov7a1c0142016-03-17 15:59:38 -070083 unlink(name);
Jeff Haodcdc85b2015-12-04 14:06:18 -080084 return nullptr;
85 }
86 }
87 return f.release();
88 }
89}
90
91// Either try to close the file (close=true), or erase it.
92static bool FinishFile(File* file, bool close) {
93 if (close) {
94 if (file->FlushCloseOrErase() != 0) {
95 PLOG(ERROR) << "Failed to flush and close file.";
96 return false;
97 }
98 return true;
99 } else {
100 file->Erase();
101 return false;
102 }
103}
104
David Brazdil7b49e6c2016-09-01 11:06:18 +0100105static bool SymlinkFile(const std::string& input_filename, const std::string& output_filename) {
106 if (input_filename == output_filename) {
107 // Input and output are the same, nothing to do.
108 return true;
109 }
110
111 // Unlink the original filename, since we are overwriting it.
112 unlink(output_filename.c_str());
113
114 // Create a symlink from the source file to the target path.
115 if (symlink(input_filename.c_str(), output_filename.c_str()) < 0) {
116 PLOG(ERROR) << "Failed to create symlink " << output_filename << " -> " << input_filename;
117 return false;
118 }
119
120 if (kIsDebugBuild) {
121 LOG(INFO) << "Created symlink " << output_filename << " -> " << input_filename;
122 }
123
124 return true;
125}
126
Alex Klyubinfbe5f2f2017-10-23 13:53:13 -0700127bool PatchOat::GeneratePatch(
128 const MemMap& original,
129 const MemMap& relocated,
130 std::vector<uint8_t>* output,
131 std::string* error_msg) {
132 // FORMAT of the patch (aka image relocation) file:
133 // * SHA-256 digest (32 bytes) of original/unrelocated file (e.g., the one from /system)
134 // * List of monotonically increasing offsets (max value defined by uint32_t) at which relocations
135 // occur.
136 // Each element is represented as the delta from the previous offset in the list (first element
137 // is a delta from 0). Each delta is encoded using unsigned LEB128: little-endian
138 // variable-length 7 bits per byte encoding, where all bytes have the highest bit (0x80) set
139 // except for the final byte which does not have that bit set. For example, 0x3f is offset 0x3f,
140 // whereas 0xbf 0x05 is offset (0x3f & 0x7f) | (0x5 << 7) which is 0x2bf. Most deltas end up
141 // being encoding using just one byte, achieving ~4x decrease in relocation file size compared
142 // to the encoding where offsets are stored verbatim, as uint32_t.
143
144 size_t original_size = original.Size();
145 size_t relocated_size = relocated.Size();
146 if (original_size != relocated_size) {
147 *error_msg =
148 StringPrintf(
149 "Original and relocated image sizes differ: %zu vs %zu", original_size, relocated_size);
150 return false;
151 }
152 if ((original_size % 4) != 0) {
153 *error_msg = StringPrintf("Image size not multiple of 4: %zu", original_size);
154 return false;
155 }
156 if (original_size > UINT32_MAX) {
157 *error_msg = StringPrintf("Image too large: %zu" , original_size);
158 return false;
159 }
160
161 const ImageHeader& relocated_header =
162 *reinterpret_cast<const ImageHeader*>(relocated.Begin());
163 // Offsets are supposed to differ between original and relocated by this value
164 off_t expected_diff = relocated_header.GetPatchDelta();
165 if (expected_diff == 0) {
166 // Can't identify offsets which are supposed to differ due to relocation
167 *error_msg = "Relocation delta is 0";
168 return false;
169 }
170
171 // Output the SHA-256 digest of the original
172 output->resize(SHA256_DIGEST_LENGTH);
173 const uint8_t* original_bytes = original.Begin();
174 SHA256(original_bytes, original_size, output->data());
175
176 // Output the list of offsets at which the original and patched images differ
177 size_t last_diff_offset = 0;
178 size_t diff_offset_count = 0;
179 const uint8_t* relocated_bytes = relocated.Begin();
180 for (size_t offset = 0; offset < original_size; offset += 4) {
181 uint32_t original_value = *reinterpret_cast<const uint32_t*>(original_bytes + offset);
182 uint32_t relocated_value = *reinterpret_cast<const uint32_t*>(relocated_bytes + offset);
183 off_t diff = relocated_value - original_value;
184 if (diff == 0) {
185 continue;
186 } else if (diff != expected_diff) {
187 *error_msg =
188 StringPrintf(
189 "Unexpected diff at offset %zu. Expected: %jd, but was: %jd",
190 offset,
191 (intmax_t) expected_diff,
192 (intmax_t) diff);
193 return false;
194 }
195
196 uint32_t offset_diff = offset - last_diff_offset;
197 last_diff_offset = offset;
198 diff_offset_count++;
199
200 EncodeUnsignedLeb128(output, offset_diff);
201 }
202
203 if (diff_offset_count == 0) {
204 *error_msg = "Original and patched images are identical";
205 return false;
206 }
207
208 return true;
209}
210
211static bool WriteRelFile(
212 const MemMap& original,
213 const MemMap& relocated,
214 const std::string& rel_filename,
215 std::string* error_msg) {
216 std::vector<uint8_t> output;
217 if (!PatchOat::GeneratePatch(original, relocated, &output, error_msg)) {
218 return false;
219 }
220
221 std::unique_ptr<File> rel_file(OS::CreateEmptyFileWriteOnly(rel_filename.c_str()));
222 if (rel_file.get() == nullptr) {
223 *error_msg = StringPrintf("Failed to create/open output file %s", rel_filename.c_str());
224 return false;
225 }
226 if (!rel_file->WriteFully(output.data(), output.size())) {
227 *error_msg = StringPrintf("Failed to write to %s", rel_filename.c_str());
228 return false;
229 }
230 if (rel_file->FlushCloseOrErase() != 0) {
231 *error_msg = StringPrintf("Failed to flush and close %s", rel_filename.c_str());
232 return false;
233 }
234
235 return true;
236}
237
Andreas Gampe6eb6a392016-02-10 20:18:37 -0800238bool PatchOat::Patch(const std::string& image_location,
239 off_t delta,
Alex Klyubinfbe5f2f2017-10-23 13:53:13 -0700240 const std::string& output_image_directory,
241 const std::string& output_image_relocation_directory,
Andreas Gampe6eb6a392016-02-10 20:18:37 -0800242 InstructionSet isa,
243 TimingLogger* timings) {
Alex Klyubinfbe5f2f2017-10-23 13:53:13 -0700244 bool output_image = !output_image_directory.empty();
245 bool output_image_relocation = !output_image_relocation_directory.empty();
246 if ((!output_image) && (!output_image_relocation)) {
247 // Nothing to do
248 return true;
249 }
250 if ((output_image_relocation) && (delta == 0)) {
251 LOG(ERROR) << "Cannot output image relocation information when requested relocation delta is 0";
252 return false;
253 }
254
Alex Light53cb16b2014-06-12 11:26:29 -0700255 CHECK(Runtime::Current() == nullptr);
Alex Light53cb16b2014-06-12 11:26:29 -0700256 CHECK(!image_location.empty()) << "image file must have a filename.";
257
Alex Lighteefbe392014-07-08 09:53:18 -0700258 TimingLogger::ScopedTiming t("Runtime Setup", timings);
Alex Light53cb16b2014-06-12 11:26:29 -0700259
Vladimir Marko33bff252017-11-01 14:35:42 +0000260 CHECK_NE(isa, InstructionSet::kNone);
Alex Light53cb16b2014-06-12 11:26:29 -0700261 const char* isa_name = GetInstructionSetString(isa);
Igor Murashkin46774762014-10-22 11:37:02 -0700262
Alex Light53cb16b2014-06-12 11:26:29 -0700263 // Set up the runtime
Ian Rogerse63db272014-07-15 15:36:11 -0700264 RuntimeOptions options;
Alex Light53cb16b2014-06-12 11:26:29 -0700265 NoopCompilerCallbacks callbacks;
266 options.push_back(std::make_pair("compilercallbacks", &callbacks));
267 std::string img = "-Ximage:" + image_location;
268 options.push_back(std::make_pair(img.c_str(), nullptr));
269 options.push_back(std::make_pair("imageinstructionset", reinterpret_cast<const void*>(isa_name)));
Calin Juravle01aaf6e2015-06-19 22:05:39 +0100270 options.push_back(std::make_pair("-Xno-sig-chain", nullptr));
Alex Light53cb16b2014-06-12 11:26:29 -0700271 if (!Runtime::Create(options, false)) {
272 LOG(ERROR) << "Unable to initialize runtime";
273 return false;
274 }
Andreas Gampeb8cc1752017-04-26 21:28:50 -0700275 std::unique_ptr<Runtime> runtime(Runtime::Current());
276
Alex Light53cb16b2014-06-12 11:26:29 -0700277 // Runtime::Create acquired the mutator_lock_ that is normally given away when we Runtime::Start,
278 // give it away now and then switch to a more manageable ScopedObjectAccess.
279 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
280 ScopedObjectAccess soa(Thread::Current());
281
Richard Uhler4bc11d02017-02-01 09:53:54 +0000282 t.NewTiming("Image Patching setup");
Jeff Haodcdc85b2015-12-04 14:06:18 -0800283 std::vector<gc::space::ImageSpace*> spaces = Runtime::Current()->GetHeap()->GetBootImageSpaces();
284 std::map<gc::space::ImageSpace*, std::unique_ptr<File>> space_to_file_map;
285 std::map<gc::space::ImageSpace*, std::unique_ptr<MemMap>> space_to_memmap_map;
286 std::map<gc::space::ImageSpace*, PatchOat> space_to_patchoat_map;
Alex Light53cb16b2014-06-12 11:26:29 -0700287
Jeff Haodcdc85b2015-12-04 14:06:18 -0800288 for (size_t i = 0; i < spaces.size(); ++i) {
289 gc::space::ImageSpace* space = spaces[i];
290 std::string input_image_filename = space->GetImageFilename();
291 std::unique_ptr<File> input_image(OS::OpenFileForReading(input_image_filename.c_str()));
292 if (input_image.get() == nullptr) {
293 LOG(ERROR) << "Unable to open input image file at " << input_image_filename;
Igor Murashkin46774762014-10-22 11:37:02 -0700294 return false;
295 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800296
297 int64_t image_len = input_image->GetLength();
298 if (image_len < 0) {
299 LOG(ERROR) << "Error while getting image length";
300 return false;
301 }
302 ImageHeader image_header;
303 if (sizeof(image_header) != input_image->Read(reinterpret_cast<char*>(&image_header),
304 sizeof(image_header), 0)) {
305 LOG(ERROR) << "Unable to read image header from image file " << input_image->GetPath();
306 }
307
308 /*bool is_image_pic = */IsImagePic(image_header, input_image->GetPath());
309 // Nothing special to do right now since the image always needs to get patched.
310 // Perhaps in some far-off future we may have images with relative addresses that are true-PIC.
311
312 // Create the map where we will write the image patches to.
313 std::string error_msg;
314 std::unique_ptr<MemMap> image(MemMap::MapFile(image_len,
315 PROT_READ | PROT_WRITE,
316 MAP_PRIVATE,
317 input_image->Fd(),
318 0,
319 /*low_4gb*/false,
320 input_image->GetPath().c_str(),
321 &error_msg));
322 if (image.get() == nullptr) {
323 LOG(ERROR) << "Unable to map image file " << input_image->GetPath() << " : " << error_msg;
324 return false;
325 }
326 space_to_file_map.emplace(space, std::move(input_image));
327 space_to_memmap_map.emplace(space, std::move(image));
Igor Murashkin46774762014-10-22 11:37:02 -0700328 }
329
Richard Uhler4bc11d02017-02-01 09:53:54 +0000330 // Symlink PIC oat and vdex files and patch the image spaces in memory.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800331 for (size_t i = 0; i < spaces.size(); ++i) {
332 gc::space::ImageSpace* space = spaces[i];
333 std::string input_image_filename = space->GetImageFilename();
David Brazdil7b49e6c2016-09-01 11:06:18 +0100334 std::string input_vdex_filename =
335 ImageHeader::GetVdexLocationFromImageLocation(input_image_filename);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800336 std::string input_oat_filename =
337 ImageHeader::GetOatLocationFromImageLocation(input_image_filename);
338 std::unique_ptr<File> input_oat_file(OS::OpenFileForReading(input_oat_filename.c_str()));
339 if (input_oat_file.get() == nullptr) {
340 LOG(ERROR) << "Unable to open input oat file at " << input_oat_filename;
341 return false;
342 }
343 std::string error_msg;
344 std::unique_ptr<ElfFile> elf(ElfFile::Open(input_oat_file.get(),
345 PROT_READ | PROT_WRITE, MAP_PRIVATE, &error_msg));
346 if (elf.get() == nullptr) {
347 LOG(ERROR) << "Unable to open oat file " << input_oat_file->GetPath() << " : " << error_msg;
348 return false;
349 }
350
Alex Klyubinfbe5f2f2017-10-23 13:53:13 -0700351 if (output_image) {
352 MaybePic is_oat_pic = IsOatPic(elf.get());
353 if (is_oat_pic >= ERROR_FIRST) {
354 // Error logged by IsOatPic
Jeff Haodcdc85b2015-12-04 14:06:18 -0800355 return false;
Alex Klyubinfbe5f2f2017-10-23 13:53:13 -0700356 } else if (is_oat_pic == NOT_PIC) {
357 LOG(ERROR) << "patchoat cannot be used on non-PIC oat file: " << input_oat_file->GetPath();
358 return false;
359 } else {
360 CHECK(is_oat_pic == PIC);
361
362 // Create a symlink.
363 std::string converted_image_filename = space->GetImageLocation();
364 std::replace(
365 converted_image_filename.begin() + 1, converted_image_filename.end(), '/', '@');
366 std::string output_image_filename = output_image_directory +
367 (android::base::StartsWith(converted_image_filename, "/") ? "" : "/") +
368 converted_image_filename;
369 std::string output_vdex_filename =
370 ImageHeader::GetVdexLocationFromImageLocation(output_image_filename);
371 std::string output_oat_filename =
372 ImageHeader::GetOatLocationFromImageLocation(output_image_filename);
373
374 if (!ReplaceOatFileWithSymlink(input_oat_file->GetPath(),
375 output_oat_filename) ||
376 !SymlinkFile(input_vdex_filename, output_vdex_filename)) {
377 // Errors already logged by above call.
378 return false;
379 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800380 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800381 }
382
383 PatchOat& p = space_to_patchoat_map.emplace(space,
384 PatchOat(
385 isa,
Jeff Haodcdc85b2015-12-04 14:06:18 -0800386 space_to_memmap_map.find(space)->second.get(),
387 space->GetLiveBitmap(),
388 space->GetMemMap(),
389 delta,
390 &space_to_memmap_map,
391 timings)).first->second;
392
Richard Uhler4bc11d02017-02-01 09:53:54 +0000393 t.NewTiming("Patching image");
Jeff Haodcdc85b2015-12-04 14:06:18 -0800394 if (!p.PatchImage(i == 0)) {
395 LOG(ERROR) << "Failed to patch image file " << input_image_filename;
396 return false;
397 }
Alex Light53cb16b2014-06-12 11:26:29 -0700398 }
399
Alex Klyubinfbe5f2f2017-10-23 13:53:13 -0700400 if (output_image) {
401 // Write the patched image spaces.
402 for (size_t i = 0; i < spaces.size(); ++i) {
403 gc::space::ImageSpace* space = spaces[i];
Jeff Haodcdc85b2015-12-04 14:06:18 -0800404
Alex Klyubinfbe5f2f2017-10-23 13:53:13 -0700405 t.NewTiming("Writing image");
406 std::string converted_image_filename = space->GetImageLocation();
407 std::replace(converted_image_filename.begin() + 1, converted_image_filename.end(), '/', '@');
408 std::string output_image_filename = output_image_directory +
409 (android::base::StartsWith(converted_image_filename, "/") ? "" : "/") +
410 converted_image_filename;
411 std::unique_ptr<File> output_image_file(CreateOrOpen(output_image_filename.c_str()));
412 if (output_image_file.get() == nullptr) {
413 LOG(ERROR) << "Failed to open output image file at " << output_image_filename;
414 return false;
415 }
416
417 PatchOat& p = space_to_patchoat_map.find(space)->second;
418
419 bool success = p.WriteImage(output_image_file.get());
420 success = FinishFile(output_image_file.get(), success);
421 if (!success) {
422 return false;
423 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800424 }
Alex Klyubinfbe5f2f2017-10-23 13:53:13 -0700425 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800426
Alex Klyubinfbe5f2f2017-10-23 13:53:13 -0700427 if (output_image_relocation) {
428 // Write the image relocation information for each space.
429 for (size_t i = 0; i < spaces.size(); ++i) {
430 gc::space::ImageSpace* space = spaces[i];
Jeff Haodcdc85b2015-12-04 14:06:18 -0800431
Alex Klyubinfbe5f2f2017-10-23 13:53:13 -0700432 t.NewTiming("Writing image relocation");
433 std::string original_image_filename(space->GetImageLocation() + ".rel");
434 std::string image_relocation_filename =
435 output_image_relocation_directory
436 + (android::base::StartsWith(original_image_filename, "/") ? "" : "/")
437 + original_image_filename.substr(original_image_filename.find_last_of("/"));
438 File& input_image = *space_to_file_map.find(space)->second;
439 int64_t input_image_size = input_image.GetLength();
440 if (input_image_size < 0) {
441 LOG(ERROR) << "Error while getting input image size";
442 return false;
443 }
444 std::string error_msg;
445 std::unique_ptr<MemMap> original(MemMap::MapFile(input_image_size,
446 PROT_READ,
447 MAP_PRIVATE,
448 input_image.Fd(),
449 0,
450 /*low_4gb*/false,
451 input_image.GetPath().c_str(),
452 &error_msg));
453 if (original.get() == nullptr) {
454 LOG(ERROR) << "Unable to map image file " << input_image.GetPath() << " : " << error_msg;
455 return false;
456 }
457
458 PatchOat& p = space_to_patchoat_map.find(space)->second;
459 const MemMap* relocated = p.image_;
460
461 if (!WriteRelFile(*original, *relocated, image_relocation_filename, &error_msg)) {
462 LOG(ERROR) << "Failed to create image relocation file " << image_relocation_filename
463 << ": " << error_msg;
464 return false;
465 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800466 }
Alex Light53cb16b2014-06-12 11:26:29 -0700467 }
Andreas Gampeb8cc1752017-04-26 21:28:50 -0700468
469 if (!kIsDebugBuild && !(RUNNING_ON_MEMORY_TOOL && kMemoryToolDetectsLeaks)) {
470 // We want to just exit on non-debug builds, not bringing the runtime down
471 // in an orderly fashion. So release the following fields.
472 runtime.release();
473 }
474
Alex Light53cb16b2014-06-12 11:26:29 -0700475 return true;
476}
477
Alex Light53cb16b2014-06-12 11:26:29 -0700478bool PatchOat::WriteImage(File* out) {
Alex Lighteefbe392014-07-08 09:53:18 -0700479 TimingLogger::ScopedTiming t("Writing image File", timings_);
Alex Lighta59dd802014-07-02 16:28:08 -0700480 std::string error_msg;
481
Narayan Kamatha3d27eb2017-05-11 13:50:59 +0100482 // No error checking here, this is best effort. The locking may or may not
483 // succeed and we don't really care either way.
484 ScopedFlock img_flock = LockedFile::DupOf(out->Fd(), out->GetPath(),
485 true /* read_only_mode */, &error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -0700486
Alex Light53cb16b2014-06-12 11:26:29 -0700487 CHECK(image_ != nullptr);
488 CHECK(out != nullptr);
489 size_t expect = image_->Size();
490 if (out->WriteFully(reinterpret_cast<char*>(image_->Begin()), expect) &&
491 out->SetLength(expect) == 0) {
492 return true;
493 } else {
494 LOG(ERROR) << "Writing to image file " << out->GetPath() << " failed.";
495 return false;
496 }
497}
498
Igor Murashkin46774762014-10-22 11:37:02 -0700499bool PatchOat::IsImagePic(const ImageHeader& image_header, const std::string& image_path) {
500 if (!image_header.CompilePic()) {
501 if (kIsDebugBuild) {
502 LOG(INFO) << "image at location " << image_path << " was *not* compiled pic";
503 }
504 return false;
505 }
506
507 if (kIsDebugBuild) {
508 LOG(INFO) << "image at location " << image_path << " was compiled PIC";
509 }
510
511 return true;
512}
513
514PatchOat::MaybePic PatchOat::IsOatPic(const ElfFile* oat_in) {
515 if (oat_in == nullptr) {
516 LOG(ERROR) << "No ELF input oat fie available";
517 return ERROR_OAT_FILE;
518 }
519
Brian Carlstromf5b0f2c2016-10-14 01:04:26 -0700520 const std::string& file_path = oat_in->GetFilePath();
Igor Murashkin46774762014-10-22 11:37:02 -0700521
522 const OatHeader* oat_header = GetOatHeader(oat_in);
523 if (oat_header == nullptr) {
524 LOG(ERROR) << "Failed to find oat header in oat file " << file_path;
525 return ERROR_OAT_FILE;
526 }
527
528 if (!oat_header->IsValid()) {
529 LOG(ERROR) << "Elf file " << file_path << " has an invalid oat header";
530 return ERROR_OAT_FILE;
531 }
532
533 bool is_pic = oat_header->IsPic();
534 if (kIsDebugBuild) {
535 LOG(INFO) << "Oat file at " << file_path << " is " << (is_pic ? "PIC" : "not pic");
536 }
537
538 return is_pic ? PIC : NOT_PIC;
539}
540
541bool PatchOat::ReplaceOatFileWithSymlink(const std::string& input_oat_filename,
Richard Uhler4bc11d02017-02-01 09:53:54 +0000542 const std::string& output_oat_filename) {
Igor Murashkin46774762014-10-22 11:37:02 -0700543 // Delete the original file, since we won't need it.
Dimitry Ivanov7a1c0142016-03-17 15:59:38 -0700544 unlink(output_oat_filename.c_str());
Igor Murashkin46774762014-10-22 11:37:02 -0700545
546 // Create a symlink from the old oat to the new oat
547 if (symlink(input_oat_filename.c_str(), output_oat_filename.c_str()) < 0) {
548 int err = errno;
549 LOG(ERROR) << "Failed to create symlink at " << output_oat_filename
550 << " error(" << err << "): " << strerror(err);
551 return false;
552 }
553
554 if (kIsDebugBuild) {
555 LOG(INFO) << "Created symlink " << output_oat_filename << " -> " << input_oat_filename;
556 }
557
558 return true;
559}
560
Vladimir Markoad06b982016-11-17 16:38:59 +0000561class PatchOat::PatchOatArtFieldVisitor : public ArtFieldVisitor {
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700562 public:
563 explicit PatchOatArtFieldVisitor(PatchOat* patch_oat) : patch_oat_(patch_oat) {}
564
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700565 void Visit(ArtField* field) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700566 ArtField* const dest = patch_oat_->RelocatedCopyOf(field);
Mathieu Chartier3398c782016-09-30 10:27:43 -0700567 dest->SetDeclaringClass(
Mathieu Chartier1cc62e42016-10-03 18:01:28 -0700568 patch_oat_->RelocatedAddressOfPointer(field->GetDeclaringClass().Ptr()));
Mathieu Chartiere401d142015-04-22 13:56:20 -0700569 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700570
571 private:
572 PatchOat* const patch_oat_;
573};
574
575void PatchOat::PatchArtFields(const ImageHeader* image_header) {
576 PatchOatArtFieldVisitor visitor(this);
Mathieu Chartiere42888f2016-04-14 10:49:19 -0700577 image_header->VisitPackedArtFields(&visitor, heap_->Begin());
Mathieu Chartiere401d142015-04-22 13:56:20 -0700578}
579
Vladimir Markoad06b982016-11-17 16:38:59 +0000580class PatchOat::PatchOatArtMethodVisitor : public ArtMethodVisitor {
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700581 public:
582 explicit PatchOatArtMethodVisitor(PatchOat* patch_oat) : patch_oat_(patch_oat) {}
583
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700584 void Visit(ArtMethod* method) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700585 ArtMethod* const dest = patch_oat_->RelocatedCopyOf(method);
586 patch_oat_->FixupMethod(method, dest);
587 }
588
589 private:
590 PatchOat* const patch_oat_;
591};
592
Mathieu Chartiere401d142015-04-22 13:56:20 -0700593void PatchOat::PatchArtMethods(const ImageHeader* image_header) {
Andreas Gampe542451c2016-07-26 09:02:02 -0700594 const PointerSize pointer_size = InstructionSetPointerSize(isa_);
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700595 PatchOatArtMethodVisitor visitor(this);
Mathieu Chartiere42888f2016-04-14 10:49:19 -0700596 image_header->VisitPackedArtMethods(&visitor, heap_->Begin(), pointer_size);
597}
598
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +0000599void PatchOat::PatchImTables(const ImageHeader* image_header) {
Andreas Gampe542451c2016-07-26 09:02:02 -0700600 const PointerSize pointer_size = InstructionSetPointerSize(isa_);
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +0000601 // We can safely walk target image since the conflict tables are independent.
602 image_header->VisitPackedImTables(
603 [this](ArtMethod* method) {
604 return RelocatedAddressOfPointer(method);
605 },
606 image_->Begin(),
607 pointer_size);
608}
609
Mathieu Chartiere42888f2016-04-14 10:49:19 -0700610void PatchOat::PatchImtConflictTables(const ImageHeader* image_header) {
Andreas Gampe542451c2016-07-26 09:02:02 -0700611 const PointerSize pointer_size = InstructionSetPointerSize(isa_);
Mathieu Chartiere42888f2016-04-14 10:49:19 -0700612 // We can safely walk target image since the conflict tables are independent.
613 image_header->VisitPackedImtConflictTables(
614 [this](ArtMethod* method) {
615 return RelocatedAddressOfPointer(method);
616 },
617 image_->Begin(),
618 pointer_size);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700619}
620
Vladimir Markoad06b982016-11-17 16:38:59 +0000621class PatchOat::FixupRootVisitor : public RootVisitor {
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700622 public:
623 explicit FixupRootVisitor(const PatchOat* patch_oat) : patch_oat_(patch_oat) {
624 }
625
626 void VisitRoots(mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700627 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700628 for (size_t i = 0; i < count; ++i) {
629 *roots[i] = patch_oat_->RelocatedAddressOfPointer(*roots[i]);
630 }
631 }
632
633 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots, size_t count,
634 const RootInfo& info ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700635 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700636 for (size_t i = 0; i < count; ++i) {
637 roots[i]->Assign(patch_oat_->RelocatedAddressOfPointer(roots[i]->AsMirrorPtr()));
638 }
639 }
640
641 private:
642 const PatchOat* const patch_oat_;
643};
644
645void PatchOat::PatchInternedStrings(const ImageHeader* image_header) {
Vladimir Markocd87c3e2017-09-05 13:11:57 +0100646 const auto& section = image_header->GetInternedStringsSection();
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100647 if (section.Size() == 0) {
648 return;
649 }
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700650 InternTable temp_table;
651 // Note that we require that ReadFromMemory does not make an internal copy of the elements.
652 // This also relies on visit roots not doing any verification which could fail after we update
653 // the roots to be the image addresses.
Mathieu Chartierea0831f2015-12-29 13:17:37 -0800654 temp_table.AddTableFromMemory(image_->Begin() + section.Offset());
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700655 FixupRootVisitor visitor(this);
656 temp_table.VisitRoots(&visitor, kVisitRootFlagAllRoots);
657}
658
Mathieu Chartier208a5cb2015-12-02 15:44:07 -0800659void PatchOat::PatchClassTable(const ImageHeader* image_header) {
Vladimir Markocd87c3e2017-09-05 13:11:57 +0100660 const auto& section = image_header->GetClassTableSection();
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800661 if (section.Size() == 0) {
662 return;
663 }
Mathieu Chartier208a5cb2015-12-02 15:44:07 -0800664 // Note that we require that ReadFromMemory does not make an internal copy of the elements.
665 // This also relies on visit roots not doing any verification which could fail after we update
666 // the roots to be the image addresses.
667 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
668 ClassTable temp_table;
669 temp_table.ReadFromMemory(image_->Begin() + section.Offset());
670 FixupRootVisitor visitor(this);
Mathieu Chartier58c3f6a2016-12-01 14:21:11 -0800671 temp_table.VisitRoots(UnbufferedRootVisitor(&visitor, RootInfo(kRootUnknown)));
Mathieu Chartier208a5cb2015-12-02 15:44:07 -0800672}
673
674
Vladimir Markoad06b982016-11-17 16:38:59 +0000675class PatchOat::RelocatedPointerVisitor {
Mathieu Chartier4b00d342015-11-13 10:42:08 -0800676 public:
677 explicit RelocatedPointerVisitor(PatchOat* patch_oat) : patch_oat_(patch_oat) {}
678
679 template <typename T>
Mathieu Chartier8c19d242017-03-06 12:35:10 -0800680 T* operator()(T* ptr, void** dest_addr ATTRIBUTE_UNUSED = 0) const {
Mathieu Chartier4b00d342015-11-13 10:42:08 -0800681 return patch_oat_->RelocatedAddressOfPointer(ptr);
682 }
683
684 private:
685 PatchOat* const patch_oat_;
686};
687
Mathieu Chartierc7853442015-03-27 14:35:38 -0700688void PatchOat::PatchDexFileArrays(mirror::ObjectArray<mirror::Object>* img_roots) {
689 auto* dex_caches = down_cast<mirror::ObjectArray<mirror::DexCache>*>(
690 img_roots->Get(ImageHeader::kDexCaches));
Andreas Gampe542451c2016-07-26 09:02:02 -0700691 const PointerSize pointer_size = InstructionSetPointerSize(isa_);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700692 for (size_t i = 0, count = dex_caches->GetLength(); i < count; ++i) {
Vladimir Marko05792b92015-08-03 11:56:49 +0100693 auto* orig_dex_cache = dex_caches->GetWithoutChecks(i);
694 auto* copy_dex_cache = RelocatedCopyOf(orig_dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +0100695 // Though the DexCache array fields are usually treated as native pointers, we set the full
696 // 64-bit values here, clearing the top 32 bits for 32-bit targets. The zero-extension is
697 // done by casting to the unsigned type uintptr_t before casting to int64_t, i.e.
698 // static_cast<int64_t>(reinterpret_cast<uintptr_t>(image_begin_ + offset))).
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -0700699 mirror::StringDexCacheType* orig_strings = orig_dex_cache->GetStrings();
700 mirror::StringDexCacheType* relocated_strings = RelocatedAddressOfPointer(orig_strings);
Vladimir Marko05792b92015-08-03 11:56:49 +0100701 copy_dex_cache->SetField64<false>(
702 mirror::DexCache::StringsOffset(),
703 static_cast<int64_t>(reinterpret_cast<uintptr_t>(relocated_strings)));
704 if (orig_strings != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -0800705 orig_dex_cache->FixupStrings(RelocatedCopyOf(orig_strings), RelocatedPointerVisitor(this));
Mathieu Chartierc7853442015-03-27 14:35:38 -0700706 }
Vladimir Marko8d6768d2017-03-14 10:13:21 +0000707 mirror::TypeDexCacheType* orig_types = orig_dex_cache->GetResolvedTypes();
708 mirror::TypeDexCacheType* relocated_types = RelocatedAddressOfPointer(orig_types);
Vladimir Marko05792b92015-08-03 11:56:49 +0100709 copy_dex_cache->SetField64<false>(
710 mirror::DexCache::ResolvedTypesOffset(),
711 static_cast<int64_t>(reinterpret_cast<uintptr_t>(relocated_types)));
712 if (orig_types != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -0800713 orig_dex_cache->FixupResolvedTypes(RelocatedCopyOf(orig_types),
714 RelocatedPointerVisitor(this));
Vladimir Marko05792b92015-08-03 11:56:49 +0100715 }
Vladimir Marko07bfbac2017-07-06 14:55:02 +0100716 mirror::MethodDexCacheType* orig_methods = orig_dex_cache->GetResolvedMethods();
717 mirror::MethodDexCacheType* relocated_methods = RelocatedAddressOfPointer(orig_methods);
Vladimir Marko05792b92015-08-03 11:56:49 +0100718 copy_dex_cache->SetField64<false>(
719 mirror::DexCache::ResolvedMethodsOffset(),
720 static_cast<int64_t>(reinterpret_cast<uintptr_t>(relocated_methods)));
721 if (orig_methods != nullptr) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +0100722 mirror::MethodDexCacheType* copy_methods = RelocatedCopyOf(orig_methods);
Vladimir Marko05792b92015-08-03 11:56:49 +0100723 for (size_t j = 0, num = orig_dex_cache->NumResolvedMethods(); j != num; ++j) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +0100724 mirror::MethodDexCachePair orig =
725 mirror::DexCache::GetNativePairPtrSize(orig_methods, j, pointer_size);
726 mirror::MethodDexCachePair copy(RelocatedAddressOfPointer(orig.object), orig.index);
727 mirror::DexCache::SetNativePairPtrSize(copy_methods, j, copy, pointer_size);
Vladimir Marko05792b92015-08-03 11:56:49 +0100728 }
729 }
Vladimir Markof44d36c2017-03-14 14:18:46 +0000730 mirror::FieldDexCacheType* orig_fields = orig_dex_cache->GetResolvedFields();
731 mirror::FieldDexCacheType* relocated_fields = RelocatedAddressOfPointer(orig_fields);
Vladimir Marko05792b92015-08-03 11:56:49 +0100732 copy_dex_cache->SetField64<false>(
733 mirror::DexCache::ResolvedFieldsOffset(),
734 static_cast<int64_t>(reinterpret_cast<uintptr_t>(relocated_fields)));
735 if (orig_fields != nullptr) {
Vladimir Markof44d36c2017-03-14 14:18:46 +0000736 mirror::FieldDexCacheType* copy_fields = RelocatedCopyOf(orig_fields);
Vladimir Marko05792b92015-08-03 11:56:49 +0100737 for (size_t j = 0, num = orig_dex_cache->NumResolvedFields(); j != num; ++j) {
Vladimir Markof44d36c2017-03-14 14:18:46 +0000738 mirror::FieldDexCachePair orig =
739 mirror::DexCache::GetNativePairPtrSize(orig_fields, j, pointer_size);
740 mirror::FieldDexCachePair copy(RelocatedAddressOfPointer(orig.object), orig.index);
741 mirror::DexCache::SetNativePairPtrSize(copy_fields, j, copy, pointer_size);
Vladimir Marko05792b92015-08-03 11:56:49 +0100742 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700743 }
Narayan Kamath7fe56582016-10-14 18:49:12 +0100744 mirror::MethodTypeDexCacheType* orig_method_types = orig_dex_cache->GetResolvedMethodTypes();
745 mirror::MethodTypeDexCacheType* relocated_method_types =
746 RelocatedAddressOfPointer(orig_method_types);
747 copy_dex_cache->SetField64<false>(
748 mirror::DexCache::ResolvedMethodTypesOffset(),
749 static_cast<int64_t>(reinterpret_cast<uintptr_t>(relocated_method_types)));
750 if (orig_method_types != nullptr) {
751 orig_dex_cache->FixupResolvedMethodTypes(RelocatedCopyOf(orig_method_types),
752 RelocatedPointerVisitor(this));
753 }
Orion Hodsonc069a302017-01-18 09:23:12 +0000754
755 GcRoot<mirror::CallSite>* orig_call_sites = orig_dex_cache->GetResolvedCallSites();
756 GcRoot<mirror::CallSite>* relocated_call_sites = RelocatedAddressOfPointer(orig_call_sites);
757 copy_dex_cache->SetField64<false>(
758 mirror::DexCache::ResolvedCallSitesOffset(),
759 static_cast<int64_t>(reinterpret_cast<uintptr_t>(relocated_call_sites)));
760 if (orig_call_sites != nullptr) {
761 orig_dex_cache->FixupResolvedCallSites(RelocatedCopyOf(orig_call_sites),
762 RelocatedPointerVisitor(this));
763 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700764 }
765}
766
Jeff Haodcdc85b2015-12-04 14:06:18 -0800767bool PatchOat::PatchImage(bool primary_image) {
Alex Light53cb16b2014-06-12 11:26:29 -0700768 ImageHeader* image_header = reinterpret_cast<ImageHeader*>(image_->Begin());
769 CHECK_GT(image_->Size(), sizeof(ImageHeader));
770 // These are the roots from the original file.
Mathieu Chartierc7853442015-03-27 14:35:38 -0700771 auto* img_roots = image_header->GetImageRoots();
Alex Light53cb16b2014-06-12 11:26:29 -0700772 image_header->RelocateImage(delta_);
773
Mathieu Chartierc7853442015-03-27 14:35:38 -0700774 PatchArtFields(image_header);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700775 PatchArtMethods(image_header);
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +0000776 PatchImTables(image_header);
Mathieu Chartiere42888f2016-04-14 10:49:19 -0700777 PatchImtConflictTables(image_header);
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700778 PatchInternedStrings(image_header);
Mathieu Chartier208a5cb2015-12-02 15:44:07 -0800779 PatchClassTable(image_header);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700780 // Patch dex file int/long arrays which point to ArtFields.
781 PatchDexFileArrays(img_roots);
782
Jeff Haodcdc85b2015-12-04 14:06:18 -0800783 if (primary_image) {
784 VisitObject(img_roots);
785 }
786
Alex Light53cb16b2014-06-12 11:26:29 -0700787 if (!image_header->IsValid()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800788 LOG(ERROR) << "relocation renders image header invalid";
Alex Light53cb16b2014-06-12 11:26:29 -0700789 return false;
790 }
791
792 {
Alex Lighteefbe392014-07-08 09:53:18 -0700793 TimingLogger::ScopedTiming t("Walk Bitmap", timings_);
Alex Light53cb16b2014-06-12 11:26:29 -0700794 // Walk the bitmap.
795 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
Andreas Gampe0c183382017-07-13 22:26:24 -0700796 auto visitor = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
797 VisitObject(obj);
798 };
799 bitmap_->Walk(visitor);
Alex Light53cb16b2014-06-12 11:26:29 -0700800 }
801 return true;
802}
803
Alex Light53cb16b2014-06-12 11:26:29 -0700804
Mathieu Chartier31e88222016-10-14 18:43:19 -0700805void PatchOat::PatchVisitor::operator() (ObjPtr<mirror::Object> obj,
806 MemberOffset off,
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700807 bool is_static_unused ATTRIBUTE_UNUSED) const {
Alex Light53cb16b2014-06-12 11:26:29 -0700808 mirror::Object* referent = obj->GetFieldObject<mirror::Object, kVerifyNone>(off);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700809 mirror::Object* moved_object = patcher_->RelocatedAddressOfPointer(referent);
Alex Light53cb16b2014-06-12 11:26:29 -0700810 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(off, moved_object);
811}
812
Mathieu Chartier31e88222016-10-14 18:43:19 -0700813void PatchOat::PatchVisitor::operator() (ObjPtr<mirror::Class> cls ATTRIBUTE_UNUSED,
814 ObjPtr<mirror::Reference> ref) const {
Alex Light53cb16b2014-06-12 11:26:29 -0700815 MemberOffset off = mirror::Reference::ReferentOffset();
816 mirror::Object* referent = ref->GetReferent();
Mathieu Chartiera13abba2016-04-21 10:23:16 -0700817 DCHECK(referent == nullptr ||
818 Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(referent)) << referent;
Mathieu Chartierc7853442015-03-27 14:35:38 -0700819 mirror::Object* moved_object = patcher_->RelocatedAddressOfPointer(referent);
Alex Light53cb16b2014-06-12 11:26:29 -0700820 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(off, moved_object);
821}
822
Andreas Gampe0c183382017-07-13 22:26:24 -0700823// Called by PatchImage.
Alex Light53cb16b2014-06-12 11:26:29 -0700824void PatchOat::VisitObject(mirror::Object* object) {
825 mirror::Object* copy = RelocatedCopyOf(object);
826 CHECK(copy != nullptr);
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700827 if (kUseBakerReadBarrier) {
828 object->AssertReadBarrierState();
Alex Light53cb16b2014-06-12 11:26:29 -0700829 }
830 PatchOat::PatchVisitor visitor(this, copy);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -0700831 object->VisitReferences<kVerifyNone>(visitor, visitor);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700832 if (object->IsClass<kVerifyNone>()) {
Andreas Gampe542451c2016-07-26 09:02:02 -0700833 const PointerSize pointer_size = InstructionSetPointerSize(isa_);
Mathieu Chartier4b00d342015-11-13 10:42:08 -0800834 mirror::Class* klass = object->AsClass();
835 mirror::Class* copy_klass = down_cast<mirror::Class*>(copy);
836 RelocatedPointerVisitor native_visitor(this);
837 klass->FixupNativePointers(copy_klass, pointer_size, native_visitor);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700838 auto* vtable = klass->GetVTable();
839 if (vtable != nullptr) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800840 vtable->Fixup(RelocatedCopyOfFollowImages(vtable), pointer_size, native_visitor);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700841 }
Mathieu Chartier6beced42016-11-15 15:51:31 -0800842 mirror::IfTable* iftable = klass->GetIfTable();
843 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
844 if (iftable->GetMethodArrayCount(i) > 0) {
845 auto* method_array = iftable->GetMethodArray(i);
846 CHECK(method_array != nullptr);
847 method_array->Fixup(RelocatedCopyOfFollowImages(method_array),
848 pointer_size,
849 native_visitor);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700850 }
851 }
Mathieu Chartier4b00d342015-11-13 10:42:08 -0800852 } else if (object->GetClass() == mirror::Method::StaticClass() ||
853 object->GetClass() == mirror::Constructor::StaticClass()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700854 // Need to go update the ArtMethod.
Neil Fuller0e844392016-09-08 13:43:31 +0100855 auto* dest = down_cast<mirror::Executable*>(copy);
856 auto* src = down_cast<mirror::Executable*>(object);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700857 dest->SetArtMethod(RelocatedAddressOfPointer(src->GetArtMethod()));
Alex Light53cb16b2014-06-12 11:26:29 -0700858 }
859}
860
Mathieu Chartiere401d142015-04-22 13:56:20 -0700861void PatchOat::FixupMethod(ArtMethod* object, ArtMethod* copy) {
Andreas Gampe542451c2016-07-26 09:02:02 -0700862 const PointerSize pointer_size = InstructionSetPointerSize(isa_);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700863 copy->CopyFrom(object, pointer_size);
Alex Light53cb16b2014-06-12 11:26:29 -0700864 // Just update the entry points if it looks like we should.
Alex Lighteefbe392014-07-08 09:53:18 -0700865 // TODO: sanity check all the pointers' values
Mathieu Chartiere401d142015-04-22 13:56:20 -0700866 copy->SetDeclaringClass(RelocatedAddressOfPointer(object->GetDeclaringClass()));
Mathieu Chartiere401d142015-04-22 13:56:20 -0700867 copy->SetEntryPointFromQuickCompiledCodePtrSize(RelocatedAddressOfPointer(
868 object->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size)), pointer_size);
Mathieu Chartiere42888f2016-04-14 10:49:19 -0700869 // No special handling for IMT conflict table since all pointers are moved by the same offset.
Andreas Gampe75f08852016-07-19 08:06:07 -0700870 copy->SetDataPtrSize(RelocatedAddressOfPointer(
871 object->GetDataPtrSize(pointer_size)), pointer_size);
Alex Light53cb16b2014-06-12 11:26:29 -0700872}
873
Alex Light53cb16b2014-06-12 11:26:29 -0700874static int orig_argc;
875static char** orig_argv;
876
877static std::string CommandLine() {
878 std::vector<std::string> command;
879 for (int i = 0; i < orig_argc; ++i) {
880 command.push_back(orig_argv[i]);
881 }
Andreas Gampe9186ced2016-12-12 14:28:21 -0800882 return android::base::Join(command, ' ');
Alex Light53cb16b2014-06-12 11:26:29 -0700883}
884
885static void UsageErrorV(const char* fmt, va_list ap) {
886 std::string error;
Andreas Gampe46ee31b2016-12-14 10:11:49 -0800887 android::base::StringAppendV(&error, fmt, ap);
Alex Light53cb16b2014-06-12 11:26:29 -0700888 LOG(ERROR) << error;
889}
890
891static void UsageError(const char* fmt, ...) {
892 va_list ap;
893 va_start(ap, fmt);
894 UsageErrorV(fmt, ap);
895 va_end(ap);
896}
897
Andreas Gampe794ad762015-02-23 08:12:24 -0800898NO_RETURN static void Usage(const char *fmt, ...) {
Alex Light53cb16b2014-06-12 11:26:29 -0700899 va_list ap;
900 va_start(ap, fmt);
901 UsageErrorV(fmt, ap);
902 va_end(ap);
903
904 UsageError("Command: %s", CommandLine().c_str());
905 UsageError("Usage: patchoat [options]...");
906 UsageError("");
907 UsageError(" --instruction-set=<isa>: Specifies the instruction set the patched code is");
Richard Uhler4bc11d02017-02-01 09:53:54 +0000908 UsageError(" compiled for (required).");
Alex Light53cb16b2014-06-12 11:26:29 -0700909 UsageError("");
910 UsageError(" --input-image-location=<file.art>: Specifies the 'location' of the image file to");
Richard Uhler4bc11d02017-02-01 09:53:54 +0000911 UsageError(" be patched.");
Alex Light53cb16b2014-06-12 11:26:29 -0700912 UsageError("");
913 UsageError(" --output-image-file=<file.art>: Specifies the exact file to write the patched");
914 UsageError(" image file to.");
915 UsageError("");
Alex Klyubinfbe5f2f2017-10-23 13:53:13 -0700916 UsageError(" --output-image-relocation-file=<file.art.rel>: Specifies the exact file to write");
917 UsageError(" the image relocation information to.");
918 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700919 UsageError(" --base-offset-delta=<delta>: Specify the amount to change the old base-offset by.");
920 UsageError(" This value may be negative.");
921 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700922 UsageError(" --dump-timings: dump out patch timing information");
923 UsageError("");
924 UsageError(" --no-dump-timings: do not dump out patch timing information");
925 UsageError("");
926
927 exit(EXIT_FAILURE);
928}
929
Andreas Gampe6eb6a392016-02-10 20:18:37 -0800930static int patchoat_image(TimingLogger& timings,
931 InstructionSet isa,
932 const std::string& input_image_location,
933 const std::string& output_image_filename,
Alex Klyubinfbe5f2f2017-10-23 13:53:13 -0700934 const std::string& output_image_relocation_filename,
Andreas Gampe6eb6a392016-02-10 20:18:37 -0800935 off_t base_delta,
936 bool base_delta_set,
937 bool debug) {
938 CHECK(!input_image_location.empty());
Alex Klyubinfbe5f2f2017-10-23 13:53:13 -0700939 if ((output_image_filename.empty()) && (output_image_relocation_filename.empty())) {
940 Usage("Image patching requires --output-image-file or --output-image-relocation-file");
Andreas Gampe6eb6a392016-02-10 20:18:37 -0800941 }
942
943 if (!base_delta_set) {
944 Usage("Must supply a desired new offset or delta.");
945 }
946
947 if (!IsAligned<kPageSize>(base_delta)) {
948 Usage("Base offset/delta must be aligned to a pagesize (0x%08x) boundary.", kPageSize);
949 }
950
951 if (debug) {
952 LOG(INFO) << "moving offset by " << base_delta
953 << " (0x" << std::hex << base_delta << ") bytes or "
954 << std::dec << (base_delta/kPageSize) << " pages.";
955 }
956
957 TimingLogger::ScopedTiming pt("patch image and oat", &timings);
958
Alex Klyubinfbe5f2f2017-10-23 13:53:13 -0700959 std::string output_image_directory =
Andreas Gampeca620d72016-11-08 08:09:33 -0800960 output_image_filename.substr(0, output_image_filename.find_last_of('/'));
Alex Klyubinfbe5f2f2017-10-23 13:53:13 -0700961 std::string output_image_relocation_directory =
962 output_image_relocation_filename.substr(
963 0, output_image_relocation_filename.find_last_of('/'));
964 bool ret =
965 PatchOat::Patch(
966 input_image_location,
967 base_delta,
968 output_image_directory,
969 output_image_relocation_directory,
970 isa,
971 &timings);
Andreas Gampe6eb6a392016-02-10 20:18:37 -0800972
973 if (kIsDebugBuild) {
974 LOG(INFO) << "Exiting with return ... " << ret;
975 }
976 return ret ? EXIT_SUCCESS : EXIT_FAILURE;
977}
978
Alex Lighteefbe392014-07-08 09:53:18 -0700979static int patchoat(int argc, char **argv) {
Andreas Gampe51d80cc2017-06-21 21:05:13 -0700980 InitLogging(argv, Runtime::Abort);
Mathieu Chartier6e88ef62014-10-14 15:01:24 -0700981 MemMap::Init();
Alex Light53cb16b2014-06-12 11:26:29 -0700982 const bool debug = kIsDebugBuild;
983 orig_argc = argc;
984 orig_argv = argv;
985 TimingLogger timings("patcher", false, false);
986
Alex Light53cb16b2014-06-12 11:26:29 -0700987 // Skip over the command name.
988 argv++;
989 argc--;
990
991 if (argc == 0) {
992 Usage("No arguments specified");
993 }
994
995 timings.StartTiming("Patchoat");
996
997 // cmd line args
998 bool isa_set = false;
Vladimir Marko33bff252017-11-01 14:35:42 +0000999 InstructionSet isa = InstructionSet::kNone;
Alex Light53cb16b2014-06-12 11:26:29 -07001000 std::string input_image_location;
Alex Light53cb16b2014-06-12 11:26:29 -07001001 std::string output_image_filename;
Alex Klyubinfbe5f2f2017-10-23 13:53:13 -07001002 std::string output_image_relocation_filename;
Alex Light53cb16b2014-06-12 11:26:29 -07001003 off_t base_delta = 0;
1004 bool base_delta_set = false;
Alex Light53cb16b2014-06-12 11:26:29 -07001005 bool dump_timings = kIsDebugBuild;
1006
Ian Rogersd4c4d952014-10-16 20:31:53 -07001007 for (int i = 0; i < argc; ++i) {
Alex Light53cb16b2014-06-12 11:26:29 -07001008 const StringPiece option(argv[i]);
1009 const bool log_options = false;
1010 if (log_options) {
1011 LOG(INFO) << "patchoat: option[" << i << "]=" << argv[i];
1012 }
Alex Light53cb16b2014-06-12 11:26:29 -07001013 if (option.starts_with("--instruction-set=")) {
1014 isa_set = true;
1015 const char* isa_str = option.substr(strlen("--instruction-set=")).data();
Andreas Gampe20c89302014-08-19 17:28:06 -07001016 isa = GetInstructionSetFromString(isa_str);
Vladimir Marko33bff252017-11-01 14:35:42 +00001017 if (isa == InstructionSet::kNone) {
Andreas Gampe20c89302014-08-19 17:28:06 -07001018 Usage("Unknown or invalid instruction set %s", isa_str);
Alex Light53cb16b2014-06-12 11:26:29 -07001019 }
Alex Light53cb16b2014-06-12 11:26:29 -07001020 } else if (option.starts_with("--input-image-location=")) {
1021 input_image_location = option.substr(strlen("--input-image-location=")).data();
Alex Light53cb16b2014-06-12 11:26:29 -07001022 } else if (option.starts_with("--output-image-file=")) {
Alex Light53cb16b2014-06-12 11:26:29 -07001023 output_image_filename = option.substr(strlen("--output-image-file=")).data();
Alex Klyubinfbe5f2f2017-10-23 13:53:13 -07001024 } else if (option.starts_with("--output-image-relocation-file=")) {
1025 output_image_relocation_filename =
1026 option.substr(strlen("--output-image-relocation-file=")).data();
Alex Light53cb16b2014-06-12 11:26:29 -07001027 } else if (option.starts_with("--base-offset-delta=")) {
1028 const char* base_delta_str = option.substr(strlen("--base-offset-delta=")).data();
1029 base_delta_set = true;
1030 if (!ParseInt(base_delta_str, &base_delta)) {
1031 Usage("Failed to parse --base-offset-delta argument '%s' as an off_t", base_delta_str);
1032 }
Alex Light53cb16b2014-06-12 11:26:29 -07001033 } else if (option == "--dump-timings") {
1034 dump_timings = true;
1035 } else if (option == "--no-dump-timings") {
1036 dump_timings = false;
1037 } else {
1038 Usage("Unknown argument %s", option.data());
1039 }
1040 }
1041
Andreas Gampe6eb6a392016-02-10 20:18:37 -08001042 // The instruction set is mandatory. This simplifies things...
1043 if (!isa_set) {
1044 Usage("Instruction set must be set.");
Alex Light53cb16b2014-06-12 11:26:29 -07001045 }
1046
Richard Uhler4bc11d02017-02-01 09:53:54 +00001047 int ret = patchoat_image(timings,
1048 isa,
1049 input_image_location,
1050 output_image_filename,
Alex Klyubinfbe5f2f2017-10-23 13:53:13 -07001051 output_image_relocation_filename,
Richard Uhler4bc11d02017-02-01 09:53:54 +00001052 base_delta,
1053 base_delta_set,
1054 debug);
Alex Light53cb16b2014-06-12 11:26:29 -07001055
Andreas Gampe6eb6a392016-02-10 20:18:37 -08001056 timings.EndTiming();
1057 if (dump_timings) {
1058 LOG(INFO) << Dumpable<TimingLogger>(timings);
Alex Light53cb16b2014-06-12 11:26:29 -07001059 }
1060
Andreas Gampe6eb6a392016-02-10 20:18:37 -08001061 return ret;
Alex Light53cb16b2014-06-12 11:26:29 -07001062}
1063
1064} // namespace art
1065
1066int main(int argc, char **argv) {
1067 return art::patchoat(argc, argv);
1068}