blob: 1668dc5f257db72b7a81f91ed976caba28ae8d47 [file] [log] [blame]
Alex Light53cb16b2014-06-12 11:26:29 -07001/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16#include "patchoat.h"
17
18#include <stdio.h>
19#include <stdlib.h>
Alex Lighta59dd802014-07-02 16:28:08 -070020#include <sys/file.h>
Alex Light53cb16b2014-06-12 11:26:29 -070021#include <sys/stat.h>
Alex Lighta59dd802014-07-02 16:28:08 -070022#include <unistd.h>
Alex Light53cb16b2014-06-12 11:26:29 -070023
24#include <string>
25#include <vector>
26
Mathieu Chartierc7853442015-03-27 14:35:38 -070027#include "art_field-inl.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070028#include "art_method-inl.h"
Ian Rogersc7dd2952014-10-21 23:31:19 -070029#include "base/dumpable.h"
Alex Lighta59dd802014-07-02 16:28:08 -070030#include "base/scoped_flock.h"
Alex Light53cb16b2014-06-12 11:26:29 -070031#include "base/stringpiece.h"
32#include "base/stringprintf.h"
Ian Rogersd4c4d952014-10-16 20:31:53 -070033#include "base/unix_file/fd_file.h"
Alex Light53cb16b2014-06-12 11:26:29 -070034#include "elf_utils.h"
35#include "elf_file.h"
Tong Shen62d1ca32014-09-03 17:24:56 -070036#include "elf_file_impl.h"
Ian Rogerse63db272014-07-15 15:36:11 -070037#include "gc/space/image_space.h"
Mathieu Chartier4a26f172016-01-26 14:26:18 -080038#include "image-inl.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070039#include "mirror/abstract_method.h"
Alex Light53cb16b2014-06-12 11:26:29 -070040#include "mirror/object-inl.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070041#include "mirror/method.h"
Alex Light53cb16b2014-06-12 11:26:29 -070042#include "mirror/reference.h"
43#include "noop_compiler_callbacks.h"
44#include "offsets.h"
45#include "os.h"
46#include "runtime.h"
47#include "scoped_thread_state_change.h"
48#include "thread.h"
49#include "utils.h"
50
51namespace art {
52
Alex Lightcf4bf382014-07-24 11:29:14 -070053static bool LocationToFilename(const std::string& location, InstructionSet isa,
54 std::string* filename) {
55 bool has_system = false;
56 bool has_cache = false;
57 // image_location = /system/framework/boot.art
Igor Murashkin46774762014-10-22 11:37:02 -070058 // system_image_filename = /system/framework/<image_isa>/boot.art
Alex Lightcf4bf382014-07-24 11:29:14 -070059 std::string system_filename(GetSystemImageFilename(location.c_str(), isa));
60 if (OS::FileExists(system_filename.c_str())) {
61 has_system = true;
62 }
63
64 bool have_android_data = false;
65 bool dalvik_cache_exists = false;
Andreas Gampe3c13a792014-09-18 20:56:04 -070066 bool is_global_cache = false;
Alex Lightcf4bf382014-07-24 11:29:14 -070067 std::string dalvik_cache;
68 GetDalvikCache(GetInstructionSetString(isa), false, &dalvik_cache,
Andreas Gampe3c13a792014-09-18 20:56:04 -070069 &have_android_data, &dalvik_cache_exists, &is_global_cache);
Alex Lightcf4bf382014-07-24 11:29:14 -070070
71 std::string cache_filename;
72 if (have_android_data && dalvik_cache_exists) {
73 // Always set output location even if it does not exist,
74 // so that the caller knows where to create the image.
75 //
76 // image_location = /system/framework/boot.art
77 // *image_filename = /data/dalvik-cache/<image_isa>/boot.art
78 std::string error_msg;
79 if (GetDalvikCacheFilename(location.c_str(), dalvik_cache.c_str(),
80 &cache_filename, &error_msg)) {
81 has_cache = true;
82 }
83 }
84 if (has_system) {
85 *filename = system_filename;
86 return true;
87 } else if (has_cache) {
88 *filename = cache_filename;
89 return true;
90 } else {
91 return false;
92 }
93}
94
Alex Light0eb76d22015-08-11 18:03:47 -070095static const OatHeader* GetOatHeader(const ElfFile* elf_file) {
96 uint64_t off = 0;
97 if (!elf_file->GetSectionOffsetAndSize(".rodata", &off, nullptr)) {
98 return nullptr;
99 }
100
101 OatHeader* oat_header = reinterpret_cast<OatHeader*>(elf_file->Begin() + off);
102 return oat_header;
103}
104
105// This function takes an elf file and reads the current patch delta value
106// encoded in its oat header value
107static bool ReadOatPatchDelta(const ElfFile* elf_file, off_t* delta, std::string* error_msg) {
108 const OatHeader* oat_header = GetOatHeader(elf_file);
109 if (oat_header == nullptr) {
110 *error_msg = "Unable to get oat header from elf file.";
111 return false;
112 }
113 if (!oat_header->IsValid()) {
114 *error_msg = "Elf file has an invalid oat header";
115 return false;
116 }
117 *delta = oat_header->GetImagePatchDelta();
118 return true;
119}
120
Jeff Haodcdc85b2015-12-04 14:06:18 -0800121static File* CreateOrOpen(const char* name, bool* created) {
122 if (OS::FileExists(name)) {
123 *created = false;
124 return OS::OpenFileReadWrite(name);
125 } else {
126 *created = true;
127 std::unique_ptr<File> f(OS::CreateEmptyFile(name));
128 if (f.get() != nullptr) {
129 if (fchmod(f->Fd(), 0644) != 0) {
130 PLOG(ERROR) << "Unable to make " << name << " world readable";
131 TEMP_FAILURE_RETRY(unlink(name));
132 return nullptr;
133 }
134 }
135 return f.release();
136 }
137}
138
139// Either try to close the file (close=true), or erase it.
140static bool FinishFile(File* file, bool close) {
141 if (close) {
142 if (file->FlushCloseOrErase() != 0) {
143 PLOG(ERROR) << "Failed to flush and close file.";
144 return false;
145 }
146 return true;
147 } else {
148 file->Erase();
149 return false;
150 }
151}
152
Igor Murashkin46774762014-10-22 11:37:02 -0700153bool PatchOat::Patch(File* input_oat, const std::string& image_location, off_t delta,
Alex Light53cb16b2014-06-12 11:26:29 -0700154 File* output_oat, File* output_image, InstructionSet isa,
Igor Murashkin46774762014-10-22 11:37:02 -0700155 TimingLogger* timings,
Jeff Haodcdc85b2015-12-04 14:06:18 -0800156 bool output_oat_opened_from_fd ATTRIBUTE_UNUSED,
Igor Murashkin46774762014-10-22 11:37:02 -0700157 bool new_oat_out) {
Alex Light53cb16b2014-06-12 11:26:29 -0700158 CHECK(Runtime::Current() == nullptr);
159 CHECK(output_image != nullptr);
160 CHECK_GE(output_image->Fd(), 0);
161 CHECK(input_oat != nullptr);
162 CHECK(output_oat != nullptr);
163 CHECK_GE(input_oat->Fd(), 0);
164 CHECK_GE(output_oat->Fd(), 0);
165 CHECK(!image_location.empty()) << "image file must have a filename.";
166
Alex Lighteefbe392014-07-08 09:53:18 -0700167 TimingLogger::ScopedTiming t("Runtime Setup", timings);
Alex Light53cb16b2014-06-12 11:26:29 -0700168
169 if (isa == kNone) {
170 Elf32_Ehdr elf_hdr;
171 if (sizeof(elf_hdr) != input_oat->Read(reinterpret_cast<char*>(&elf_hdr), sizeof(elf_hdr), 0)) {
172 LOG(ERROR) << "unable to read elf header";
173 return false;
174 }
Andreas Gampe6f611412015-01-21 22:25:24 -0800175 isa = GetInstructionSetFromELF(elf_hdr.e_machine, elf_hdr.e_flags);
Alex Light53cb16b2014-06-12 11:26:29 -0700176 }
177 const char* isa_name = GetInstructionSetString(isa);
Igor Murashkin46774762014-10-22 11:37:02 -0700178
Alex Light53cb16b2014-06-12 11:26:29 -0700179 // Set up the runtime
Ian Rogerse63db272014-07-15 15:36:11 -0700180 RuntimeOptions options;
Alex Light53cb16b2014-06-12 11:26:29 -0700181 NoopCompilerCallbacks callbacks;
182 options.push_back(std::make_pair("compilercallbacks", &callbacks));
183 std::string img = "-Ximage:" + image_location;
184 options.push_back(std::make_pair(img.c_str(), nullptr));
185 options.push_back(std::make_pair("imageinstructionset", reinterpret_cast<const void*>(isa_name)));
Calin Juravle01aaf6e2015-06-19 22:05:39 +0100186 options.push_back(std::make_pair("-Xno-sig-chain", nullptr));
Alex Light53cb16b2014-06-12 11:26:29 -0700187 if (!Runtime::Create(options, false)) {
188 LOG(ERROR) << "Unable to initialize runtime";
189 return false;
190 }
191 // Runtime::Create acquired the mutator_lock_ that is normally given away when we Runtime::Start,
192 // give it away now and then switch to a more manageable ScopedObjectAccess.
193 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
194 ScopedObjectAccess soa(Thread::Current());
195
Jeff Haodcdc85b2015-12-04 14:06:18 -0800196 std::string output_directory =
197 output_image->GetPath().substr(0, output_image->GetPath().find_last_of("/"));
Alex Light53cb16b2014-06-12 11:26:29 -0700198 t.NewTiming("Image and oat Patching setup");
Jeff Haodcdc85b2015-12-04 14:06:18 -0800199 std::vector<gc::space::ImageSpace*> spaces = Runtime::Current()->GetHeap()->GetBootImageSpaces();
200 std::map<gc::space::ImageSpace*, std::unique_ptr<File>> space_to_file_map;
201 std::map<gc::space::ImageSpace*, std::unique_ptr<MemMap>> space_to_memmap_map;
202 std::map<gc::space::ImageSpace*, PatchOat> space_to_patchoat_map;
203 std::map<gc::space::ImageSpace*, bool> space_to_skip_patching_map;
Alex Light53cb16b2014-06-12 11:26:29 -0700204
Jeff Haodcdc85b2015-12-04 14:06:18 -0800205 for (size_t i = 0; i < spaces.size(); ++i) {
206 gc::space::ImageSpace* space = spaces[i];
207 std::string input_image_filename = space->GetImageFilename();
208 std::unique_ptr<File> input_image(OS::OpenFileForReading(input_image_filename.c_str()));
209 if (input_image.get() == nullptr) {
210 LOG(ERROR) << "Unable to open input image file at " << input_image_filename;
Igor Murashkin46774762014-10-22 11:37:02 -0700211 return false;
212 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800213
214 int64_t image_len = input_image->GetLength();
215 if (image_len < 0) {
216 LOG(ERROR) << "Error while getting image length";
217 return false;
218 }
219 ImageHeader image_header;
220 if (sizeof(image_header) != input_image->Read(reinterpret_cast<char*>(&image_header),
221 sizeof(image_header), 0)) {
222 LOG(ERROR) << "Unable to read image header from image file " << input_image->GetPath();
223 }
224
225 /*bool is_image_pic = */IsImagePic(image_header, input_image->GetPath());
226 // Nothing special to do right now since the image always needs to get patched.
227 // Perhaps in some far-off future we may have images with relative addresses that are true-PIC.
228
229 // Create the map where we will write the image patches to.
230 std::string error_msg;
231 std::unique_ptr<MemMap> image(MemMap::MapFile(image_len,
232 PROT_READ | PROT_WRITE,
233 MAP_PRIVATE,
234 input_image->Fd(),
235 0,
236 /*low_4gb*/false,
237 input_image->GetPath().c_str(),
238 &error_msg));
239 if (image.get() == nullptr) {
240 LOG(ERROR) << "Unable to map image file " << input_image->GetPath() << " : " << error_msg;
241 return false;
242 }
243 space_to_file_map.emplace(space, std::move(input_image));
244 space_to_memmap_map.emplace(space, std::move(image));
Igor Murashkin46774762014-10-22 11:37:02 -0700245 }
246
Jeff Haodcdc85b2015-12-04 14:06:18 -0800247 for (size_t i = 0; i < spaces.size(); ++i) {
248 gc::space::ImageSpace* space = spaces[i];
249 std::string input_image_filename = space->GetImageFilename();
250 std::string input_oat_filename =
251 ImageHeader::GetOatLocationFromImageLocation(input_image_filename);
252 std::unique_ptr<File> input_oat_file(OS::OpenFileForReading(input_oat_filename.c_str()));
253 if (input_oat_file.get() == nullptr) {
254 LOG(ERROR) << "Unable to open input oat file at " << input_oat_filename;
255 return false;
256 }
257 std::string error_msg;
258 std::unique_ptr<ElfFile> elf(ElfFile::Open(input_oat_file.get(),
259 PROT_READ | PROT_WRITE, MAP_PRIVATE, &error_msg));
260 if (elf.get() == nullptr) {
261 LOG(ERROR) << "Unable to open oat file " << input_oat_file->GetPath() << " : " << error_msg;
262 return false;
263 }
264
265 bool skip_patching_oat = false;
266 MaybePic is_oat_pic = IsOatPic(elf.get());
267 if (is_oat_pic >= ERROR_FIRST) {
268 // Error logged by IsOatPic
269 return false;
270 } else if (is_oat_pic == PIC) {
271 // Do not need to do ELF-file patching. Create a symlink and skip the ELF patching.
272
273 std::string converted_image_filename = space->GetImageLocation();
274 std::replace(converted_image_filename.begin() + 1, converted_image_filename.end(), '/', '@');
275 std::string output_image_filename = output_directory +
276 (StartsWith(converted_image_filename, "/") ? "" : "/") +
277 converted_image_filename;
278 std::string output_oat_filename =
279 ImageHeader::GetOatLocationFromImageLocation(output_image_filename);
280
281 if (!ReplaceOatFileWithSymlink(input_oat_file->GetPath(),
282 output_oat_filename,
283 false,
284 true)) {
285 // Errors already logged by above call.
286 return false;
287 }
288 // Don't patch the OAT, since we just symlinked it. Image still needs patching.
289 skip_patching_oat = true;
290 } else {
291 CHECK(is_oat_pic == NOT_PIC);
292 }
293
294 PatchOat& p = space_to_patchoat_map.emplace(space,
295 PatchOat(
296 isa,
297 elf.release(),
298 space_to_memmap_map.find(space)->second.get(),
299 space->GetLiveBitmap(),
300 space->GetMemMap(),
301 delta,
302 &space_to_memmap_map,
303 timings)).first->second;
304
305 t.NewTiming("Patching files");
306 if (!skip_patching_oat && !p.PatchElf()) {
307 LOG(ERROR) << "Failed to patch oat file " << input_oat_file->GetPath();
308 return false;
309 }
310 if (!p.PatchImage(i == 0)) {
311 LOG(ERROR) << "Failed to patch image file " << input_image_filename;
312 return false;
313 }
314
315 space_to_skip_patching_map.emplace(space, skip_patching_oat);
Alex Light53cb16b2014-06-12 11:26:29 -0700316 }
317
Jeff Haodcdc85b2015-12-04 14:06:18 -0800318 for (size_t i = 0; i < spaces.size(); ++i) {
319 gc::space::ImageSpace* space = spaces[i];
320 std::string input_image_filename = space->GetImageFilename();
321
322 t.NewTiming("Writing files");
323 std::string converted_image_filename = space->GetImageLocation();
324 std::replace(converted_image_filename.begin() + 1, converted_image_filename.end(), '/', '@');
325 std::string output_image_filename = output_directory +
326 (StartsWith(converted_image_filename, "/") ? "" : "/") +
327 converted_image_filename;
328 std::unique_ptr<File>
329 output_image_file(CreateOrOpen(output_image_filename.c_str(), &new_oat_out));
330 if (output_image_file.get() == nullptr) {
331 LOG(ERROR) << "Failed to open output image file at " << output_image_filename;
332 return false;
333 }
334
335 PatchOat& p = space_to_patchoat_map.find(space)->second;
336
337 if (!p.WriteImage(output_image_file.get())) {
338 LOG(ERROR) << "Failed to write image file " << output_image_file->GetPath();
339 return false;
340 }
341 FinishFile(output_image_file.get(), true);
342
343 bool skip_patching_oat = space_to_skip_patching_map.find(space)->second;
344 if (!skip_patching_oat) {
345 std::string output_oat_filename =
346 ImageHeader::GetOatLocationFromImageLocation(output_image_filename);
347 std::unique_ptr<File>
348 output_oat_file(CreateOrOpen(output_oat_filename.c_str(), &new_oat_out));
349 if (output_oat_file.get() == nullptr) {
350 LOG(ERROR) << "Failed to open output oat file at " << output_oat_filename;
351 return false;
352 }
353 if (!p.WriteElf(output_oat_file.get())) {
354 LOG(ERROR) << "Failed to write oat file " << output_oat_file->GetPath();
355 return false;
356 }
357 FinishFile(output_oat_file.get(), true);
358 }
Alex Light53cb16b2014-06-12 11:26:29 -0700359 }
360 return true;
361}
362
363bool PatchOat::WriteElf(File* out) {
Alex Lighteefbe392014-07-08 09:53:18 -0700364 TimingLogger::ScopedTiming t("Writing Elf File", timings_);
Alex Lighta59dd802014-07-02 16:28:08 -0700365
Alex Light53cb16b2014-06-12 11:26:29 -0700366 CHECK(oat_file_.get() != nullptr);
367 CHECK(out != nullptr);
368 size_t expect = oat_file_->Size();
369 if (out->WriteFully(reinterpret_cast<char*>(oat_file_->Begin()), expect) &&
370 out->SetLength(expect) == 0) {
371 return true;
372 } else {
373 LOG(ERROR) << "Writing to oat file " << out->GetPath() << " failed.";
374 return false;
375 }
376}
377
378bool PatchOat::WriteImage(File* out) {
Alex Lighteefbe392014-07-08 09:53:18 -0700379 TimingLogger::ScopedTiming t("Writing image File", timings_);
Alex Lighta59dd802014-07-02 16:28:08 -0700380 std::string error_msg;
381
Alex Lightcf4bf382014-07-24 11:29:14 -0700382 ScopedFlock img_flock;
383 img_flock.Init(out, &error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -0700384
Alex Light53cb16b2014-06-12 11:26:29 -0700385 CHECK(image_ != nullptr);
386 CHECK(out != nullptr);
387 size_t expect = image_->Size();
388 if (out->WriteFully(reinterpret_cast<char*>(image_->Begin()), expect) &&
389 out->SetLength(expect) == 0) {
390 return true;
391 } else {
392 LOG(ERROR) << "Writing to image file " << out->GetPath() << " failed.";
393 return false;
394 }
395}
396
Igor Murashkin46774762014-10-22 11:37:02 -0700397bool PatchOat::IsImagePic(const ImageHeader& image_header, const std::string& image_path) {
398 if (!image_header.CompilePic()) {
399 if (kIsDebugBuild) {
400 LOG(INFO) << "image at location " << image_path << " was *not* compiled pic";
401 }
402 return false;
403 }
404
405 if (kIsDebugBuild) {
406 LOG(INFO) << "image at location " << image_path << " was compiled PIC";
407 }
408
409 return true;
410}
411
412PatchOat::MaybePic PatchOat::IsOatPic(const ElfFile* oat_in) {
413 if (oat_in == nullptr) {
414 LOG(ERROR) << "No ELF input oat fie available";
415 return ERROR_OAT_FILE;
416 }
417
418 const std::string& file_path = oat_in->GetFile().GetPath();
419
420 const OatHeader* oat_header = GetOatHeader(oat_in);
421 if (oat_header == nullptr) {
422 LOG(ERROR) << "Failed to find oat header in oat file " << file_path;
423 return ERROR_OAT_FILE;
424 }
425
426 if (!oat_header->IsValid()) {
427 LOG(ERROR) << "Elf file " << file_path << " has an invalid oat header";
428 return ERROR_OAT_FILE;
429 }
430
431 bool is_pic = oat_header->IsPic();
432 if (kIsDebugBuild) {
433 LOG(INFO) << "Oat file at " << file_path << " is " << (is_pic ? "PIC" : "not pic");
434 }
435
436 return is_pic ? PIC : NOT_PIC;
437}
438
439bool PatchOat::ReplaceOatFileWithSymlink(const std::string& input_oat_filename,
440 const std::string& output_oat_filename,
441 bool output_oat_opened_from_fd,
442 bool new_oat_out) {
443 // Need a file when we are PIC, since we symlink over it. Refusing to symlink into FD.
444 if (output_oat_opened_from_fd) {
445 // TODO: installd uses --output-oat-fd. Should we change class linking logic for PIC?
446 LOG(ERROR) << "No output oat filename specified, needs filename for when we are PIC";
447 return false;
448 }
449
450 // Image was PIC. Create symlink where the oat is supposed to go.
451 if (!new_oat_out) {
452 LOG(ERROR) << "Oat file " << output_oat_filename << " already exists, refusing to overwrite";
453 return false;
454 }
455
456 // Delete the original file, since we won't need it.
457 TEMP_FAILURE_RETRY(unlink(output_oat_filename.c_str()));
458
459 // Create a symlink from the old oat to the new oat
460 if (symlink(input_oat_filename.c_str(), output_oat_filename.c_str()) < 0) {
461 int err = errno;
462 LOG(ERROR) << "Failed to create symlink at " << output_oat_filename
463 << " error(" << err << "): " << strerror(err);
464 return false;
465 }
466
467 if (kIsDebugBuild) {
468 LOG(INFO) << "Created symlink " << output_oat_filename << " -> " << input_oat_filename;
469 }
470
471 return true;
472}
473
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700474class PatchOatArtFieldVisitor : public ArtFieldVisitor {
475 public:
476 explicit PatchOatArtFieldVisitor(PatchOat* patch_oat) : patch_oat_(patch_oat) {}
477
478 void Visit(ArtField* field) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
479 ArtField* const dest = patch_oat_->RelocatedCopyOf(field);
480 dest->SetDeclaringClass(patch_oat_->RelocatedAddressOfPointer(field->GetDeclaringClass()));
Mathieu Chartiere401d142015-04-22 13:56:20 -0700481 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700482
483 private:
484 PatchOat* const patch_oat_;
485};
486
487void PatchOat::PatchArtFields(const ImageHeader* image_header) {
488 PatchOatArtFieldVisitor visitor(this);
489 const auto& section = image_header->GetImageSection(ImageHeader::kSectionArtFields);
490 section.VisitPackedArtFields(&visitor, heap_->Begin());
Mathieu Chartiere401d142015-04-22 13:56:20 -0700491}
492
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700493class PatchOatArtMethodVisitor : public ArtMethodVisitor {
494 public:
495 explicit PatchOatArtMethodVisitor(PatchOat* patch_oat) : patch_oat_(patch_oat) {}
496
497 void Visit(ArtMethod* method) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
498 ArtMethod* const dest = patch_oat_->RelocatedCopyOf(method);
499 patch_oat_->FixupMethod(method, dest);
500 }
501
502 private:
503 PatchOat* const patch_oat_;
504};
505
Mathieu Chartiere401d142015-04-22 13:56:20 -0700506void PatchOat::PatchArtMethods(const ImageHeader* image_header) {
507 const auto& section = image_header->GetMethodsSection();
508 const size_t pointer_size = InstructionSetPointerSize(isa_);
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700509 PatchOatArtMethodVisitor visitor(this);
Vladimir Markocf36d492015-08-12 19:27:26 +0100510 section.VisitPackedArtMethods(&visitor, heap_->Begin(), pointer_size);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700511}
512
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700513class FixupRootVisitor : public RootVisitor {
514 public:
515 explicit FixupRootVisitor(const PatchOat* patch_oat) : patch_oat_(patch_oat) {
516 }
517
518 void VisitRoots(mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -0700519 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700520 for (size_t i = 0; i < count; ++i) {
521 *roots[i] = patch_oat_->RelocatedAddressOfPointer(*roots[i]);
522 }
523 }
524
525 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots, size_t count,
526 const RootInfo& info ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -0700527 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700528 for (size_t i = 0; i < count; ++i) {
529 roots[i]->Assign(patch_oat_->RelocatedAddressOfPointer(roots[i]->AsMirrorPtr()));
530 }
531 }
532
533 private:
534 const PatchOat* const patch_oat_;
535};
536
537void PatchOat::PatchInternedStrings(const ImageHeader* image_header) {
538 const auto& section = image_header->GetImageSection(ImageHeader::kSectionInternedStrings);
539 InternTable temp_table;
540 // Note that we require that ReadFromMemory does not make an internal copy of the elements.
541 // This also relies on visit roots not doing any verification which could fail after we update
542 // the roots to be the image addresses.
Mathieu Chartierea0831f2015-12-29 13:17:37 -0800543 temp_table.AddTableFromMemory(image_->Begin() + section.Offset());
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700544 FixupRootVisitor visitor(this);
545 temp_table.VisitRoots(&visitor, kVisitRootFlagAllRoots);
546}
547
Mathieu Chartier208a5cb2015-12-02 15:44:07 -0800548void PatchOat::PatchClassTable(const ImageHeader* image_header) {
549 const auto& section = image_header->GetImageSection(ImageHeader::kSectionClassTable);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800550 if (section.Size() == 0) {
551 return;
552 }
Mathieu Chartier208a5cb2015-12-02 15:44:07 -0800553 // Note that we require that ReadFromMemory does not make an internal copy of the elements.
554 // This also relies on visit roots not doing any verification which could fail after we update
555 // the roots to be the image addresses.
556 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
557 ClassTable temp_table;
558 temp_table.ReadFromMemory(image_->Begin() + section.Offset());
559 FixupRootVisitor visitor(this);
560 BufferedRootVisitor<kDefaultBufferedRootCount> buffered_visitor(&visitor, RootInfo(kRootUnknown));
561 temp_table.VisitRoots(buffered_visitor);
562}
563
564
Mathieu Chartier4b00d342015-11-13 10:42:08 -0800565class RelocatedPointerVisitor {
566 public:
567 explicit RelocatedPointerVisitor(PatchOat* patch_oat) : patch_oat_(patch_oat) {}
568
569 template <typename T>
570 T* operator()(T* ptr) const {
571 return patch_oat_->RelocatedAddressOfPointer(ptr);
572 }
573
574 private:
575 PatchOat* const patch_oat_;
576};
577
Mathieu Chartierc7853442015-03-27 14:35:38 -0700578void PatchOat::PatchDexFileArrays(mirror::ObjectArray<mirror::Object>* img_roots) {
579 auto* dex_caches = down_cast<mirror::ObjectArray<mirror::DexCache>*>(
580 img_roots->Get(ImageHeader::kDexCaches));
Mathieu Chartier4b00d342015-11-13 10:42:08 -0800581 const size_t pointer_size = InstructionSetPointerSize(isa_);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700582 for (size_t i = 0, count = dex_caches->GetLength(); i < count; ++i) {
Vladimir Marko05792b92015-08-03 11:56:49 +0100583 auto* orig_dex_cache = dex_caches->GetWithoutChecks(i);
584 auto* copy_dex_cache = RelocatedCopyOf(orig_dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +0100585 // Though the DexCache array fields are usually treated as native pointers, we set the full
586 // 64-bit values here, clearing the top 32 bits for 32-bit targets. The zero-extension is
587 // done by casting to the unsigned type uintptr_t before casting to int64_t, i.e.
588 // static_cast<int64_t>(reinterpret_cast<uintptr_t>(image_begin_ + offset))).
589 GcRoot<mirror::String>* orig_strings = orig_dex_cache->GetStrings();
590 GcRoot<mirror::String>* relocated_strings = RelocatedAddressOfPointer(orig_strings);
591 copy_dex_cache->SetField64<false>(
592 mirror::DexCache::StringsOffset(),
593 static_cast<int64_t>(reinterpret_cast<uintptr_t>(relocated_strings)));
594 if (orig_strings != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -0800595 orig_dex_cache->FixupStrings(RelocatedCopyOf(orig_strings), RelocatedPointerVisitor(this));
Mathieu Chartierc7853442015-03-27 14:35:38 -0700596 }
Vladimir Marko05792b92015-08-03 11:56:49 +0100597 GcRoot<mirror::Class>* orig_types = orig_dex_cache->GetResolvedTypes();
598 GcRoot<mirror::Class>* relocated_types = RelocatedAddressOfPointer(orig_types);
599 copy_dex_cache->SetField64<false>(
600 mirror::DexCache::ResolvedTypesOffset(),
601 static_cast<int64_t>(reinterpret_cast<uintptr_t>(relocated_types)));
602 if (orig_types != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -0800603 orig_dex_cache->FixupResolvedTypes(RelocatedCopyOf(orig_types),
604 RelocatedPointerVisitor(this));
Vladimir Marko05792b92015-08-03 11:56:49 +0100605 }
606 ArtMethod** orig_methods = orig_dex_cache->GetResolvedMethods();
607 ArtMethod** relocated_methods = RelocatedAddressOfPointer(orig_methods);
608 copy_dex_cache->SetField64<false>(
609 mirror::DexCache::ResolvedMethodsOffset(),
610 static_cast<int64_t>(reinterpret_cast<uintptr_t>(relocated_methods)));
611 if (orig_methods != nullptr) {
612 ArtMethod** copy_methods = RelocatedCopyOf(orig_methods);
613 for (size_t j = 0, num = orig_dex_cache->NumResolvedMethods(); j != num; ++j) {
614 ArtMethod* orig = mirror::DexCache::GetElementPtrSize(orig_methods, j, pointer_size);
615 ArtMethod* copy = RelocatedAddressOfPointer(orig);
616 mirror::DexCache::SetElementPtrSize(copy_methods, j, copy, pointer_size);
617 }
618 }
619 ArtField** orig_fields = orig_dex_cache->GetResolvedFields();
620 ArtField** relocated_fields = RelocatedAddressOfPointer(orig_fields);
621 copy_dex_cache->SetField64<false>(
622 mirror::DexCache::ResolvedFieldsOffset(),
623 static_cast<int64_t>(reinterpret_cast<uintptr_t>(relocated_fields)));
624 if (orig_fields != nullptr) {
625 ArtField** copy_fields = RelocatedCopyOf(orig_fields);
626 for (size_t j = 0, num = orig_dex_cache->NumResolvedFields(); j != num; ++j) {
627 ArtField* orig = mirror::DexCache::GetElementPtrSize(orig_fields, j, pointer_size);
628 ArtField* copy = RelocatedAddressOfPointer(orig);
629 mirror::DexCache::SetElementPtrSize(copy_fields, j, copy, pointer_size);
630 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700631 }
632 }
633}
634
Jeff Haodcdc85b2015-12-04 14:06:18 -0800635bool PatchOat::PatchImage(bool primary_image) {
Alex Light53cb16b2014-06-12 11:26:29 -0700636 ImageHeader* image_header = reinterpret_cast<ImageHeader*>(image_->Begin());
637 CHECK_GT(image_->Size(), sizeof(ImageHeader));
638 // These are the roots from the original file.
Mathieu Chartierc7853442015-03-27 14:35:38 -0700639 auto* img_roots = image_header->GetImageRoots();
Alex Light53cb16b2014-06-12 11:26:29 -0700640 image_header->RelocateImage(delta_);
641
Mathieu Chartierc7853442015-03-27 14:35:38 -0700642 PatchArtFields(image_header);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700643 PatchArtMethods(image_header);
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700644 PatchInternedStrings(image_header);
Mathieu Chartier208a5cb2015-12-02 15:44:07 -0800645 PatchClassTable(image_header);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700646 // Patch dex file int/long arrays which point to ArtFields.
647 PatchDexFileArrays(img_roots);
648
Jeff Haodcdc85b2015-12-04 14:06:18 -0800649 if (primary_image) {
650 VisitObject(img_roots);
651 }
652
Alex Light53cb16b2014-06-12 11:26:29 -0700653 if (!image_header->IsValid()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800654 LOG(ERROR) << "relocation renders image header invalid";
Alex Light53cb16b2014-06-12 11:26:29 -0700655 return false;
656 }
657
658 {
Alex Lighteefbe392014-07-08 09:53:18 -0700659 TimingLogger::ScopedTiming t("Walk Bitmap", timings_);
Alex Light53cb16b2014-06-12 11:26:29 -0700660 // Walk the bitmap.
661 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
662 bitmap_->Walk(PatchOat::BitmapCallback, this);
663 }
664 return true;
665}
666
667bool PatchOat::InHeap(mirror::Object* o) {
668 uintptr_t begin = reinterpret_cast<uintptr_t>(heap_->Begin());
669 uintptr_t end = reinterpret_cast<uintptr_t>(heap_->End());
670 uintptr_t obj = reinterpret_cast<uintptr_t>(o);
671 return o == nullptr || (begin <= obj && obj < end);
672}
673
674void PatchOat::PatchVisitor::operator() (mirror::Object* obj, MemberOffset off,
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700675 bool is_static_unused ATTRIBUTE_UNUSED) const {
Alex Light53cb16b2014-06-12 11:26:29 -0700676 mirror::Object* referent = obj->GetFieldObject<mirror::Object, kVerifyNone>(off);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700677 mirror::Object* moved_object = patcher_->RelocatedAddressOfPointer(referent);
Alex Light53cb16b2014-06-12 11:26:29 -0700678 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(off, moved_object);
679}
680
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700681void PatchOat::PatchVisitor::operator() (mirror::Class* cls ATTRIBUTE_UNUSED,
682 mirror::Reference* ref) const {
Alex Light53cb16b2014-06-12 11:26:29 -0700683 MemberOffset off = mirror::Reference::ReferentOffset();
684 mirror::Object* referent = ref->GetReferent();
Jeff Hao0d2af302016-01-04 17:38:06 -0800685 DCHECK(patcher_->InHeap(referent)) << "Referent is not in the heap.";
Mathieu Chartierc7853442015-03-27 14:35:38 -0700686 mirror::Object* moved_object = patcher_->RelocatedAddressOfPointer(referent);
Alex Light53cb16b2014-06-12 11:26:29 -0700687 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(off, moved_object);
688}
689
Alex Light53cb16b2014-06-12 11:26:29 -0700690// Called by BitmapCallback
691void PatchOat::VisitObject(mirror::Object* object) {
692 mirror::Object* copy = RelocatedCopyOf(object);
693 CHECK(copy != nullptr);
694 if (kUseBakerOrBrooksReadBarrier) {
695 object->AssertReadBarrierPointer();
696 if (kUseBrooksReadBarrier) {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700697 mirror::Object* moved_to = RelocatedAddressOfPointer(object);
Alex Light53cb16b2014-06-12 11:26:29 -0700698 copy->SetReadBarrierPointer(moved_to);
699 DCHECK_EQ(copy->GetReadBarrierPointer(), moved_to);
700 }
701 }
702 PatchOat::PatchVisitor visitor(this, copy);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -0700703 object->VisitReferences<kVerifyNone>(visitor, visitor);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700704 if (object->IsClass<kVerifyNone>()) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -0800705 const size_t pointer_size = InstructionSetPointerSize(isa_);
706 mirror::Class* klass = object->AsClass();
707 mirror::Class* copy_klass = down_cast<mirror::Class*>(copy);
708 RelocatedPointerVisitor native_visitor(this);
709 klass->FixupNativePointers(copy_klass, pointer_size, native_visitor);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700710 auto* vtable = klass->GetVTable();
711 if (vtable != nullptr) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800712 vtable->Fixup(RelocatedCopyOfFollowImages(vtable), pointer_size, native_visitor);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700713 }
714 auto* iftable = klass->GetIfTable();
715 if (iftable != nullptr) {
716 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
717 if (iftable->GetMethodArrayCount(i) > 0) {
718 auto* method_array = iftable->GetMethodArray(i);
719 CHECK(method_array != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800720 method_array->Fixup(RelocatedCopyOfFollowImages(method_array),
721 pointer_size,
722 native_visitor);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700723 }
724 }
725 }
Mathieu Chartier4b00d342015-11-13 10:42:08 -0800726 } else if (object->GetClass() == mirror::Method::StaticClass() ||
727 object->GetClass() == mirror::Constructor::StaticClass()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700728 // Need to go update the ArtMethod.
729 auto* dest = down_cast<mirror::AbstractMethod*>(copy);
730 auto* src = down_cast<mirror::AbstractMethod*>(object);
731 dest->SetArtMethod(RelocatedAddressOfPointer(src->GetArtMethod()));
Alex Light53cb16b2014-06-12 11:26:29 -0700732 }
733}
734
Mathieu Chartiere401d142015-04-22 13:56:20 -0700735void PatchOat::FixupMethod(ArtMethod* object, ArtMethod* copy) {
Mathieu Chartier2d721012014-11-10 11:08:06 -0800736 const size_t pointer_size = InstructionSetPointerSize(isa_);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700737 copy->CopyFrom(object, pointer_size);
Alex Light53cb16b2014-06-12 11:26:29 -0700738 // Just update the entry points if it looks like we should.
Alex Lighteefbe392014-07-08 09:53:18 -0700739 // TODO: sanity check all the pointers' values
Mathieu Chartiere401d142015-04-22 13:56:20 -0700740 copy->SetDeclaringClass(RelocatedAddressOfPointer(object->GetDeclaringClass()));
Vladimir Marko05792b92015-08-03 11:56:49 +0100741 copy->SetDexCacheResolvedMethods(
742 RelocatedAddressOfPointer(object->GetDexCacheResolvedMethods(pointer_size)), pointer_size);
743 copy->SetDexCacheResolvedTypes(
744 RelocatedAddressOfPointer(object->GetDexCacheResolvedTypes(pointer_size)), pointer_size);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700745 copy->SetEntryPointFromQuickCompiledCodePtrSize(RelocatedAddressOfPointer(
746 object->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size)), pointer_size);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700747 copy->SetEntryPointFromJniPtrSize(RelocatedAddressOfPointer(
748 object->GetEntryPointFromJniPtrSize(pointer_size)), pointer_size);
Alex Light53cb16b2014-06-12 11:26:29 -0700749}
750
Igor Murashkin46774762014-10-22 11:37:02 -0700751bool PatchOat::Patch(File* input_oat, off_t delta, File* output_oat, TimingLogger* timings,
752 bool output_oat_opened_from_fd, bool new_oat_out) {
Alex Light53cb16b2014-06-12 11:26:29 -0700753 CHECK(input_oat != nullptr);
754 CHECK(output_oat != nullptr);
755 CHECK_GE(input_oat->Fd(), 0);
756 CHECK_GE(output_oat->Fd(), 0);
Alex Lighteefbe392014-07-08 09:53:18 -0700757 TimingLogger::ScopedTiming t("Setup Oat File Patching", timings);
Alex Light53cb16b2014-06-12 11:26:29 -0700758
759 std::string error_msg;
Igor Murashkin46774762014-10-22 11:37:02 -0700760 std::unique_ptr<ElfFile> elf(ElfFile::Open(input_oat,
Alex Light53cb16b2014-06-12 11:26:29 -0700761 PROT_READ | PROT_WRITE, MAP_PRIVATE, &error_msg));
762 if (elf.get() == nullptr) {
763 LOG(ERROR) << "unable to open oat file " << input_oat->GetPath() << " : " << error_msg;
764 return false;
765 }
766
Igor Murashkin46774762014-10-22 11:37:02 -0700767 MaybePic is_oat_pic = IsOatPic(elf.get());
768 if (is_oat_pic >= ERROR_FIRST) {
769 // Error logged by IsOatPic
770 return false;
771 } else if (is_oat_pic == PIC) {
772 // Do not need to do ELF-file patching. Create a symlink and skip the rest.
773 // Any errors will be logged by the function call.
774 return ReplaceOatFileWithSymlink(input_oat->GetPath(),
775 output_oat->GetPath(),
776 output_oat_opened_from_fd,
777 new_oat_out);
778 } else {
779 CHECK(is_oat_pic == NOT_PIC);
780 }
781
Alex Light53cb16b2014-06-12 11:26:29 -0700782 PatchOat p(elf.release(), delta, timings);
783 t.NewTiming("Patch Oat file");
784 if (!p.PatchElf()) {
785 return false;
786 }
787
788 t.NewTiming("Writing oat file");
789 if (!p.WriteElf(output_oat)) {
790 return false;
791 }
792 return true;
793}
794
Tong Shen62d1ca32014-09-03 17:24:56 -0700795template <typename ElfFileImpl>
796bool PatchOat::PatchOatHeader(ElfFileImpl* oat_file) {
797 auto rodata_sec = oat_file->FindSectionByName(".rodata");
Alex Lighta59dd802014-07-02 16:28:08 -0700798 if (rodata_sec == nullptr) {
799 return false;
800 }
Tong Shen62d1ca32014-09-03 17:24:56 -0700801 OatHeader* oat_header = reinterpret_cast<OatHeader*>(oat_file->Begin() + rodata_sec->sh_offset);
Alex Lighta59dd802014-07-02 16:28:08 -0700802 if (!oat_header->IsValid()) {
Tong Shen62d1ca32014-09-03 17:24:56 -0700803 LOG(ERROR) << "Elf file " << oat_file->GetFile().GetPath() << " has an invalid oat header";
Alex Lighta59dd802014-07-02 16:28:08 -0700804 return false;
805 }
806 oat_header->RelocateOat(delta_);
807 return true;
808}
809
Alex Light53cb16b2014-06-12 11:26:29 -0700810bool PatchOat::PatchElf() {
Ian Rogersd4c4d952014-10-16 20:31:53 -0700811 if (oat_file_->Is64Bit())
Tong Shen62d1ca32014-09-03 17:24:56 -0700812 return PatchElf<ElfFileImpl64>(oat_file_->GetImpl64());
813 else
814 return PatchElf<ElfFileImpl32>(oat_file_->GetImpl32());
815}
816
817template <typename ElfFileImpl>
818bool PatchOat::PatchElf(ElfFileImpl* oat_file) {
Alex Lighta59dd802014-07-02 16:28:08 -0700819 TimingLogger::ScopedTiming t("Fixup Elf Text Section", timings_);
Vladimir Marko3fc99032015-05-13 19:06:30 +0100820
821 // Fix up absolute references to locations within the boot image.
David Srbecky2f6cdb02015-04-11 00:17:53 +0100822 if (!oat_file->ApplyOatPatchesTo(".text", delta_)) {
Alex Lighta59dd802014-07-02 16:28:08 -0700823 return false;
824 }
825
Vladimir Marko3fc99032015-05-13 19:06:30 +0100826 // Update the OatHeader fields referencing the boot image.
Tong Shen62d1ca32014-09-03 17:24:56 -0700827 if (!PatchOatHeader<ElfFileImpl>(oat_file)) {
Alex Lighta59dd802014-07-02 16:28:08 -0700828 return false;
829 }
830
Vladimir Marko3fc99032015-05-13 19:06:30 +0100831 bool need_boot_oat_fixup = true;
Ian Rogersd4c4d952014-10-16 20:31:53 -0700832 for (unsigned int i = 0; i < oat_file->GetProgramHeaderNum(); ++i) {
Tong Shen62d1ca32014-09-03 17:24:56 -0700833 auto hdr = oat_file->GetProgramHeader(i);
Vladimir Marko3fc99032015-05-13 19:06:30 +0100834 if (hdr->p_type == PT_LOAD && hdr->p_vaddr == 0u) {
835 need_boot_oat_fixup = false;
Ian Rogersd4c4d952014-10-16 20:31:53 -0700836 break;
Alex Light53cb16b2014-06-12 11:26:29 -0700837 }
838 }
Vladimir Marko3fc99032015-05-13 19:06:30 +0100839 if (!need_boot_oat_fixup) {
840 // This is an app oat file that can be loaded at an arbitrary address in memory.
841 // Boot image references were patched above and there's nothing else to do.
Alex Lighta59dd802014-07-02 16:28:08 -0700842 return true;
843 }
Tong Shen62d1ca32014-09-03 17:24:56 -0700844
Vladimir Marko3fc99032015-05-13 19:06:30 +0100845 // This is a boot oat file that's loaded at a particular address and we need
846 // to patch all absolute addresses, starting with ELF program headers.
847
Tong Shen62d1ca32014-09-03 17:24:56 -0700848 t.NewTiming("Fixup Elf Headers");
849 // Fixup Phdr's
850 oat_file->FixupProgramHeaders(delta_);
851
Alex Lighta59dd802014-07-02 16:28:08 -0700852 t.NewTiming("Fixup Section Headers");
Tong Shen62d1ca32014-09-03 17:24:56 -0700853 // Fixup Shdr's
854 oat_file->FixupSectionHeaders(delta_);
Alex Light53cb16b2014-06-12 11:26:29 -0700855
Alex Lighta59dd802014-07-02 16:28:08 -0700856 t.NewTiming("Fixup Dynamics");
Tong Shen62d1ca32014-09-03 17:24:56 -0700857 oat_file->FixupDynamic(delta_);
Alex Light53cb16b2014-06-12 11:26:29 -0700858
859 t.NewTiming("Fixup Elf Symbols");
860 // Fixup dynsym
Tong Shen62d1ca32014-09-03 17:24:56 -0700861 if (!oat_file->FixupSymbols(delta_, true)) {
Alex Light53cb16b2014-06-12 11:26:29 -0700862 return false;
863 }
Alex Light53cb16b2014-06-12 11:26:29 -0700864 // Fixup symtab
Tong Shen62d1ca32014-09-03 17:24:56 -0700865 if (!oat_file->FixupSymbols(delta_, false)) {
866 return false;
Alex Light53cb16b2014-06-12 11:26:29 -0700867 }
868
Yevgeny Roubane3ea8382014-08-08 16:29:38 +0700869 t.NewTiming("Fixup Debug Sections");
Tong Shen62d1ca32014-09-03 17:24:56 -0700870 if (!oat_file->FixupDebugSections(delta_)) {
Yevgeny Roubane3ea8382014-08-08 16:29:38 +0700871 return false;
872 }
873
Alex Light53cb16b2014-06-12 11:26:29 -0700874 return true;
875}
876
Alex Light53cb16b2014-06-12 11:26:29 -0700877static int orig_argc;
878static char** orig_argv;
879
880static std::string CommandLine() {
881 std::vector<std::string> command;
882 for (int i = 0; i < orig_argc; ++i) {
883 command.push_back(orig_argv[i]);
884 }
885 return Join(command, ' ');
886}
887
888static void UsageErrorV(const char* fmt, va_list ap) {
889 std::string error;
890 StringAppendV(&error, fmt, ap);
891 LOG(ERROR) << error;
892}
893
894static void UsageError(const char* fmt, ...) {
895 va_list ap;
896 va_start(ap, fmt);
897 UsageErrorV(fmt, ap);
898 va_end(ap);
899}
900
Andreas Gampe794ad762015-02-23 08:12:24 -0800901NO_RETURN static void Usage(const char *fmt, ...) {
Alex Light53cb16b2014-06-12 11:26:29 -0700902 va_list ap;
903 va_start(ap, fmt);
904 UsageErrorV(fmt, ap);
905 va_end(ap);
906
907 UsageError("Command: %s", CommandLine().c_str());
908 UsageError("Usage: patchoat [options]...");
909 UsageError("");
910 UsageError(" --instruction-set=<isa>: Specifies the instruction set the patched code is");
911 UsageError(" compiled for. Required if you use --input-oat-location");
912 UsageError("");
913 UsageError(" --input-oat-file=<file.oat>: Specifies the exact filename of the oat file to be");
914 UsageError(" patched.");
915 UsageError("");
916 UsageError(" --input-oat-fd=<file-descriptor>: Specifies the file-descriptor of the oat file");
917 UsageError(" to be patched.");
918 UsageError("");
919 UsageError(" --input-oat-location=<file.oat>: Specifies the 'location' to read the patched");
920 UsageError(" oat file from. If used one must also supply the --instruction-set");
921 UsageError("");
922 UsageError(" --input-image-location=<file.art>: Specifies the 'location' of the image file to");
923 UsageError(" be patched. If --instruction-set is not given it will use the instruction set");
924 UsageError(" extracted from the --input-oat-file.");
925 UsageError("");
926 UsageError(" --output-oat-file=<file.oat>: Specifies the exact file to write the patched oat");
927 UsageError(" file to.");
928 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700929 UsageError(" --output-oat-fd=<file-descriptor>: Specifies the file-descriptor to write the");
930 UsageError(" the patched oat file to.");
931 UsageError("");
932 UsageError(" --output-image-file=<file.art>: Specifies the exact file to write the patched");
933 UsageError(" image file to.");
934 UsageError("");
935 UsageError(" --output-image-fd=<file-descriptor>: Specifies the file-descriptor to write the");
936 UsageError(" the patched image file to.");
937 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700938 UsageError(" --orig-base-offset=<original-base-offset>: Specify the base offset the input file");
939 UsageError(" was compiled with. This is needed if one is specifying a --base-offset");
940 UsageError("");
941 UsageError(" --base-offset=<new-base-offset>: Specify the base offset we will repatch the");
942 UsageError(" given files to use. This requires that --orig-base-offset is also given.");
943 UsageError("");
944 UsageError(" --base-offset-delta=<delta>: Specify the amount to change the old base-offset by.");
945 UsageError(" This value may be negative.");
946 UsageError("");
Alex Light0eb76d22015-08-11 18:03:47 -0700947 UsageError(" --patched-image-file=<file.art>: Relocate the oat file to be the same as the");
948 UsageError(" given image file.");
Alex Light53cb16b2014-06-12 11:26:29 -0700949 UsageError("");
Alex Light0eb76d22015-08-11 18:03:47 -0700950 UsageError(" --patched-image-location=<file.art>: Relocate the oat file to be the same as the");
951 UsageError(" image at the given location. If used one must also specify the");
Alex Lighta59dd802014-07-02 16:28:08 -0700952 UsageError(" --instruction-set flag. It will search for this image in the same way that");
953 UsageError(" is done when loading one.");
Alex Light53cb16b2014-06-12 11:26:29 -0700954 UsageError("");
Alex Lightcf4bf382014-07-24 11:29:14 -0700955 UsageError(" --lock-output: Obtain a flock on output oat file before starting.");
956 UsageError("");
957 UsageError(" --no-lock-output: Do not attempt to obtain a flock on output oat file.");
958 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700959 UsageError(" --dump-timings: dump out patch timing information");
960 UsageError("");
961 UsageError(" --no-dump-timings: do not dump out patch timing information");
962 UsageError("");
963
964 exit(EXIT_FAILURE);
965}
966
Alex Lighteefbe392014-07-08 09:53:18 -0700967static bool ReadBaseDelta(const char* name, off_t* delta, std::string* error_msg) {
Alex Light53cb16b2014-06-12 11:26:29 -0700968 CHECK(name != nullptr);
969 CHECK(delta != nullptr);
970 std::unique_ptr<File> file;
971 if (OS::FileExists(name)) {
972 file.reset(OS::OpenFileForReading(name));
973 if (file.get() == nullptr) {
Alex Lighteefbe392014-07-08 09:53:18 -0700974 *error_msg = "Failed to open file %s for reading";
Alex Light53cb16b2014-06-12 11:26:29 -0700975 return false;
976 }
977 } else {
Alex Lighteefbe392014-07-08 09:53:18 -0700978 *error_msg = "File %s does not exist";
Alex Light53cb16b2014-06-12 11:26:29 -0700979 return false;
980 }
981 CHECK(file.get() != nullptr);
982 ImageHeader hdr;
983 if (sizeof(hdr) != file->Read(reinterpret_cast<char*>(&hdr), sizeof(hdr), 0)) {
Alex Lighteefbe392014-07-08 09:53:18 -0700984 *error_msg = "Failed to read file %s";
Alex Light53cb16b2014-06-12 11:26:29 -0700985 return false;
986 }
987 if (!hdr.IsValid()) {
Alex Lighteefbe392014-07-08 09:53:18 -0700988 *error_msg = "%s does not contain a valid image header.";
Alex Light53cb16b2014-06-12 11:26:29 -0700989 return false;
990 }
991 *delta = hdr.GetPatchDelta();
992 return true;
993}
994
Alex Lighteefbe392014-07-08 09:53:18 -0700995static int patchoat(int argc, char **argv) {
Alex Light53cb16b2014-06-12 11:26:29 -0700996 InitLogging(argv);
Mathieu Chartier6e88ef62014-10-14 15:01:24 -0700997 MemMap::Init();
Alex Light53cb16b2014-06-12 11:26:29 -0700998 const bool debug = kIsDebugBuild;
999 orig_argc = argc;
1000 orig_argv = argv;
1001 TimingLogger timings("patcher", false, false);
1002
1003 InitLogging(argv);
1004
1005 // Skip over the command name.
1006 argv++;
1007 argc--;
1008
1009 if (argc == 0) {
1010 Usage("No arguments specified");
1011 }
1012
1013 timings.StartTiming("Patchoat");
1014
1015 // cmd line args
1016 bool isa_set = false;
1017 InstructionSet isa = kNone;
1018 std::string input_oat_filename;
1019 std::string input_oat_location;
1020 int input_oat_fd = -1;
1021 bool have_input_oat = false;
1022 std::string input_image_location;
1023 std::string output_oat_filename;
Alex Light53cb16b2014-06-12 11:26:29 -07001024 int output_oat_fd = -1;
1025 bool have_output_oat = false;
1026 std::string output_image_filename;
Alex Light53cb16b2014-06-12 11:26:29 -07001027 int output_image_fd = -1;
1028 bool have_output_image = false;
1029 uintptr_t base_offset = 0;
1030 bool base_offset_set = false;
1031 uintptr_t orig_base_offset = 0;
1032 bool orig_base_offset_set = false;
1033 off_t base_delta = 0;
1034 bool base_delta_set = false;
Alex Light0eb76d22015-08-11 18:03:47 -07001035 bool match_delta = false;
Alex Light53cb16b2014-06-12 11:26:29 -07001036 std::string patched_image_filename;
1037 std::string patched_image_location;
1038 bool dump_timings = kIsDebugBuild;
Alex Lightcf4bf382014-07-24 11:29:14 -07001039 bool lock_output = true;
Alex Light53cb16b2014-06-12 11:26:29 -07001040
Ian Rogersd4c4d952014-10-16 20:31:53 -07001041 for (int i = 0; i < argc; ++i) {
Alex Light53cb16b2014-06-12 11:26:29 -07001042 const StringPiece option(argv[i]);
1043 const bool log_options = false;
1044 if (log_options) {
1045 LOG(INFO) << "patchoat: option[" << i << "]=" << argv[i];
1046 }
Alex Light53cb16b2014-06-12 11:26:29 -07001047 if (option.starts_with("--instruction-set=")) {
1048 isa_set = true;
1049 const char* isa_str = option.substr(strlen("--instruction-set=")).data();
Andreas Gampe20c89302014-08-19 17:28:06 -07001050 isa = GetInstructionSetFromString(isa_str);
1051 if (isa == kNone) {
1052 Usage("Unknown or invalid instruction set %s", isa_str);
Alex Light53cb16b2014-06-12 11:26:29 -07001053 }
1054 } else if (option.starts_with("--input-oat-location=")) {
1055 if (have_input_oat) {
1056 Usage("Only one of --input-oat-file, --input-oat-location and --input-oat-fd may be used.");
1057 }
1058 have_input_oat = true;
1059 input_oat_location = option.substr(strlen("--input-oat-location=")).data();
1060 } else if (option.starts_with("--input-oat-file=")) {
1061 if (have_input_oat) {
1062 Usage("Only one of --input-oat-file, --input-oat-location and --input-oat-fd may be used.");
1063 }
1064 have_input_oat = true;
1065 input_oat_filename = option.substr(strlen("--input-oat-file=")).data();
1066 } else if (option.starts_with("--input-oat-fd=")) {
1067 if (have_input_oat) {
1068 Usage("Only one of --input-oat-file, --input-oat-location and --input-oat-fd may be used.");
1069 }
1070 have_input_oat = true;
1071 const char* oat_fd_str = option.substr(strlen("--input-oat-fd=")).data();
1072 if (!ParseInt(oat_fd_str, &input_oat_fd)) {
1073 Usage("Failed to parse --input-oat-fd argument '%s' as an integer", oat_fd_str);
1074 }
1075 if (input_oat_fd < 0) {
1076 Usage("--input-oat-fd pass a negative value %d", input_oat_fd);
1077 }
1078 } else if (option.starts_with("--input-image-location=")) {
1079 input_image_location = option.substr(strlen("--input-image-location=")).data();
Alex Light53cb16b2014-06-12 11:26:29 -07001080 } else if (option.starts_with("--output-oat-file=")) {
1081 if (have_output_oat) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001082 Usage("Only one of --output-oat-file, and --output-oat-fd may be used.");
Alex Light53cb16b2014-06-12 11:26:29 -07001083 }
1084 have_output_oat = true;
1085 output_oat_filename = option.substr(strlen("--output-oat-file=")).data();
1086 } else if (option.starts_with("--output-oat-fd=")) {
1087 if (have_output_oat) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001088 Usage("Only one of --output-oat-file, --output-oat-fd may be used.");
Alex Light53cb16b2014-06-12 11:26:29 -07001089 }
1090 have_output_oat = true;
1091 const char* oat_fd_str = option.substr(strlen("--output-oat-fd=")).data();
1092 if (!ParseInt(oat_fd_str, &output_oat_fd)) {
1093 Usage("Failed to parse --output-oat-fd argument '%s' as an integer", oat_fd_str);
1094 }
1095 if (output_oat_fd < 0) {
1096 Usage("--output-oat-fd pass a negative value %d", output_oat_fd);
1097 }
Alex Light53cb16b2014-06-12 11:26:29 -07001098 } else if (option.starts_with("--output-image-file=")) {
1099 if (have_output_image) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001100 Usage("Only one of --output-image-file, and --output-image-fd may be used.");
Alex Light53cb16b2014-06-12 11:26:29 -07001101 }
1102 have_output_image = true;
1103 output_image_filename = option.substr(strlen("--output-image-file=")).data();
1104 } else if (option.starts_with("--output-image-fd=")) {
1105 if (have_output_image) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001106 Usage("Only one of --output-image-file, and --output-image-fd may be used.");
Alex Light53cb16b2014-06-12 11:26:29 -07001107 }
1108 have_output_image = true;
1109 const char* image_fd_str = option.substr(strlen("--output-image-fd=")).data();
1110 if (!ParseInt(image_fd_str, &output_image_fd)) {
1111 Usage("Failed to parse --output-image-fd argument '%s' as an integer", image_fd_str);
1112 }
1113 if (output_image_fd < 0) {
1114 Usage("--output-image-fd pass a negative value %d", output_image_fd);
1115 }
1116 } else if (option.starts_with("--orig-base-offset=")) {
1117 const char* orig_base_offset_str = option.substr(strlen("--orig-base-offset=")).data();
1118 orig_base_offset_set = true;
1119 if (!ParseUint(orig_base_offset_str, &orig_base_offset)) {
1120 Usage("Failed to parse --orig-base-offset argument '%s' as an uintptr_t",
1121 orig_base_offset_str);
1122 }
1123 } else if (option.starts_with("--base-offset=")) {
1124 const char* base_offset_str = option.substr(strlen("--base-offset=")).data();
1125 base_offset_set = true;
1126 if (!ParseUint(base_offset_str, &base_offset)) {
1127 Usage("Failed to parse --base-offset argument '%s' as an uintptr_t", base_offset_str);
1128 }
1129 } else if (option.starts_with("--base-offset-delta=")) {
1130 const char* base_delta_str = option.substr(strlen("--base-offset-delta=")).data();
1131 base_delta_set = true;
1132 if (!ParseInt(base_delta_str, &base_delta)) {
1133 Usage("Failed to parse --base-offset-delta argument '%s' as an off_t", base_delta_str);
1134 }
1135 } else if (option.starts_with("--patched-image-location=")) {
1136 patched_image_location = option.substr(strlen("--patched-image-location=")).data();
1137 } else if (option.starts_with("--patched-image-file=")) {
1138 patched_image_filename = option.substr(strlen("--patched-image-file=")).data();
Alex Lightcf4bf382014-07-24 11:29:14 -07001139 } else if (option == "--lock-output") {
1140 lock_output = true;
1141 } else if (option == "--no-lock-output") {
1142 lock_output = false;
Alex Light53cb16b2014-06-12 11:26:29 -07001143 } else if (option == "--dump-timings") {
1144 dump_timings = true;
1145 } else if (option == "--no-dump-timings") {
1146 dump_timings = false;
1147 } else {
1148 Usage("Unknown argument %s", option.data());
1149 }
1150 }
1151
1152 {
1153 // Only 1 of these may be set.
1154 uint32_t cnt = 0;
1155 cnt += (base_delta_set) ? 1 : 0;
1156 cnt += (base_offset_set && orig_base_offset_set) ? 1 : 0;
1157 cnt += (!patched_image_filename.empty()) ? 1 : 0;
1158 cnt += (!patched_image_location.empty()) ? 1 : 0;
1159 if (cnt > 1) {
1160 Usage("Only one of --base-offset/--orig-base-offset, --base-offset-delta, "
1161 "--patched-image-filename or --patched-image-location may be used.");
1162 } else if (cnt == 0) {
1163 Usage("Must specify --base-offset-delta, --base-offset and --orig-base-offset, "
1164 "--patched-image-location or --patched-image-file");
1165 }
1166 }
1167
1168 if (have_input_oat != have_output_oat) {
1169 Usage("Either both input and output oat must be supplied or niether must be.");
1170 }
1171
1172 if ((!input_image_location.empty()) != have_output_image) {
1173 Usage("Either both input and output image must be supplied or niether must be.");
1174 }
1175
1176 // We know we have both the input and output so rename for clarity.
1177 bool have_image_files = have_output_image;
1178 bool have_oat_files = have_output_oat;
1179
Jeff Hao0d2af302016-01-04 17:38:06 -08001180 if (!have_oat_files) {
1181 if (have_image_files) {
1182 Usage("Cannot patch an image file without an oat file");
1183 } else {
1184 Usage("Must be patching either an oat file or an image file with an oat file.");
1185 }
Alex Light53cb16b2014-06-12 11:26:29 -07001186 }
1187
1188 if (!have_oat_files && !isa_set) {
1189 Usage("Must include ISA if patching an image file without an oat file.");
1190 }
1191
1192 if (!input_oat_location.empty()) {
1193 if (!isa_set) {
1194 Usage("specifying a location requires specifying an instruction set");
1195 }
Alex Lightcf4bf382014-07-24 11:29:14 -07001196 if (!LocationToFilename(input_oat_location, isa, &input_oat_filename)) {
1197 Usage("Unable to find filename for input oat location %s", input_oat_location.c_str());
1198 }
Alex Light53cb16b2014-06-12 11:26:29 -07001199 if (debug) {
1200 LOG(INFO) << "Using input-oat-file " << input_oat_filename;
1201 }
1202 }
Alex Light53cb16b2014-06-12 11:26:29 -07001203 if (!patched_image_location.empty()) {
1204 if (!isa_set) {
1205 Usage("specifying a location requires specifying an instruction set");
1206 }
Alex Lighta59dd802014-07-02 16:28:08 -07001207 std::string system_filename;
1208 bool has_system = false;
1209 std::string cache_filename;
1210 bool has_cache = false;
1211 bool has_android_data_unused = false;
Andreas Gampe3c13a792014-09-18 20:56:04 -07001212 bool is_global_cache = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001213 if (!gc::space::ImageSpace::FindImageFilename(patched_image_location.c_str(), isa,
1214 &system_filename, &has_system, &cache_filename,
Andreas Gampe3c13a792014-09-18 20:56:04 -07001215 &has_android_data_unused, &has_cache,
1216 &is_global_cache)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001217 Usage("Unable to determine image file for location %s", patched_image_location.c_str());
1218 }
1219 if (has_cache) {
1220 patched_image_filename = cache_filename;
1221 } else if (has_system) {
1222 LOG(WARNING) << "Only image file found was in /system for image location "
1223 << patched_image_location;
1224 patched_image_filename = system_filename;
1225 } else {
1226 Usage("Unable to determine image file for location %s", patched_image_location.c_str());
1227 }
Alex Light53cb16b2014-06-12 11:26:29 -07001228 if (debug) {
1229 LOG(INFO) << "Using patched-image-file " << patched_image_filename;
1230 }
1231 }
1232
1233 if (!base_delta_set) {
1234 if (orig_base_offset_set && base_offset_set) {
1235 base_delta_set = true;
1236 base_delta = base_offset - orig_base_offset;
1237 } else if (!patched_image_filename.empty()) {
Alex Light0eb76d22015-08-11 18:03:47 -07001238 if (have_image_files) {
1239 Usage("--patched-image-location should not be used when patching other images");
1240 }
Alex Light53cb16b2014-06-12 11:26:29 -07001241 base_delta_set = true;
Alex Light0eb76d22015-08-11 18:03:47 -07001242 match_delta = true;
Alex Light53cb16b2014-06-12 11:26:29 -07001243 std::string error_msg;
Alex Lighteefbe392014-07-08 09:53:18 -07001244 if (!ReadBaseDelta(patched_image_filename.c_str(), &base_delta, &error_msg)) {
Alex Light53cb16b2014-06-12 11:26:29 -07001245 Usage(error_msg.c_str(), patched_image_filename.c_str());
1246 }
1247 } else {
1248 if (base_offset_set) {
1249 Usage("Unable to determine original base offset.");
1250 } else {
1251 Usage("Must supply a desired new offset or delta.");
1252 }
1253 }
1254 }
1255
1256 if (!IsAligned<kPageSize>(base_delta)) {
1257 Usage("Base offset/delta must be alligned to a pagesize (0x%08x) boundary.", kPageSize);
1258 }
1259
1260 // Do we need to cleanup output files if we fail?
1261 bool new_image_out = false;
1262 bool new_oat_out = false;
1263
1264 std::unique_ptr<File> input_oat;
1265 std::unique_ptr<File> output_oat;
1266 std::unique_ptr<File> output_image;
1267
1268 if (have_image_files) {
1269 CHECK(!input_image_location.empty());
1270
1271 if (output_image_fd != -1) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001272 if (output_image_filename.empty()) {
1273 output_image_filename = "output-image-file";
1274 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001275 output_image.reset(new File(output_image_fd, output_image_filename, true));
Alex Light53cb16b2014-06-12 11:26:29 -07001276 } else {
1277 CHECK(!output_image_filename.empty());
1278 output_image.reset(CreateOrOpen(output_image_filename.c_str(), &new_image_out));
1279 }
1280 } else {
1281 CHECK(output_image_filename.empty() && output_image_fd == -1 && input_image_location.empty());
1282 }
1283
1284 if (have_oat_files) {
1285 if (input_oat_fd != -1) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001286 if (input_oat_filename.empty()) {
1287 input_oat_filename = "input-oat-file";
1288 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001289 input_oat.reset(new File(input_oat_fd, input_oat_filename, false));
Julien Delayena473f512015-03-05 16:37:52 +01001290 if (input_oat_fd == output_oat_fd) {
1291 input_oat.get()->DisableAutoClose();
1292 }
Igor Murashkin46774762014-10-22 11:37:02 -07001293 if (input_oat == nullptr) {
1294 // Unlikely, but ensure exhaustive logging in non-0 exit code case
1295 LOG(ERROR) << "Failed to open input oat file by its FD" << input_oat_fd;
1296 }
Alex Light53cb16b2014-06-12 11:26:29 -07001297 } else {
1298 CHECK(!input_oat_filename.empty());
1299 input_oat.reset(OS::OpenFileForReading(input_oat_filename.c_str()));
Igor Murashkin46774762014-10-22 11:37:02 -07001300 if (input_oat == nullptr) {
1301 int err = errno;
1302 LOG(ERROR) << "Failed to open input oat file " << input_oat_filename
1303 << ": " << strerror(err) << "(" << err << ")";
Andreas Gampe1c83cbc2014-07-22 18:52:29 -07001304 }
Alex Light53cb16b2014-06-12 11:26:29 -07001305 }
1306
1307 if (output_oat_fd != -1) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001308 if (output_oat_filename.empty()) {
1309 output_oat_filename = "output-oat-file";
Alex Lighta59dd802014-07-02 16:28:08 -07001310 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001311 output_oat.reset(new File(output_oat_fd, output_oat_filename, true));
Igor Murashkin46774762014-10-22 11:37:02 -07001312 if (output_oat == nullptr) {
1313 // Unlikely, but ensure exhaustive logging in non-0 exit code case
1314 LOG(ERROR) << "Failed to open output oat file by its FD" << output_oat_fd;
1315 }
Alex Light53cb16b2014-06-12 11:26:29 -07001316 } else {
1317 CHECK(!output_oat_filename.empty());
1318 output_oat.reset(CreateOrOpen(output_oat_filename.c_str(), &new_oat_out));
Igor Murashkin46774762014-10-22 11:37:02 -07001319 if (output_oat == nullptr) {
1320 int err = errno;
1321 LOG(ERROR) << "Failed to open output oat file " << output_oat_filename
1322 << ": " << strerror(err) << "(" << err << ")";
1323 }
Alex Light53cb16b2014-06-12 11:26:29 -07001324 }
1325 }
1326
Igor Murashkin46774762014-10-22 11:37:02 -07001327 // TODO: get rid of this.
Alex Light53cb16b2014-06-12 11:26:29 -07001328 auto cleanup = [&output_image_filename, &output_oat_filename,
1329 &new_oat_out, &new_image_out, &timings, &dump_timings](bool success) {
1330 timings.EndTiming();
1331 if (!success) {
1332 if (new_oat_out) {
1333 CHECK(!output_oat_filename.empty());
Brian Carlstrom8c52a3f2014-09-30 16:18:01 -07001334 TEMP_FAILURE_RETRY(unlink(output_oat_filename.c_str()));
Alex Light53cb16b2014-06-12 11:26:29 -07001335 }
1336 if (new_image_out) {
1337 CHECK(!output_image_filename.empty());
Brian Carlstrom8c52a3f2014-09-30 16:18:01 -07001338 TEMP_FAILURE_RETRY(unlink(output_image_filename.c_str()));
Alex Light53cb16b2014-06-12 11:26:29 -07001339 }
1340 }
1341 if (dump_timings) {
1342 LOG(INFO) << Dumpable<TimingLogger>(timings);
1343 }
Igor Murashkin46774762014-10-22 11:37:02 -07001344
1345 if (kIsDebugBuild) {
1346 LOG(INFO) << "Cleaning up.. success? " << success;
1347 }
Alex Light53cb16b2014-06-12 11:26:29 -07001348 };
1349
Igor Murashkin46774762014-10-22 11:37:02 -07001350 if (have_oat_files && (input_oat.get() == nullptr || output_oat.get() == nullptr)) {
1351 LOG(ERROR) << "Failed to open input/output oat files";
1352 cleanup(false);
1353 return EXIT_FAILURE;
1354 } else if (have_image_files && output_image.get() == nullptr) {
1355 LOG(ERROR) << "Failed to open output image file";
Alex Lightcf4bf382014-07-24 11:29:14 -07001356 cleanup(false);
1357 return EXIT_FAILURE;
1358 }
1359
Alex Light0eb76d22015-08-11 18:03:47 -07001360 if (match_delta) {
1361 CHECK(!have_image_files); // We will not do this with images.
1362 std::string error_msg;
1363 // Figure out what the current delta is so we can match it to the desired delta.
1364 std::unique_ptr<ElfFile> elf(ElfFile::Open(input_oat.get(), PROT_READ, MAP_PRIVATE,
1365 &error_msg));
1366 off_t current_delta = 0;
1367 if (elf.get() == nullptr) {
1368 LOG(ERROR) << "unable to open oat file " << input_oat->GetPath() << " : " << error_msg;
1369 cleanup(false);
1370 return EXIT_FAILURE;
1371 } else if (!ReadOatPatchDelta(elf.get(), &current_delta, &error_msg)) {
1372 LOG(ERROR) << "Unable to get current delta: " << error_msg;
1373 cleanup(false);
1374 return EXIT_FAILURE;
1375 }
1376 // Before this line base_delta is the desired final delta. We need it to be the actual amount to
1377 // change everything by. We subtract the current delta from it to make it this.
1378 base_delta -= current_delta;
1379 if (!IsAligned<kPageSize>(base_delta)) {
1380 LOG(ERROR) << "Given image file was relocated by an illegal delta";
1381 cleanup(false);
1382 return false;
1383 }
1384 }
1385
Igor Murashkin46774762014-10-22 11:37:02 -07001386 if (debug) {
1387 LOG(INFO) << "moving offset by " << base_delta
1388 << " (0x" << std::hex << base_delta << ") bytes or "
1389 << std::dec << (base_delta/kPageSize) << " pages.";
1390 }
1391
1392 // TODO: is it going to be promatic to unlink a file that was flock-ed?
Alex Lightcf4bf382014-07-24 11:29:14 -07001393 ScopedFlock output_oat_lock;
1394 if (lock_output) {
1395 std::string error_msg;
1396 if (have_oat_files && !output_oat_lock.Init(output_oat.get(), &error_msg)) {
1397 LOG(ERROR) << "Unable to lock output oat " << output_image->GetPath() << ": " << error_msg;
1398 cleanup(false);
1399 return EXIT_FAILURE;
1400 }
1401 }
1402
Alex Light53cb16b2014-06-12 11:26:29 -07001403 bool ret;
1404 if (have_image_files && have_oat_files) {
1405 TimingLogger::ScopedTiming pt("patch image and oat", &timings);
1406 ret = PatchOat::Patch(input_oat.get(), input_image_location, base_delta,
Igor Murashkin46774762014-10-22 11:37:02 -07001407 output_oat.get(), output_image.get(), isa, &timings,
1408 output_oat_fd >= 0, // was it opened from FD?
1409 new_oat_out);
Andreas Gampe4303ba92014-11-06 01:00:46 -08001410 // The order here doesn't matter. If the first one is successfully saved and the second one
1411 // erased, ImageSpace will still detect a problem and not use the files.
Alex Light0eb76d22015-08-11 18:03:47 -07001412 ret = FinishFile(output_image.get(), ret);
1413 ret = FinishFile(output_oat.get(), ret);
Alex Light53cb16b2014-06-12 11:26:29 -07001414 } else if (have_oat_files) {
1415 TimingLogger::ScopedTiming pt("patch oat", &timings);
Igor Murashkin46774762014-10-22 11:37:02 -07001416 ret = PatchOat::Patch(input_oat.get(), base_delta, output_oat.get(), &timings,
1417 output_oat_fd >= 0, // was it opened from FD?
1418 new_oat_out);
Alex Light0eb76d22015-08-11 18:03:47 -07001419 ret = FinishFile(output_oat.get(), ret);
Igor Murashkin46774762014-10-22 11:37:02 -07001420 } else {
1421 CHECK(false);
1422 ret = true;
1423 }
1424
1425 if (kIsDebugBuild) {
1426 LOG(INFO) << "Exiting with return ... " << ret;
Alex Light53cb16b2014-06-12 11:26:29 -07001427 }
1428 cleanup(ret);
Alex Light53cb16b2014-06-12 11:26:29 -07001429 return (ret) ? EXIT_SUCCESS : EXIT_FAILURE;
1430}
1431
1432} // namespace art
1433
1434int main(int argc, char **argv) {
1435 return art::patchoat(argc, argv);
1436}