blob: 50b4ece69ffb66ccdf929039ce235e37960691b7 [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
Alex Lighta59dd802014-07-02 16:28:08 -070027#include "base/scoped_flock.h"
Alex Light53cb16b2014-06-12 11:26:29 -070028#include "base/stringpiece.h"
29#include "base/stringprintf.h"
30#include "elf_utils.h"
31#include "elf_file.h"
Ian Rogerse63db272014-07-15 15:36:11 -070032#include "gc/space/image_space.h"
Alex Light53cb16b2014-06-12 11:26:29 -070033#include "image.h"
34#include "instruction_set.h"
35#include "mirror/art_field.h"
36#include "mirror/art_field-inl.h"
37#include "mirror/art_method.h"
38#include "mirror/art_method-inl.h"
39#include "mirror/object.h"
40#include "mirror/object-inl.h"
41#include "mirror/reference.h"
42#include "noop_compiler_callbacks.h"
43#include "offsets.h"
44#include "os.h"
45#include "runtime.h"
46#include "scoped_thread_state_change.h"
47#include "thread.h"
48#include "utils.h"
49
50namespace art {
51
52static InstructionSet ElfISAToInstructionSet(Elf32_Word isa) {
53 switch (isa) {
54 case EM_ARM:
55 return kArm;
56 case EM_AARCH64:
57 return kArm64;
58 case EM_386:
59 return kX86;
60 case EM_X86_64:
61 return kX86_64;
62 case EM_MIPS:
63 return kMips;
64 default:
65 return kNone;
66 }
67}
68
Alex Lightcf4bf382014-07-24 11:29:14 -070069static bool LocationToFilename(const std::string& location, InstructionSet isa,
70 std::string* filename) {
71 bool has_system = false;
72 bool has_cache = false;
73 // image_location = /system/framework/boot.art
74 // system_image_location = /system/framework/<image_isa>/boot.art
75 std::string system_filename(GetSystemImageFilename(location.c_str(), isa));
76 if (OS::FileExists(system_filename.c_str())) {
77 has_system = true;
78 }
79
80 bool have_android_data = false;
81 bool dalvik_cache_exists = false;
Andreas Gampe3c13a792014-09-18 20:56:04 -070082 bool is_global_cache = false;
Alex Lightcf4bf382014-07-24 11:29:14 -070083 std::string dalvik_cache;
84 GetDalvikCache(GetInstructionSetString(isa), false, &dalvik_cache,
Andreas Gampe3c13a792014-09-18 20:56:04 -070085 &have_android_data, &dalvik_cache_exists, &is_global_cache);
Alex Lightcf4bf382014-07-24 11:29:14 -070086
87 std::string cache_filename;
88 if (have_android_data && dalvik_cache_exists) {
89 // Always set output location even if it does not exist,
90 // so that the caller knows where to create the image.
91 //
92 // image_location = /system/framework/boot.art
93 // *image_filename = /data/dalvik-cache/<image_isa>/boot.art
94 std::string error_msg;
95 if (GetDalvikCacheFilename(location.c_str(), dalvik_cache.c_str(),
96 &cache_filename, &error_msg)) {
97 has_cache = true;
98 }
99 }
100 if (has_system) {
101 *filename = system_filename;
102 return true;
103 } else if (has_cache) {
104 *filename = cache_filename;
105 return true;
106 } else {
107 return false;
108 }
109}
110
Alex Light53cb16b2014-06-12 11:26:29 -0700111bool PatchOat::Patch(const std::string& image_location, off_t delta,
112 File* output_image, InstructionSet isa,
Alex Lighteefbe392014-07-08 09:53:18 -0700113 TimingLogger* timings) {
Alex Light53cb16b2014-06-12 11:26:29 -0700114 CHECK(Runtime::Current() == nullptr);
115 CHECK(output_image != nullptr);
116 CHECK_GE(output_image->Fd(), 0);
117 CHECK(!image_location.empty()) << "image file must have a filename.";
118 CHECK_NE(isa, kNone);
119
Alex Lighteefbe392014-07-08 09:53:18 -0700120 TimingLogger::ScopedTiming t("Runtime Setup", timings);
Alex Light53cb16b2014-06-12 11:26:29 -0700121 const char *isa_name = GetInstructionSetString(isa);
Alex Lightcf4bf382014-07-24 11:29:14 -0700122 std::string image_filename;
123 if (!LocationToFilename(image_location, isa, &image_filename)) {
124 LOG(ERROR) << "Unable to find image at location " << image_location;
125 return false;
126 }
Alex Light53cb16b2014-06-12 11:26:29 -0700127 std::unique_ptr<File> input_image(OS::OpenFileForReading(image_filename.c_str()));
128 if (input_image.get() == nullptr) {
Alex Lightcf4bf382014-07-24 11:29:14 -0700129 LOG(ERROR) << "unable to open input image file at " << image_filename
130 << " for location " << image_location;
Alex Light53cb16b2014-06-12 11:26:29 -0700131 return false;
132 }
133 int64_t image_len = input_image->GetLength();
134 if (image_len < 0) {
135 LOG(ERROR) << "Error while getting image length";
136 return false;
137 }
138 ImageHeader image_header;
139 if (sizeof(image_header) != input_image->Read(reinterpret_cast<char*>(&image_header),
140 sizeof(image_header), 0)) {
141 LOG(ERROR) << "Unable to read image header from image file " << input_image->GetPath();
142 return false;
143 }
144
145 // Set up the runtime
Ian Rogerse63db272014-07-15 15:36:11 -0700146 RuntimeOptions options;
Alex Light53cb16b2014-06-12 11:26:29 -0700147 NoopCompilerCallbacks callbacks;
148 options.push_back(std::make_pair("compilercallbacks", &callbacks));
149 std::string img = "-Ximage:" + image_location;
150 options.push_back(std::make_pair(img.c_str(), nullptr));
151 options.push_back(std::make_pair("imageinstructionset", reinterpret_cast<const void*>(isa_name)));
152 if (!Runtime::Create(options, false)) {
153 LOG(ERROR) << "Unable to initialize runtime";
154 return false;
155 }
156 // Runtime::Create acquired the mutator_lock_ that is normally given away when we Runtime::Start,
157 // give it away now and then switch to a more manageable ScopedObjectAccess.
158 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
159 ScopedObjectAccess soa(Thread::Current());
160
161 t.NewTiming("Image and oat Patching setup");
162 // Create the map where we will write the image patches to.
Alex Lighteefbe392014-07-08 09:53:18 -0700163 std::string error_msg;
Alex Light53cb16b2014-06-12 11:26:29 -0700164 std::unique_ptr<MemMap> image(MemMap::MapFile(image_len, PROT_READ | PROT_WRITE, MAP_PRIVATE,
165 input_image->Fd(), 0,
166 input_image->GetPath().c_str(),
167 &error_msg));
168 if (image.get() == nullptr) {
169 LOG(ERROR) << "unable to map image file " << input_image->GetPath() << " : " << error_msg;
170 return false;
171 }
172 gc::space::ImageSpace* ispc = Runtime::Current()->GetHeap()->GetImageSpace();
173
174 PatchOat p(image.release(), ispc->GetLiveBitmap(), ispc->GetMemMap(),
175 delta, timings);
176 t.NewTiming("Patching files");
177 if (!p.PatchImage()) {
Alex Lighta59dd802014-07-02 16:28:08 -0700178 LOG(ERROR) << "Failed to patch image file " << input_image->GetPath();
Alex Light53cb16b2014-06-12 11:26:29 -0700179 return false;
180 }
181
182 t.NewTiming("Writing files");
183 if (!p.WriteImage(output_image)) {
184 return false;
185 }
186 return true;
187}
188
189bool PatchOat::Patch(const File* input_oat, const std::string& image_location, off_t delta,
190 File* output_oat, File* output_image, InstructionSet isa,
Alex Lighteefbe392014-07-08 09:53:18 -0700191 TimingLogger* timings) {
Alex Light53cb16b2014-06-12 11:26:29 -0700192 CHECK(Runtime::Current() == nullptr);
193 CHECK(output_image != nullptr);
194 CHECK_GE(output_image->Fd(), 0);
195 CHECK(input_oat != nullptr);
196 CHECK(output_oat != nullptr);
197 CHECK_GE(input_oat->Fd(), 0);
198 CHECK_GE(output_oat->Fd(), 0);
199 CHECK(!image_location.empty()) << "image file must have a filename.";
200
Alex Lighteefbe392014-07-08 09:53:18 -0700201 TimingLogger::ScopedTiming t("Runtime Setup", timings);
Alex Light53cb16b2014-06-12 11:26:29 -0700202
203 if (isa == kNone) {
204 Elf32_Ehdr elf_hdr;
205 if (sizeof(elf_hdr) != input_oat->Read(reinterpret_cast<char*>(&elf_hdr), sizeof(elf_hdr), 0)) {
206 LOG(ERROR) << "unable to read elf header";
207 return false;
208 }
209 isa = ElfISAToInstructionSet(elf_hdr.e_machine);
210 }
211 const char* isa_name = GetInstructionSetString(isa);
Alex Lightcf4bf382014-07-24 11:29:14 -0700212 std::string image_filename;
213 if (!LocationToFilename(image_location, isa, &image_filename)) {
214 LOG(ERROR) << "Unable to find image at location " << image_location;
215 return false;
216 }
Alex Light53cb16b2014-06-12 11:26:29 -0700217 std::unique_ptr<File> input_image(OS::OpenFileForReading(image_filename.c_str()));
218 if (input_image.get() == nullptr) {
Alex Lightcf4bf382014-07-24 11:29:14 -0700219 LOG(ERROR) << "unable to open input image file at " << image_filename
220 << " for location " << image_location;
Alex Light53cb16b2014-06-12 11:26:29 -0700221 return false;
222 }
223 int64_t image_len = input_image->GetLength();
224 if (image_len < 0) {
225 LOG(ERROR) << "Error while getting image length";
226 return false;
227 }
228 ImageHeader image_header;
229 if (sizeof(image_header) != input_image->Read(reinterpret_cast<char*>(&image_header),
230 sizeof(image_header), 0)) {
231 LOG(ERROR) << "Unable to read image header from image file " << input_image->GetPath();
232 }
233
234 // Set up the runtime
Ian Rogerse63db272014-07-15 15:36:11 -0700235 RuntimeOptions options;
Alex Light53cb16b2014-06-12 11:26:29 -0700236 NoopCompilerCallbacks callbacks;
237 options.push_back(std::make_pair("compilercallbacks", &callbacks));
238 std::string img = "-Ximage:" + image_location;
239 options.push_back(std::make_pair(img.c_str(), nullptr));
240 options.push_back(std::make_pair("imageinstructionset", reinterpret_cast<const void*>(isa_name)));
241 if (!Runtime::Create(options, false)) {
242 LOG(ERROR) << "Unable to initialize runtime";
243 return false;
244 }
245 // Runtime::Create acquired the mutator_lock_ that is normally given away when we Runtime::Start,
246 // give it away now and then switch to a more manageable ScopedObjectAccess.
247 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
248 ScopedObjectAccess soa(Thread::Current());
249
250 t.NewTiming("Image and oat Patching setup");
251 // Create the map where we will write the image patches to.
Alex Lighteefbe392014-07-08 09:53:18 -0700252 std::string error_msg;
Alex Light53cb16b2014-06-12 11:26:29 -0700253 std::unique_ptr<MemMap> image(MemMap::MapFile(image_len, PROT_READ | PROT_WRITE, MAP_PRIVATE,
254 input_image->Fd(), 0,
255 input_image->GetPath().c_str(),
256 &error_msg));
257 if (image.get() == nullptr) {
258 LOG(ERROR) << "unable to map image file " << input_image->GetPath() << " : " << error_msg;
259 return false;
260 }
261 gc::space::ImageSpace* ispc = Runtime::Current()->GetHeap()->GetImageSpace();
262
263 std::unique_ptr<ElfFile> elf(ElfFile::Open(const_cast<File*>(input_oat),
264 PROT_READ | PROT_WRITE, MAP_PRIVATE, &error_msg));
265 if (elf.get() == nullptr) {
266 LOG(ERROR) << "unable to open oat file " << input_oat->GetPath() << " : " << error_msg;
267 return false;
268 }
269
270 PatchOat p(elf.release(), image.release(), ispc->GetLiveBitmap(), ispc->GetMemMap(),
271 delta, timings);
272 t.NewTiming("Patching files");
273 if (!p.PatchElf()) {
Alex Lighta59dd802014-07-02 16:28:08 -0700274 LOG(ERROR) << "Failed to patch oat file " << input_oat->GetPath();
Alex Light53cb16b2014-06-12 11:26:29 -0700275 return false;
276 }
277 if (!p.PatchImage()) {
Alex Lighta59dd802014-07-02 16:28:08 -0700278 LOG(ERROR) << "Failed to patch image file " << input_image->GetPath();
Alex Light53cb16b2014-06-12 11:26:29 -0700279 return false;
280 }
281
282 t.NewTiming("Writing files");
283 if (!p.WriteElf(output_oat)) {
284 return false;
285 }
286 if (!p.WriteImage(output_image)) {
287 return false;
288 }
289 return true;
290}
291
292bool PatchOat::WriteElf(File* out) {
Alex Lighteefbe392014-07-08 09:53:18 -0700293 TimingLogger::ScopedTiming t("Writing Elf File", timings_);
Alex Lighta59dd802014-07-02 16:28:08 -0700294
Alex Light53cb16b2014-06-12 11:26:29 -0700295 CHECK(oat_file_.get() != nullptr);
296 CHECK(out != nullptr);
297 size_t expect = oat_file_->Size();
298 if (out->WriteFully(reinterpret_cast<char*>(oat_file_->Begin()), expect) &&
299 out->SetLength(expect) == 0) {
300 return true;
301 } else {
302 LOG(ERROR) << "Writing to oat file " << out->GetPath() << " failed.";
303 return false;
304 }
305}
306
307bool PatchOat::WriteImage(File* out) {
Alex Lighteefbe392014-07-08 09:53:18 -0700308 TimingLogger::ScopedTiming t("Writing image File", timings_);
Alex Lighta59dd802014-07-02 16:28:08 -0700309 std::string error_msg;
310
Alex Lightcf4bf382014-07-24 11:29:14 -0700311 ScopedFlock img_flock;
312 img_flock.Init(out, &error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -0700313
Alex Light53cb16b2014-06-12 11:26:29 -0700314 CHECK(image_ != nullptr);
315 CHECK(out != nullptr);
316 size_t expect = image_->Size();
317 if (out->WriteFully(reinterpret_cast<char*>(image_->Begin()), expect) &&
318 out->SetLength(expect) == 0) {
319 return true;
320 } else {
321 LOG(ERROR) << "Writing to image file " << out->GetPath() << " failed.";
322 return false;
323 }
324}
325
326bool PatchOat::PatchImage() {
327 ImageHeader* image_header = reinterpret_cast<ImageHeader*>(image_->Begin());
328 CHECK_GT(image_->Size(), sizeof(ImageHeader));
329 // These are the roots from the original file.
330 mirror::Object* img_roots = image_header->GetImageRoots();
331 image_header->RelocateImage(delta_);
332
333 VisitObject(img_roots);
334 if (!image_header->IsValid()) {
335 LOG(ERROR) << "reloction renders image header invalid";
336 return false;
337 }
338
339 {
Alex Lighteefbe392014-07-08 09:53:18 -0700340 TimingLogger::ScopedTiming t("Walk Bitmap", timings_);
Alex Light53cb16b2014-06-12 11:26:29 -0700341 // Walk the bitmap.
342 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
343 bitmap_->Walk(PatchOat::BitmapCallback, this);
344 }
345 return true;
346}
347
348bool PatchOat::InHeap(mirror::Object* o) {
349 uintptr_t begin = reinterpret_cast<uintptr_t>(heap_->Begin());
350 uintptr_t end = reinterpret_cast<uintptr_t>(heap_->End());
351 uintptr_t obj = reinterpret_cast<uintptr_t>(o);
352 return o == nullptr || (begin <= obj && obj < end);
353}
354
355void PatchOat::PatchVisitor::operator() (mirror::Object* obj, MemberOffset off,
356 bool is_static_unused) const {
357 mirror::Object* referent = obj->GetFieldObject<mirror::Object, kVerifyNone>(off);
358 DCHECK(patcher_->InHeap(referent)) << "Referent is not in the heap.";
359 mirror::Object* moved_object = patcher_->RelocatedAddressOf(referent);
360 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(off, moved_object);
361}
362
363void PatchOat::PatchVisitor::operator() (mirror::Class* cls, mirror::Reference* ref) const {
364 MemberOffset off = mirror::Reference::ReferentOffset();
365 mirror::Object* referent = ref->GetReferent();
366 DCHECK(patcher_->InHeap(referent)) << "Referent is not in the heap.";
367 mirror::Object* moved_object = patcher_->RelocatedAddressOf(referent);
368 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(off, moved_object);
369}
370
371mirror::Object* PatchOat::RelocatedCopyOf(mirror::Object* obj) {
372 if (obj == nullptr) {
373 return nullptr;
374 }
375 DCHECK_GT(reinterpret_cast<uintptr_t>(obj), reinterpret_cast<uintptr_t>(heap_->Begin()));
376 DCHECK_LT(reinterpret_cast<uintptr_t>(obj), reinterpret_cast<uintptr_t>(heap_->End()));
377 uintptr_t heap_off =
378 reinterpret_cast<uintptr_t>(obj) - reinterpret_cast<uintptr_t>(heap_->Begin());
379 DCHECK_LT(heap_off, image_->Size());
380 return reinterpret_cast<mirror::Object*>(image_->Begin() + heap_off);
381}
382
383mirror::Object* PatchOat::RelocatedAddressOf(mirror::Object* obj) {
384 if (obj == nullptr) {
385 return nullptr;
386 } else {
387 return reinterpret_cast<mirror::Object*>(reinterpret_cast<byte*>(obj) + delta_);
388 }
389}
390
391// Called by BitmapCallback
392void PatchOat::VisitObject(mirror::Object* object) {
393 mirror::Object* copy = RelocatedCopyOf(object);
394 CHECK(copy != nullptr);
395 if (kUseBakerOrBrooksReadBarrier) {
396 object->AssertReadBarrierPointer();
397 if (kUseBrooksReadBarrier) {
398 mirror::Object* moved_to = RelocatedAddressOf(object);
399 copy->SetReadBarrierPointer(moved_to);
400 DCHECK_EQ(copy->GetReadBarrierPointer(), moved_to);
401 }
402 }
403 PatchOat::PatchVisitor visitor(this, copy);
404 object->VisitReferences<true, kVerifyNone>(visitor, visitor);
405 if (object->IsArtMethod<kVerifyNone>()) {
406 FixupMethod(static_cast<mirror::ArtMethod*>(object),
407 static_cast<mirror::ArtMethod*>(copy));
408 }
409}
410
411void PatchOat::FixupMethod(mirror::ArtMethod* object, mirror::ArtMethod* copy) {
412 // Just update the entry points if it looks like we should.
Alex Lighteefbe392014-07-08 09:53:18 -0700413 // TODO: sanity check all the pointers' values
Alex Light53cb16b2014-06-12 11:26:29 -0700414 uintptr_t portable = reinterpret_cast<uintptr_t>(
415 object->GetEntryPointFromPortableCompiledCode<kVerifyNone>());
416 if (portable != 0) {
417 copy->SetEntryPointFromPortableCompiledCode(reinterpret_cast<void*>(portable + delta_));
418 }
419 uintptr_t quick= reinterpret_cast<uintptr_t>(
420 object->GetEntryPointFromQuickCompiledCode<kVerifyNone>());
421 if (quick != 0) {
422 copy->SetEntryPointFromQuickCompiledCode(reinterpret_cast<void*>(quick + delta_));
423 }
424 uintptr_t interpreter = reinterpret_cast<uintptr_t>(
425 object->GetEntryPointFromInterpreter<kVerifyNone>());
426 if (interpreter != 0) {
427 copy->SetEntryPointFromInterpreter(
428 reinterpret_cast<mirror::EntryPointFromInterpreter*>(interpreter + delta_));
429 }
430
431 uintptr_t native_method = reinterpret_cast<uintptr_t>(object->GetNativeMethod());
432 if (native_method != 0) {
433 copy->SetNativeMethod(reinterpret_cast<void*>(native_method + delta_));
434 }
435
436 uintptr_t native_gc_map = reinterpret_cast<uintptr_t>(object->GetNativeGcMap());
437 if (native_gc_map != 0) {
438 copy->SetNativeGcMap(reinterpret_cast<uint8_t*>(native_gc_map + delta_));
439 }
440}
441
Alex Lighteefbe392014-07-08 09:53:18 -0700442bool PatchOat::Patch(File* input_oat, off_t delta, File* output_oat, TimingLogger* timings) {
Alex Light53cb16b2014-06-12 11:26:29 -0700443 CHECK(input_oat != nullptr);
444 CHECK(output_oat != nullptr);
445 CHECK_GE(input_oat->Fd(), 0);
446 CHECK_GE(output_oat->Fd(), 0);
Alex Lighteefbe392014-07-08 09:53:18 -0700447 TimingLogger::ScopedTiming t("Setup Oat File Patching", timings);
Alex Light53cb16b2014-06-12 11:26:29 -0700448
449 std::string error_msg;
450 std::unique_ptr<ElfFile> elf(ElfFile::Open(const_cast<File*>(input_oat),
451 PROT_READ | PROT_WRITE, MAP_PRIVATE, &error_msg));
452 if (elf.get() == nullptr) {
453 LOG(ERROR) << "unable to open oat file " << input_oat->GetPath() << " : " << error_msg;
454 return false;
455 }
456
457 PatchOat p(elf.release(), delta, timings);
458 t.NewTiming("Patch Oat file");
459 if (!p.PatchElf()) {
460 return false;
461 }
462
463 t.NewTiming("Writing oat file");
464 if (!p.WriteElf(output_oat)) {
465 return false;
466 }
467 return true;
468}
469
Alex Light4b0d2d92014-08-06 13:37:23 -0700470template <typename ptr_t>
471bool PatchOat::CheckOatFile(const Elf32_Shdr& patches_sec) {
472 if (patches_sec.sh_type != SHT_OAT_PATCH) {
Alex Light53cb16b2014-06-12 11:26:29 -0700473 return false;
474 }
Alex Light4b0d2d92014-08-06 13:37:23 -0700475 ptr_t* patches = reinterpret_cast<ptr_t*>(oat_file_->Begin() + patches_sec.sh_offset);
476 ptr_t* patches_end = patches + (patches_sec.sh_size / sizeof(ptr_t));
Alex Light53cb16b2014-06-12 11:26:29 -0700477 Elf32_Shdr* oat_data_sec = oat_file_->FindSectionByName(".rodata");
478 Elf32_Shdr* oat_text_sec = oat_file_->FindSectionByName(".text");
479 if (oat_data_sec == nullptr) {
480 return false;
481 }
482 if (oat_text_sec == nullptr) {
483 return false;
484 }
485 if (oat_text_sec->sh_offset <= oat_data_sec->sh_offset) {
486 return false;
487 }
488
489 for (; patches < patches_end; patches++) {
490 if (oat_text_sec->sh_size <= *patches) {
491 return false;
492 }
493 }
494
495 return true;
496}
497
Alex Lighta59dd802014-07-02 16:28:08 -0700498bool PatchOat::PatchOatHeader() {
499 Elf32_Shdr *rodata_sec = oat_file_->FindSectionByName(".rodata");
500 if (rodata_sec == nullptr) {
501 return false;
502 }
503 OatHeader* oat_header = reinterpret_cast<OatHeader*>(oat_file_->Begin() + rodata_sec->sh_offset);
504 if (!oat_header->IsValid()) {
505 LOG(ERROR) << "Elf file " << oat_file_->GetFile().GetPath() << " has an invalid oat header";
506 return false;
507 }
508 oat_header->RelocateOat(delta_);
509 return true;
510}
511
Alex Light53cb16b2014-06-12 11:26:29 -0700512bool PatchOat::PatchElf() {
Alex Lighta59dd802014-07-02 16:28:08 -0700513 TimingLogger::ScopedTiming t("Fixup Elf Text Section", timings_);
514 if (!PatchTextSection()) {
515 return false;
516 }
517
518 if (!PatchOatHeader()) {
519 return false;
520 }
521
522 bool need_fixup = false;
523 t.NewTiming("Fixup Elf Headers");
Alex Light53cb16b2014-06-12 11:26:29 -0700524 // Fixup Phdr's
525 for (unsigned int i = 0; i < oat_file_->GetProgramHeaderNum(); i++) {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700526 Elf32_Phdr* hdr = oat_file_->GetProgramHeader(i);
527 CHECK(hdr != nullptr);
528 if (hdr->p_vaddr != 0 && hdr->p_vaddr != hdr->p_offset) {
Alex Lighta59dd802014-07-02 16:28:08 -0700529 need_fixup = true;
Andreas Gampedaab38c2014-09-12 18:38:24 -0700530 hdr->p_vaddr += delta_;
Alex Light53cb16b2014-06-12 11:26:29 -0700531 }
Andreas Gampedaab38c2014-09-12 18:38:24 -0700532 if (hdr->p_paddr != 0 && hdr->p_paddr != hdr->p_offset) {
Alex Lighta59dd802014-07-02 16:28:08 -0700533 need_fixup = true;
Andreas Gampedaab38c2014-09-12 18:38:24 -0700534 hdr->p_paddr += delta_;
Alex Light53cb16b2014-06-12 11:26:29 -0700535 }
536 }
Alex Lighta59dd802014-07-02 16:28:08 -0700537 if (!need_fixup) {
538 // This was never passed through ElfFixup so all headers/symbols just have their offset as
539 // their addr. Therefore we do not need to update these parts.
540 return true;
541 }
542 t.NewTiming("Fixup Section Headers");
Alex Light53cb16b2014-06-12 11:26:29 -0700543 for (unsigned int i = 0; i < oat_file_->GetSectionHeaderNum(); i++) {
Andreas Gampedaab38c2014-09-12 18:38:24 -0700544 Elf32_Shdr* hdr = oat_file_->GetSectionHeader(i);
545 CHECK(hdr != nullptr);
546 if (hdr->sh_addr != 0) {
547 hdr->sh_addr += delta_;
Alex Light53cb16b2014-06-12 11:26:29 -0700548 }
549 }
550
Alex Lighta59dd802014-07-02 16:28:08 -0700551 t.NewTiming("Fixup Dynamics");
Alex Light53cb16b2014-06-12 11:26:29 -0700552 for (Elf32_Word i = 0; i < oat_file_->GetDynamicNum(); i++) {
553 Elf32_Dyn& dyn = oat_file_->GetDynamic(i);
554 if (IsDynamicSectionPointer(dyn.d_tag, oat_file_->GetHeader().e_machine)) {
555 dyn.d_un.d_ptr += delta_;
556 }
557 }
558
559 t.NewTiming("Fixup Elf Symbols");
560 // Fixup dynsym
561 Elf32_Shdr* dynsym_sec = oat_file_->FindSectionByName(".dynsym");
562 CHECK(dynsym_sec != nullptr);
563 if (!PatchSymbols(dynsym_sec)) {
564 return false;
565 }
566
567 // Fixup symtab
568 Elf32_Shdr* symtab_sec = oat_file_->FindSectionByName(".symtab");
569 if (symtab_sec != nullptr) {
570 if (!PatchSymbols(symtab_sec)) {
571 return false;
572 }
573 }
574
Yevgeny Roubane3ea8382014-08-08 16:29:38 +0700575 t.NewTiming("Fixup Debug Sections");
576 if (!oat_file_->FixupDebugSections(delta_)) {
577 return false;
578 }
579
Alex Light53cb16b2014-06-12 11:26:29 -0700580 return true;
581}
582
583bool PatchOat::PatchSymbols(Elf32_Shdr* section) {
584 Elf32_Sym* syms = reinterpret_cast<Elf32_Sym*>(oat_file_->Begin() + section->sh_offset);
585 const Elf32_Sym* last_sym =
586 reinterpret_cast<Elf32_Sym*>(oat_file_->Begin() + section->sh_offset + section->sh_size);
587 CHECK_EQ(section->sh_size % sizeof(Elf32_Sym), 0u)
588 << "Symtab section size is not multiple of symbol size";
589 for (; syms < last_sym; syms++) {
590 uint8_t sttype = ELF32_ST_TYPE(syms->st_info);
591 Elf32_Word shndx = syms->st_shndx;
592 if (shndx != SHN_ABS && shndx != SHN_COMMON && shndx != SHN_UNDEF &&
593 (sttype == STT_FUNC || sttype == STT_OBJECT)) {
594 CHECK_NE(syms->st_value, 0u);
595 syms->st_value += delta_;
596 }
597 }
598 return true;
599}
600
601bool PatchOat::PatchTextSection() {
602 Elf32_Shdr* patches_sec = oat_file_->FindSectionByName(".oat_patches");
603 if (patches_sec == nullptr) {
Alex Lighta59dd802014-07-02 16:28:08 -0700604 LOG(ERROR) << ".oat_patches section not found. Aborting patch";
Alex Light53cb16b2014-06-12 11:26:29 -0700605 return false;
606 }
Alex Light4b0d2d92014-08-06 13:37:23 -0700607 if (patches_sec->sh_type != SHT_OAT_PATCH) {
608 LOG(ERROR) << "Unexpected type of .oat_patches";
609 return false;
610 }
611
612 switch (patches_sec->sh_entsize) {
613 case sizeof(uint32_t):
614 return PatchTextSection<uint32_t>(*patches_sec);
615 case sizeof(uint64_t):
616 return PatchTextSection<uint64_t>(*patches_sec);
617 default:
618 LOG(ERROR) << ".oat_patches Entsize of " << patches_sec->sh_entsize << "bits "
619 << "is not valid";
620 return false;
621 }
622}
623
624template <typename ptr_t>
625bool PatchOat::PatchTextSection(const Elf32_Shdr& patches_sec) {
626 DCHECK(CheckOatFile<ptr_t>(patches_sec)) << "Oat file invalid";
627 ptr_t* patches = reinterpret_cast<ptr_t*>(oat_file_->Begin() + patches_sec.sh_offset);
628 ptr_t* patches_end = patches + (patches_sec.sh_size / sizeof(ptr_t));
Alex Light53cb16b2014-06-12 11:26:29 -0700629 Elf32_Shdr* oat_text_sec = oat_file_->FindSectionByName(".text");
630 CHECK(oat_text_sec != nullptr);
631 byte* to_patch = oat_file_->Begin() + oat_text_sec->sh_offset;
632 uintptr_t to_patch_end = reinterpret_cast<uintptr_t>(to_patch) + oat_text_sec->sh_size;
633
634 for (; patches < patches_end; patches++) {
635 CHECK_LT(*patches, oat_text_sec->sh_size) << "Bad Patch";
636 uint32_t* patch_loc = reinterpret_cast<uint32_t*>(to_patch + *patches);
637 CHECK_LT(reinterpret_cast<uintptr_t>(patch_loc), to_patch_end);
638 *patch_loc += delta_;
639 }
Alex Light53cb16b2014-06-12 11:26:29 -0700640 return true;
641}
642
643static int orig_argc;
644static char** orig_argv;
645
646static std::string CommandLine() {
647 std::vector<std::string> command;
648 for (int i = 0; i < orig_argc; ++i) {
649 command.push_back(orig_argv[i]);
650 }
651 return Join(command, ' ');
652}
653
654static void UsageErrorV(const char* fmt, va_list ap) {
655 std::string error;
656 StringAppendV(&error, fmt, ap);
657 LOG(ERROR) << error;
658}
659
660static void UsageError(const char* fmt, ...) {
661 va_list ap;
662 va_start(ap, fmt);
663 UsageErrorV(fmt, ap);
664 va_end(ap);
665}
666
667static void Usage(const char *fmt, ...) {
668 va_list ap;
669 va_start(ap, fmt);
670 UsageErrorV(fmt, ap);
671 va_end(ap);
672
673 UsageError("Command: %s", CommandLine().c_str());
674 UsageError("Usage: patchoat [options]...");
675 UsageError("");
676 UsageError(" --instruction-set=<isa>: Specifies the instruction set the patched code is");
677 UsageError(" compiled for. Required if you use --input-oat-location");
678 UsageError("");
679 UsageError(" --input-oat-file=<file.oat>: Specifies the exact filename of the oat file to be");
680 UsageError(" patched.");
681 UsageError("");
682 UsageError(" --input-oat-fd=<file-descriptor>: Specifies the file-descriptor of the oat file");
683 UsageError(" to be patched.");
684 UsageError("");
685 UsageError(" --input-oat-location=<file.oat>: Specifies the 'location' to read the patched");
686 UsageError(" oat file from. If used one must also supply the --instruction-set");
687 UsageError("");
688 UsageError(" --input-image-location=<file.art>: Specifies the 'location' of the image file to");
689 UsageError(" be patched. If --instruction-set is not given it will use the instruction set");
690 UsageError(" extracted from the --input-oat-file.");
691 UsageError("");
692 UsageError(" --output-oat-file=<file.oat>: Specifies the exact file to write the patched oat");
693 UsageError(" file to.");
694 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700695 UsageError(" --output-oat-fd=<file-descriptor>: Specifies the file-descriptor to write the");
696 UsageError(" the patched oat file to.");
697 UsageError("");
698 UsageError(" --output-image-file=<file.art>: Specifies the exact file to write the patched");
699 UsageError(" image file to.");
700 UsageError("");
701 UsageError(" --output-image-fd=<file-descriptor>: Specifies the file-descriptor to write the");
702 UsageError(" the patched image file to.");
703 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700704 UsageError(" --orig-base-offset=<original-base-offset>: Specify the base offset the input file");
705 UsageError(" was compiled with. This is needed if one is specifying a --base-offset");
706 UsageError("");
707 UsageError(" --base-offset=<new-base-offset>: Specify the base offset we will repatch the");
708 UsageError(" given files to use. This requires that --orig-base-offset is also given.");
709 UsageError("");
710 UsageError(" --base-offset-delta=<delta>: Specify the amount to change the old base-offset by.");
711 UsageError(" This value may be negative.");
712 UsageError("");
713 UsageError(" --patched-image-file=<file.art>: Use the same patch delta as was used to patch");
714 UsageError(" the given image file.");
715 UsageError("");
716 UsageError(" --patched-image-location=<file.art>: Use the same patch delta as was used to");
717 UsageError(" patch the given image location. If used one must also specify the");
Alex Lighta59dd802014-07-02 16:28:08 -0700718 UsageError(" --instruction-set flag. It will search for this image in the same way that");
719 UsageError(" is done when loading one.");
Alex Light53cb16b2014-06-12 11:26:29 -0700720 UsageError("");
Alex Lightcf4bf382014-07-24 11:29:14 -0700721 UsageError(" --lock-output: Obtain a flock on output oat file before starting.");
722 UsageError("");
723 UsageError(" --no-lock-output: Do not attempt to obtain a flock on output oat file.");
724 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700725 UsageError(" --dump-timings: dump out patch timing information");
726 UsageError("");
727 UsageError(" --no-dump-timings: do not dump out patch timing information");
728 UsageError("");
729
730 exit(EXIT_FAILURE);
731}
732
Alex Lighteefbe392014-07-08 09:53:18 -0700733static bool ReadBaseDelta(const char* name, off_t* delta, std::string* error_msg) {
Alex Light53cb16b2014-06-12 11:26:29 -0700734 CHECK(name != nullptr);
735 CHECK(delta != nullptr);
736 std::unique_ptr<File> file;
737 if (OS::FileExists(name)) {
738 file.reset(OS::OpenFileForReading(name));
739 if (file.get() == nullptr) {
Alex Lighteefbe392014-07-08 09:53:18 -0700740 *error_msg = "Failed to open file %s for reading";
Alex Light53cb16b2014-06-12 11:26:29 -0700741 return false;
742 }
743 } else {
Alex Lighteefbe392014-07-08 09:53:18 -0700744 *error_msg = "File %s does not exist";
Alex Light53cb16b2014-06-12 11:26:29 -0700745 return false;
746 }
747 CHECK(file.get() != nullptr);
748 ImageHeader hdr;
749 if (sizeof(hdr) != file->Read(reinterpret_cast<char*>(&hdr), sizeof(hdr), 0)) {
Alex Lighteefbe392014-07-08 09:53:18 -0700750 *error_msg = "Failed to read file %s";
Alex Light53cb16b2014-06-12 11:26:29 -0700751 return false;
752 }
753 if (!hdr.IsValid()) {
Alex Lighteefbe392014-07-08 09:53:18 -0700754 *error_msg = "%s does not contain a valid image header.";
Alex Light53cb16b2014-06-12 11:26:29 -0700755 return false;
756 }
757 *delta = hdr.GetPatchDelta();
758 return true;
759}
760
761static File* CreateOrOpen(const char* name, bool* created) {
762 if (OS::FileExists(name)) {
763 *created = false;
764 return OS::OpenFileReadWrite(name);
765 } else {
766 *created = true;
Alex Lightcf4bf382014-07-24 11:29:14 -0700767 std::unique_ptr<File> f(OS::CreateEmptyFile(name));
768 if (f.get() != nullptr) {
769 if (fchmod(f->Fd(), 0644) != 0) {
770 PLOG(ERROR) << "Unable to make " << name << " world readable";
771 unlink(name);
772 return nullptr;
773 }
774 }
775 return f.release();
Alex Light53cb16b2014-06-12 11:26:29 -0700776 }
777}
778
Alex Lighteefbe392014-07-08 09:53:18 -0700779static int patchoat(int argc, char **argv) {
Alex Light53cb16b2014-06-12 11:26:29 -0700780 InitLogging(argv);
781 const bool debug = kIsDebugBuild;
782 orig_argc = argc;
783 orig_argv = argv;
784 TimingLogger timings("patcher", false, false);
785
786 InitLogging(argv);
787
788 // Skip over the command name.
789 argv++;
790 argc--;
791
792 if (argc == 0) {
793 Usage("No arguments specified");
794 }
795
796 timings.StartTiming("Patchoat");
797
798 // cmd line args
799 bool isa_set = false;
800 InstructionSet isa = kNone;
801 std::string input_oat_filename;
802 std::string input_oat_location;
803 int input_oat_fd = -1;
804 bool have_input_oat = false;
805 std::string input_image_location;
806 std::string output_oat_filename;
Alex Light53cb16b2014-06-12 11:26:29 -0700807 int output_oat_fd = -1;
808 bool have_output_oat = false;
809 std::string output_image_filename;
Alex Light53cb16b2014-06-12 11:26:29 -0700810 int output_image_fd = -1;
811 bool have_output_image = false;
812 uintptr_t base_offset = 0;
813 bool base_offset_set = false;
814 uintptr_t orig_base_offset = 0;
815 bool orig_base_offset_set = false;
816 off_t base_delta = 0;
817 bool base_delta_set = false;
818 std::string patched_image_filename;
819 std::string patched_image_location;
820 bool dump_timings = kIsDebugBuild;
Alex Lightcf4bf382014-07-24 11:29:14 -0700821 bool lock_output = true;
Alex Light53cb16b2014-06-12 11:26:29 -0700822
823 for (int i = 0; i < argc; i++) {
824 const StringPiece option(argv[i]);
825 const bool log_options = false;
826 if (log_options) {
827 LOG(INFO) << "patchoat: option[" << i << "]=" << argv[i];
828 }
Alex Light53cb16b2014-06-12 11:26:29 -0700829 if (option.starts_with("--instruction-set=")) {
830 isa_set = true;
831 const char* isa_str = option.substr(strlen("--instruction-set=")).data();
Andreas Gampe20c89302014-08-19 17:28:06 -0700832 isa = GetInstructionSetFromString(isa_str);
833 if (isa == kNone) {
834 Usage("Unknown or invalid instruction set %s", isa_str);
Alex Light53cb16b2014-06-12 11:26:29 -0700835 }
836 } else if (option.starts_with("--input-oat-location=")) {
837 if (have_input_oat) {
838 Usage("Only one of --input-oat-file, --input-oat-location and --input-oat-fd may be used.");
839 }
840 have_input_oat = true;
841 input_oat_location = option.substr(strlen("--input-oat-location=")).data();
842 } else if (option.starts_with("--input-oat-file=")) {
843 if (have_input_oat) {
844 Usage("Only one of --input-oat-file, --input-oat-location and --input-oat-fd may be used.");
845 }
846 have_input_oat = true;
847 input_oat_filename = option.substr(strlen("--input-oat-file=")).data();
848 } else if (option.starts_with("--input-oat-fd=")) {
849 if (have_input_oat) {
850 Usage("Only one of --input-oat-file, --input-oat-location and --input-oat-fd may be used.");
851 }
852 have_input_oat = true;
853 const char* oat_fd_str = option.substr(strlen("--input-oat-fd=")).data();
854 if (!ParseInt(oat_fd_str, &input_oat_fd)) {
855 Usage("Failed to parse --input-oat-fd argument '%s' as an integer", oat_fd_str);
856 }
857 if (input_oat_fd < 0) {
858 Usage("--input-oat-fd pass a negative value %d", input_oat_fd);
859 }
860 } else if (option.starts_with("--input-image-location=")) {
861 input_image_location = option.substr(strlen("--input-image-location=")).data();
Alex Light53cb16b2014-06-12 11:26:29 -0700862 } else if (option.starts_with("--output-oat-file=")) {
863 if (have_output_oat) {
Alex Lightcf4bf382014-07-24 11:29:14 -0700864 Usage("Only one of --output-oat-file, and --output-oat-fd may be used.");
Alex Light53cb16b2014-06-12 11:26:29 -0700865 }
866 have_output_oat = true;
867 output_oat_filename = option.substr(strlen("--output-oat-file=")).data();
868 } else if (option.starts_with("--output-oat-fd=")) {
869 if (have_output_oat) {
Alex Lightcf4bf382014-07-24 11:29:14 -0700870 Usage("Only one of --output-oat-file, --output-oat-fd may be used.");
Alex Light53cb16b2014-06-12 11:26:29 -0700871 }
872 have_output_oat = true;
873 const char* oat_fd_str = option.substr(strlen("--output-oat-fd=")).data();
874 if (!ParseInt(oat_fd_str, &output_oat_fd)) {
875 Usage("Failed to parse --output-oat-fd argument '%s' as an integer", oat_fd_str);
876 }
877 if (output_oat_fd < 0) {
878 Usage("--output-oat-fd pass a negative value %d", output_oat_fd);
879 }
Alex Light53cb16b2014-06-12 11:26:29 -0700880 } else if (option.starts_with("--output-image-file=")) {
881 if (have_output_image) {
Alex Lightcf4bf382014-07-24 11:29:14 -0700882 Usage("Only one of --output-image-file, and --output-image-fd may be used.");
Alex Light53cb16b2014-06-12 11:26:29 -0700883 }
884 have_output_image = true;
885 output_image_filename = option.substr(strlen("--output-image-file=")).data();
886 } else if (option.starts_with("--output-image-fd=")) {
887 if (have_output_image) {
Alex Lightcf4bf382014-07-24 11:29:14 -0700888 Usage("Only one of --output-image-file, and --output-image-fd may be used.");
Alex Light53cb16b2014-06-12 11:26:29 -0700889 }
890 have_output_image = true;
891 const char* image_fd_str = option.substr(strlen("--output-image-fd=")).data();
892 if (!ParseInt(image_fd_str, &output_image_fd)) {
893 Usage("Failed to parse --output-image-fd argument '%s' as an integer", image_fd_str);
894 }
895 if (output_image_fd < 0) {
896 Usage("--output-image-fd pass a negative value %d", output_image_fd);
897 }
898 } else if (option.starts_with("--orig-base-offset=")) {
899 const char* orig_base_offset_str = option.substr(strlen("--orig-base-offset=")).data();
900 orig_base_offset_set = true;
901 if (!ParseUint(orig_base_offset_str, &orig_base_offset)) {
902 Usage("Failed to parse --orig-base-offset argument '%s' as an uintptr_t",
903 orig_base_offset_str);
904 }
905 } else if (option.starts_with("--base-offset=")) {
906 const char* base_offset_str = option.substr(strlen("--base-offset=")).data();
907 base_offset_set = true;
908 if (!ParseUint(base_offset_str, &base_offset)) {
909 Usage("Failed to parse --base-offset argument '%s' as an uintptr_t", base_offset_str);
910 }
911 } else if (option.starts_with("--base-offset-delta=")) {
912 const char* base_delta_str = option.substr(strlen("--base-offset-delta=")).data();
913 base_delta_set = true;
914 if (!ParseInt(base_delta_str, &base_delta)) {
915 Usage("Failed to parse --base-offset-delta argument '%s' as an off_t", base_delta_str);
916 }
917 } else if (option.starts_with("--patched-image-location=")) {
918 patched_image_location = option.substr(strlen("--patched-image-location=")).data();
919 } else if (option.starts_with("--patched-image-file=")) {
920 patched_image_filename = option.substr(strlen("--patched-image-file=")).data();
Alex Lightcf4bf382014-07-24 11:29:14 -0700921 } else if (option == "--lock-output") {
922 lock_output = true;
923 } else if (option == "--no-lock-output") {
924 lock_output = false;
Alex Light53cb16b2014-06-12 11:26:29 -0700925 } else if (option == "--dump-timings") {
926 dump_timings = true;
927 } else if (option == "--no-dump-timings") {
928 dump_timings = false;
929 } else {
930 Usage("Unknown argument %s", option.data());
931 }
932 }
933
934 {
935 // Only 1 of these may be set.
936 uint32_t cnt = 0;
937 cnt += (base_delta_set) ? 1 : 0;
938 cnt += (base_offset_set && orig_base_offset_set) ? 1 : 0;
939 cnt += (!patched_image_filename.empty()) ? 1 : 0;
940 cnt += (!patched_image_location.empty()) ? 1 : 0;
941 if (cnt > 1) {
942 Usage("Only one of --base-offset/--orig-base-offset, --base-offset-delta, "
943 "--patched-image-filename or --patched-image-location may be used.");
944 } else if (cnt == 0) {
945 Usage("Must specify --base-offset-delta, --base-offset and --orig-base-offset, "
946 "--patched-image-location or --patched-image-file");
947 }
948 }
949
950 if (have_input_oat != have_output_oat) {
951 Usage("Either both input and output oat must be supplied or niether must be.");
952 }
953
954 if ((!input_image_location.empty()) != have_output_image) {
955 Usage("Either both input and output image must be supplied or niether must be.");
956 }
957
958 // We know we have both the input and output so rename for clarity.
959 bool have_image_files = have_output_image;
960 bool have_oat_files = have_output_oat;
961
962 if (!have_oat_files && !have_image_files) {
963 Usage("Must be patching either an oat or an image file or both.");
964 }
965
966 if (!have_oat_files && !isa_set) {
967 Usage("Must include ISA if patching an image file without an oat file.");
968 }
969
970 if (!input_oat_location.empty()) {
971 if (!isa_set) {
972 Usage("specifying a location requires specifying an instruction set");
973 }
Alex Lightcf4bf382014-07-24 11:29:14 -0700974 if (!LocationToFilename(input_oat_location, isa, &input_oat_filename)) {
975 Usage("Unable to find filename for input oat location %s", input_oat_location.c_str());
976 }
Alex Light53cb16b2014-06-12 11:26:29 -0700977 if (debug) {
978 LOG(INFO) << "Using input-oat-file " << input_oat_filename;
979 }
980 }
Alex Light53cb16b2014-06-12 11:26:29 -0700981 if (!patched_image_location.empty()) {
982 if (!isa_set) {
983 Usage("specifying a location requires specifying an instruction set");
984 }
Alex Lighta59dd802014-07-02 16:28:08 -0700985 std::string system_filename;
986 bool has_system = false;
987 std::string cache_filename;
988 bool has_cache = false;
989 bool has_android_data_unused = false;
Andreas Gampe3c13a792014-09-18 20:56:04 -0700990 bool is_global_cache = false;
Alex Lighta59dd802014-07-02 16:28:08 -0700991 if (!gc::space::ImageSpace::FindImageFilename(patched_image_location.c_str(), isa,
992 &system_filename, &has_system, &cache_filename,
Andreas Gampe3c13a792014-09-18 20:56:04 -0700993 &has_android_data_unused, &has_cache,
994 &is_global_cache)) {
Alex Lighta59dd802014-07-02 16:28:08 -0700995 Usage("Unable to determine image file for location %s", patched_image_location.c_str());
996 }
997 if (has_cache) {
998 patched_image_filename = cache_filename;
999 } else if (has_system) {
1000 LOG(WARNING) << "Only image file found was in /system for image location "
1001 << patched_image_location;
1002 patched_image_filename = system_filename;
1003 } else {
1004 Usage("Unable to determine image file for location %s", patched_image_location.c_str());
1005 }
Alex Light53cb16b2014-06-12 11:26:29 -07001006 if (debug) {
1007 LOG(INFO) << "Using patched-image-file " << patched_image_filename;
1008 }
1009 }
1010
1011 if (!base_delta_set) {
1012 if (orig_base_offset_set && base_offset_set) {
1013 base_delta_set = true;
1014 base_delta = base_offset - orig_base_offset;
1015 } else if (!patched_image_filename.empty()) {
1016 base_delta_set = true;
1017 std::string error_msg;
Alex Lighteefbe392014-07-08 09:53:18 -07001018 if (!ReadBaseDelta(patched_image_filename.c_str(), &base_delta, &error_msg)) {
Alex Light53cb16b2014-06-12 11:26:29 -07001019 Usage(error_msg.c_str(), patched_image_filename.c_str());
1020 }
1021 } else {
1022 if (base_offset_set) {
1023 Usage("Unable to determine original base offset.");
1024 } else {
1025 Usage("Must supply a desired new offset or delta.");
1026 }
1027 }
1028 }
1029
1030 if (!IsAligned<kPageSize>(base_delta)) {
1031 Usage("Base offset/delta must be alligned to a pagesize (0x%08x) boundary.", kPageSize);
1032 }
1033
1034 // Do we need to cleanup output files if we fail?
1035 bool new_image_out = false;
1036 bool new_oat_out = false;
1037
1038 std::unique_ptr<File> input_oat;
1039 std::unique_ptr<File> output_oat;
1040 std::unique_ptr<File> output_image;
1041
1042 if (have_image_files) {
1043 CHECK(!input_image_location.empty());
1044
1045 if (output_image_fd != -1) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001046 if (output_image_filename.empty()) {
1047 output_image_filename = "output-image-file";
1048 }
Alex Light53cb16b2014-06-12 11:26:29 -07001049 output_image.reset(new File(output_image_fd, output_image_filename));
1050 } else {
1051 CHECK(!output_image_filename.empty());
1052 output_image.reset(CreateOrOpen(output_image_filename.c_str(), &new_image_out));
1053 }
1054 } else {
1055 CHECK(output_image_filename.empty() && output_image_fd == -1 && input_image_location.empty());
1056 }
1057
1058 if (have_oat_files) {
1059 if (input_oat_fd != -1) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001060 if (input_oat_filename.empty()) {
1061 input_oat_filename = "input-oat-file";
1062 }
Alex Light53cb16b2014-06-12 11:26:29 -07001063 input_oat.reset(new File(input_oat_fd, input_oat_filename));
1064 } else {
1065 CHECK(!input_oat_filename.empty());
1066 input_oat.reset(OS::OpenFileForReading(input_oat_filename.c_str()));
Andreas Gampe1c83cbc2014-07-22 18:52:29 -07001067 if (input_oat.get() == nullptr) {
1068 LOG(ERROR) << "Could not open input oat file: " << strerror(errno);
1069 }
Alex Light53cb16b2014-06-12 11:26:29 -07001070 }
1071
1072 if (output_oat_fd != -1) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001073 if (output_oat_filename.empty()) {
1074 output_oat_filename = "output-oat-file";
Alex Lighta59dd802014-07-02 16:28:08 -07001075 }
Alex Lightcf4bf382014-07-24 11:29:14 -07001076 output_oat.reset(new File(output_oat_fd, output_oat_filename));
Alex Light53cb16b2014-06-12 11:26:29 -07001077 } else {
1078 CHECK(!output_oat_filename.empty());
1079 output_oat.reset(CreateOrOpen(output_oat_filename.c_str(), &new_oat_out));
1080 }
1081 }
1082
1083 auto cleanup = [&output_image_filename, &output_oat_filename,
1084 &new_oat_out, &new_image_out, &timings, &dump_timings](bool success) {
1085 timings.EndTiming();
1086 if (!success) {
1087 if (new_oat_out) {
1088 CHECK(!output_oat_filename.empty());
1089 unlink(output_oat_filename.c_str());
1090 }
1091 if (new_image_out) {
1092 CHECK(!output_image_filename.empty());
1093 unlink(output_image_filename.c_str());
1094 }
1095 }
1096 if (dump_timings) {
1097 LOG(INFO) << Dumpable<TimingLogger>(timings);
1098 }
1099 };
1100
Alex Lightcf4bf382014-07-24 11:29:14 -07001101 if ((have_oat_files && (input_oat.get() == nullptr || output_oat.get() == nullptr)) ||
1102 (have_image_files && output_image.get() == nullptr)) {
1103 cleanup(false);
1104 return EXIT_FAILURE;
1105 }
1106
1107 ScopedFlock output_oat_lock;
1108 if (lock_output) {
1109 std::string error_msg;
1110 if (have_oat_files && !output_oat_lock.Init(output_oat.get(), &error_msg)) {
1111 LOG(ERROR) << "Unable to lock output oat " << output_image->GetPath() << ": " << error_msg;
1112 cleanup(false);
1113 return EXIT_FAILURE;
1114 }
1115 }
1116
Alex Light53cb16b2014-06-12 11:26:29 -07001117 if (debug) {
Alex Lighta59dd802014-07-02 16:28:08 -07001118 LOG(INFO) << "moving offset by " << base_delta
1119 << " (0x" << std::hex << base_delta << ") bytes or "
1120 << std::dec << (base_delta/kPageSize) << " pages.";
Alex Light53cb16b2014-06-12 11:26:29 -07001121 }
1122
1123 bool ret;
1124 if (have_image_files && have_oat_files) {
1125 TimingLogger::ScopedTiming pt("patch image and oat", &timings);
1126 ret = PatchOat::Patch(input_oat.get(), input_image_location, base_delta,
Alex Lighteefbe392014-07-08 09:53:18 -07001127 output_oat.get(), output_image.get(), isa, &timings);
Alex Light53cb16b2014-06-12 11:26:29 -07001128 } else if (have_oat_files) {
1129 TimingLogger::ScopedTiming pt("patch oat", &timings);
Alex Lighteefbe392014-07-08 09:53:18 -07001130 ret = PatchOat::Patch(input_oat.get(), base_delta, output_oat.get(), &timings);
Alex Light53cb16b2014-06-12 11:26:29 -07001131 } else {
1132 TimingLogger::ScopedTiming pt("patch image", &timings);
1133 CHECK(have_image_files);
Alex Lighteefbe392014-07-08 09:53:18 -07001134 ret = PatchOat::Patch(input_image_location, base_delta, output_image.get(), isa, &timings);
Alex Light53cb16b2014-06-12 11:26:29 -07001135 }
1136 cleanup(ret);
Alex Light53cb16b2014-06-12 11:26:29 -07001137 return (ret) ? EXIT_SUCCESS : EXIT_FAILURE;
1138}
1139
1140} // namespace art
1141
1142int main(int argc, char **argv) {
1143 return art::patchoat(argc, argv);
1144}