blob: b9637d0cb6b5561e91c240b56ad5e14809d3190b [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
Igor Murashkin90ca5c02014-10-22 11:37:02 -070074 // system_image_filename = /system/framework/<image_isa>/boot.art
Alex Lightcf4bf382014-07-24 11:29:14 -070075 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 Gampe33c36d42014-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 Gampe33c36d42014-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 }
Igor Murashkin90ca5c02014-10-22 11:37:02 -0700133
Alex Light53cb16b2014-06-12 11:26:29 -0700134 int64_t image_len = input_image->GetLength();
135 if (image_len < 0) {
136 LOG(ERROR) << "Error while getting image length";
137 return false;
138 }
139 ImageHeader image_header;
140 if (sizeof(image_header) != input_image->Read(reinterpret_cast<char*>(&image_header),
141 sizeof(image_header), 0)) {
142 LOG(ERROR) << "Unable to read image header from image file " << input_image->GetPath();
143 return false;
144 }
145
Igor Murashkin90ca5c02014-10-22 11:37:02 -0700146 /*bool is_image_pic = */IsImagePic(image_header, input_image->GetPath());
147 // Nothing special to do right now since the image always needs to get patched.
148 // Perhaps in some far-off future we may have images with relative addresses that are true-PIC.
149
Alex Light53cb16b2014-06-12 11:26:29 -0700150 // Set up the runtime
Ian Rogerse63db272014-07-15 15:36:11 -0700151 RuntimeOptions options;
Alex Light53cb16b2014-06-12 11:26:29 -0700152 NoopCompilerCallbacks callbacks;
153 options.push_back(std::make_pair("compilercallbacks", &callbacks));
154 std::string img = "-Ximage:" + image_location;
155 options.push_back(std::make_pair(img.c_str(), nullptr));
156 options.push_back(std::make_pair("imageinstructionset", reinterpret_cast<const void*>(isa_name)));
157 if (!Runtime::Create(options, false)) {
158 LOG(ERROR) << "Unable to initialize runtime";
159 return false;
160 }
161 // Runtime::Create acquired the mutator_lock_ that is normally given away when we Runtime::Start,
162 // give it away now and then switch to a more manageable ScopedObjectAccess.
163 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
164 ScopedObjectAccess soa(Thread::Current());
165
166 t.NewTiming("Image and oat Patching setup");
167 // Create the map where we will write the image patches to.
Alex Lighteefbe392014-07-08 09:53:18 -0700168 std::string error_msg;
Alex Light53cb16b2014-06-12 11:26:29 -0700169 std::unique_ptr<MemMap> image(MemMap::MapFile(image_len, PROT_READ | PROT_WRITE, MAP_PRIVATE,
170 input_image->Fd(), 0,
171 input_image->GetPath().c_str(),
172 &error_msg));
173 if (image.get() == nullptr) {
174 LOG(ERROR) << "unable to map image file " << input_image->GetPath() << " : " << error_msg;
175 return false;
176 }
177 gc::space::ImageSpace* ispc = Runtime::Current()->GetHeap()->GetImageSpace();
178
179 PatchOat p(image.release(), ispc->GetLiveBitmap(), ispc->GetMemMap(),
180 delta, timings);
181 t.NewTiming("Patching files");
182 if (!p.PatchImage()) {
Alex Lighta59dd802014-07-02 16:28:08 -0700183 LOG(ERROR) << "Failed to patch image file " << input_image->GetPath();
Alex Light53cb16b2014-06-12 11:26:29 -0700184 return false;
185 }
186
187 t.NewTiming("Writing files");
188 if (!p.WriteImage(output_image)) {
189 return false;
190 }
191 return true;
192}
193
Igor Murashkin90ca5c02014-10-22 11:37:02 -0700194bool PatchOat::Patch(File* input_oat, const std::string& image_location, off_t delta,
Alex Light53cb16b2014-06-12 11:26:29 -0700195 File* output_oat, File* output_image, InstructionSet isa,
Igor Murashkin90ca5c02014-10-22 11:37:02 -0700196 TimingLogger* timings,
197 bool output_oat_opened_from_fd,
198 bool new_oat_out) {
Alex Light53cb16b2014-06-12 11:26:29 -0700199 CHECK(Runtime::Current() == nullptr);
200 CHECK(output_image != nullptr);
201 CHECK_GE(output_image->Fd(), 0);
202 CHECK(input_oat != nullptr);
203 CHECK(output_oat != nullptr);
204 CHECK_GE(input_oat->Fd(), 0);
205 CHECK_GE(output_oat->Fd(), 0);
206 CHECK(!image_location.empty()) << "image file must have a filename.";
207
Alex Lighteefbe392014-07-08 09:53:18 -0700208 TimingLogger::ScopedTiming t("Runtime Setup", timings);
Alex Light53cb16b2014-06-12 11:26:29 -0700209
210 if (isa == kNone) {
211 Elf32_Ehdr elf_hdr;
212 if (sizeof(elf_hdr) != input_oat->Read(reinterpret_cast<char*>(&elf_hdr), sizeof(elf_hdr), 0)) {
213 LOG(ERROR) << "unable to read elf header";
214 return false;
215 }
216 isa = ElfISAToInstructionSet(elf_hdr.e_machine);
217 }
218 const char* isa_name = GetInstructionSetString(isa);
Alex Lightcf4bf382014-07-24 11:29:14 -0700219 std::string image_filename;
220 if (!LocationToFilename(image_location, isa, &image_filename)) {
221 LOG(ERROR) << "Unable to find image at location " << image_location;
222 return false;
223 }
Alex Light53cb16b2014-06-12 11:26:29 -0700224 std::unique_ptr<File> input_image(OS::OpenFileForReading(image_filename.c_str()));
225 if (input_image.get() == nullptr) {
Alex Lightcf4bf382014-07-24 11:29:14 -0700226 LOG(ERROR) << "unable to open input image file at " << image_filename
227 << " for location " << image_location;
Alex Light53cb16b2014-06-12 11:26:29 -0700228 return false;
229 }
230 int64_t image_len = input_image->GetLength();
231 if (image_len < 0) {
232 LOG(ERROR) << "Error while getting image length";
233 return false;
234 }
235 ImageHeader image_header;
236 if (sizeof(image_header) != input_image->Read(reinterpret_cast<char*>(&image_header),
237 sizeof(image_header), 0)) {
238 LOG(ERROR) << "Unable to read image header from image file " << input_image->GetPath();
239 }
240
Igor Murashkin90ca5c02014-10-22 11:37:02 -0700241 /*bool is_image_pic = */IsImagePic(image_header, input_image->GetPath());
242 // Nothing special to do right now since the image always needs to get patched.
243 // Perhaps in some far-off future we may have images with relative addresses that are true-PIC.
244
Alex Light53cb16b2014-06-12 11:26:29 -0700245 // Set up the runtime
Ian Rogerse63db272014-07-15 15:36:11 -0700246 RuntimeOptions options;
Alex Light53cb16b2014-06-12 11:26:29 -0700247 NoopCompilerCallbacks callbacks;
248 options.push_back(std::make_pair("compilercallbacks", &callbacks));
249 std::string img = "-Ximage:" + image_location;
250 options.push_back(std::make_pair(img.c_str(), nullptr));
251 options.push_back(std::make_pair("imageinstructionset", reinterpret_cast<const void*>(isa_name)));
252 if (!Runtime::Create(options, false)) {
253 LOG(ERROR) << "Unable to initialize runtime";
254 return false;
255 }
256 // Runtime::Create acquired the mutator_lock_ that is normally given away when we Runtime::Start,
257 // give it away now and then switch to a more manageable ScopedObjectAccess.
258 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
259 ScopedObjectAccess soa(Thread::Current());
260
261 t.NewTiming("Image and oat Patching setup");
262 // Create the map where we will write the image patches to.
Alex Lighteefbe392014-07-08 09:53:18 -0700263 std::string error_msg;
Alex Light53cb16b2014-06-12 11:26:29 -0700264 std::unique_ptr<MemMap> image(MemMap::MapFile(image_len, PROT_READ | PROT_WRITE, MAP_PRIVATE,
265 input_image->Fd(), 0,
266 input_image->GetPath().c_str(),
267 &error_msg));
268 if (image.get() == nullptr) {
269 LOG(ERROR) << "unable to map image file " << input_image->GetPath() << " : " << error_msg;
270 return false;
271 }
272 gc::space::ImageSpace* ispc = Runtime::Current()->GetHeap()->GetImageSpace();
273
Igor Murashkin90ca5c02014-10-22 11:37:02 -0700274 std::unique_ptr<ElfFile> elf(ElfFile::Open(input_oat,
Alex Light53cb16b2014-06-12 11:26:29 -0700275 PROT_READ | PROT_WRITE, MAP_PRIVATE, &error_msg));
276 if (elf.get() == nullptr) {
277 LOG(ERROR) << "unable to open oat file " << input_oat->GetPath() << " : " << error_msg;
278 return false;
279 }
280
Igor Murashkin90ca5c02014-10-22 11:37:02 -0700281 bool skip_patching_oat = false;
282 MaybePic is_oat_pic = IsOatPic(elf.get());
283 if (is_oat_pic >= ERROR_FIRST) {
284 // Error logged by IsOatPic
285 return false;
286 } else if (is_oat_pic == PIC) {
287 // Do not need to do ELF-file patching. Create a symlink and skip the ELF patching.
288 if (!ReplaceOatFileWithSymlink(input_oat->GetPath(),
289 output_oat->GetPath(),
290 output_oat_opened_from_fd,
291 new_oat_out)) {
292 // Errors already logged by above call.
293 return false;
294 }
295 // Don't patch the OAT, since we just symlinked it. Image still needs patching.
296 skip_patching_oat = true;
297 } else {
298 CHECK(is_oat_pic == NOT_PIC);
299 }
300
Alex Light53cb16b2014-06-12 11:26:29 -0700301 PatchOat p(elf.release(), image.release(), ispc->GetLiveBitmap(), ispc->GetMemMap(),
302 delta, timings);
303 t.NewTiming("Patching files");
Igor Murashkin90ca5c02014-10-22 11:37:02 -0700304 if (!skip_patching_oat && !p.PatchElf()) {
Alex Lighta59dd802014-07-02 16:28:08 -0700305 LOG(ERROR) << "Failed to patch oat file " << input_oat->GetPath();
Alex Light53cb16b2014-06-12 11:26:29 -0700306 return false;
307 }
308 if (!p.PatchImage()) {
Alex Lighta59dd802014-07-02 16:28:08 -0700309 LOG(ERROR) << "Failed to patch image file " << input_image->GetPath();
Alex Light53cb16b2014-06-12 11:26:29 -0700310 return false;
311 }
312
313 t.NewTiming("Writing files");
Igor Murashkin90ca5c02014-10-22 11:37:02 -0700314 if (!skip_patching_oat && !p.WriteElf(output_oat)) {
315 LOG(ERROR) << "Failed to write oat file " << input_oat->GetPath();
Alex Light53cb16b2014-06-12 11:26:29 -0700316 return false;
317 }
318 if (!p.WriteImage(output_image)) {
Igor Murashkin90ca5c02014-10-22 11:37:02 -0700319 LOG(ERROR) << "Failed to write image file " << input_image->GetPath();
Alex Light53cb16b2014-06-12 11:26:29 -0700320 return false;
321 }
322 return true;
323}
324
325bool PatchOat::WriteElf(File* out) {
Alex Lighteefbe392014-07-08 09:53:18 -0700326 TimingLogger::ScopedTiming t("Writing Elf File", timings_);
Alex Lighta59dd802014-07-02 16:28:08 -0700327
Alex Light53cb16b2014-06-12 11:26:29 -0700328 CHECK(oat_file_.get() != nullptr);
329 CHECK(out != nullptr);
330 size_t expect = oat_file_->Size();
331 if (out->WriteFully(reinterpret_cast<char*>(oat_file_->Begin()), expect) &&
332 out->SetLength(expect) == 0) {
333 return true;
334 } else {
335 LOG(ERROR) << "Writing to oat file " << out->GetPath() << " failed.";
336 return false;
337 }
338}
339
340bool PatchOat::WriteImage(File* out) {
Alex Lighteefbe392014-07-08 09:53:18 -0700341 TimingLogger::ScopedTiming t("Writing image File", timings_);
Alex Lighta59dd802014-07-02 16:28:08 -0700342 std::string error_msg;
343
Alex Lightcf4bf382014-07-24 11:29:14 -0700344 ScopedFlock img_flock;
345 img_flock.Init(out, &error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -0700346
Alex Light53cb16b2014-06-12 11:26:29 -0700347 CHECK(image_ != nullptr);
348 CHECK(out != nullptr);
349 size_t expect = image_->Size();
350 if (out->WriteFully(reinterpret_cast<char*>(image_->Begin()), expect) &&
351 out->SetLength(expect) == 0) {
352 return true;
353 } else {
354 LOG(ERROR) << "Writing to image file " << out->GetPath() << " failed.";
355 return false;
356 }
357}
358
Igor Murashkin90ca5c02014-10-22 11:37:02 -0700359bool PatchOat::IsImagePic(const ImageHeader& image_header, const std::string& image_path) {
360 if (!image_header.CompilePic()) {
361 if (kIsDebugBuild) {
362 LOG(INFO) << "image at location " << image_path << " was *not* compiled pic";
363 }
364 return false;
365 }
366
367 if (kIsDebugBuild) {
368 LOG(INFO) << "image at location " << image_path << " was compiled PIC";
369 }
370
371 return true;
372}
373
374PatchOat::MaybePic PatchOat::IsOatPic(const ElfFile* oat_in) {
375 if (oat_in == nullptr) {
376 LOG(ERROR) << "No ELF input oat fie available";
377 return ERROR_OAT_FILE;
378 }
379
380 const std::string& file_path = oat_in->GetFile().GetPath();
381
382 const OatHeader* oat_header = GetOatHeader(oat_in);
383 if (oat_header == nullptr) {
384 LOG(ERROR) << "Failed to find oat header in oat file " << file_path;
385 return ERROR_OAT_FILE;
386 }
387
388 if (!oat_header->IsValid()) {
389 LOG(ERROR) << "Elf file " << file_path << " has an invalid oat header";
390 return ERROR_OAT_FILE;
391 }
392
393 bool is_pic = oat_header->IsPic();
394 if (kIsDebugBuild) {
395 LOG(INFO) << "Oat file at " << file_path << " is " << (is_pic ? "PIC" : "not pic");
396 }
397
398 return is_pic ? PIC : NOT_PIC;
399}
400
401bool PatchOat::ReplaceOatFileWithSymlink(const std::string& input_oat_filename,
402 const std::string& output_oat_filename,
403 bool output_oat_opened_from_fd,
404 bool new_oat_out) {
405 // Need a file when we are PIC, since we symlink over it. Refusing to symlink into FD.
406 if (output_oat_opened_from_fd) {
407 // TODO: installd uses --output-oat-fd. Should we change class linking logic for PIC?
408 LOG(ERROR) << "No output oat filename specified, needs filename for when we are PIC";
409 return false;
410 }
411
412 // Image was PIC. Create symlink where the oat is supposed to go.
413 if (!new_oat_out) {
414 LOG(ERROR) << "Oat file " << output_oat_filename << " already exists, refusing to overwrite";
415 return false;
416 }
417
418 // Delete the original file, since we won't need it.
419 TEMP_FAILURE_RETRY(unlink(output_oat_filename.c_str()));
420
421 // Create a symlink from the old oat to the new oat
422 if (symlink(input_oat_filename.c_str(), output_oat_filename.c_str()) < 0) {
423 int err = errno;
424 LOG(ERROR) << "Failed to create symlink at " << output_oat_filename
425 << " error(" << err << "): " << strerror(err);
426 return false;
427 }
428
429 if (kIsDebugBuild) {
430 LOG(INFO) << "Created symlink " << output_oat_filename << " -> " << input_oat_filename;
431 }
432
433 return true;
434}
435
Alex Light53cb16b2014-06-12 11:26:29 -0700436bool PatchOat::PatchImage() {
437 ImageHeader* image_header = reinterpret_cast<ImageHeader*>(image_->Begin());
438 CHECK_GT(image_->Size(), sizeof(ImageHeader));
439 // These are the roots from the original file.
440 mirror::Object* img_roots = image_header->GetImageRoots();
441 image_header->RelocateImage(delta_);
442
443 VisitObject(img_roots);
444 if (!image_header->IsValid()) {
445 LOG(ERROR) << "reloction renders image header invalid";
446 return false;
447 }
448
449 {
Alex Lighteefbe392014-07-08 09:53:18 -0700450 TimingLogger::ScopedTiming t("Walk Bitmap", timings_);
Alex Light53cb16b2014-06-12 11:26:29 -0700451 // Walk the bitmap.
452 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
453 bitmap_->Walk(PatchOat::BitmapCallback, this);
454 }
455 return true;
456}
457
458bool PatchOat::InHeap(mirror::Object* o) {
459 uintptr_t begin = reinterpret_cast<uintptr_t>(heap_->Begin());
460 uintptr_t end = reinterpret_cast<uintptr_t>(heap_->End());
461 uintptr_t obj = reinterpret_cast<uintptr_t>(o);
462 return o == nullptr || (begin <= obj && obj < end);
463}
464
465void PatchOat::PatchVisitor::operator() (mirror::Object* obj, MemberOffset off,
466 bool is_static_unused) const {
467 mirror::Object* referent = obj->GetFieldObject<mirror::Object, kVerifyNone>(off);
468 DCHECK(patcher_->InHeap(referent)) << "Referent is not in the heap.";
469 mirror::Object* moved_object = patcher_->RelocatedAddressOf(referent);
470 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(off, moved_object);
471}
472
473void PatchOat::PatchVisitor::operator() (mirror::Class* cls, mirror::Reference* ref) const {
474 MemberOffset off = mirror::Reference::ReferentOffset();
475 mirror::Object* referent = ref->GetReferent();
476 DCHECK(patcher_->InHeap(referent)) << "Referent is not in the heap.";
477 mirror::Object* moved_object = patcher_->RelocatedAddressOf(referent);
478 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(off, moved_object);
479}
480
481mirror::Object* PatchOat::RelocatedCopyOf(mirror::Object* obj) {
482 if (obj == nullptr) {
483 return nullptr;
484 }
485 DCHECK_GT(reinterpret_cast<uintptr_t>(obj), reinterpret_cast<uintptr_t>(heap_->Begin()));
486 DCHECK_LT(reinterpret_cast<uintptr_t>(obj), reinterpret_cast<uintptr_t>(heap_->End()));
487 uintptr_t heap_off =
488 reinterpret_cast<uintptr_t>(obj) - reinterpret_cast<uintptr_t>(heap_->Begin());
489 DCHECK_LT(heap_off, image_->Size());
490 return reinterpret_cast<mirror::Object*>(image_->Begin() + heap_off);
491}
492
493mirror::Object* PatchOat::RelocatedAddressOf(mirror::Object* obj) {
494 if (obj == nullptr) {
495 return nullptr;
496 } else {
497 return reinterpret_cast<mirror::Object*>(reinterpret_cast<byte*>(obj) + delta_);
498 }
499}
500
Igor Murashkin90ca5c02014-10-22 11:37:02 -0700501const OatHeader* PatchOat::GetOatHeader(const ElfFile* elf_file) {
502 auto rodata_sec = elf_file->FindSectionByName(".rodata");
503 if (rodata_sec == nullptr) {
504 return nullptr;
505 }
506
507 OatHeader* oat_header = reinterpret_cast<OatHeader*>(elf_file->Begin() + rodata_sec->sh_offset);
508 return oat_header;
509}
510
Alex Light53cb16b2014-06-12 11:26:29 -0700511// Called by BitmapCallback
512void PatchOat::VisitObject(mirror::Object* object) {
513 mirror::Object* copy = RelocatedCopyOf(object);
514 CHECK(copy != nullptr);
515 if (kUseBakerOrBrooksReadBarrier) {
516 object->AssertReadBarrierPointer();
517 if (kUseBrooksReadBarrier) {
518 mirror::Object* moved_to = RelocatedAddressOf(object);
519 copy->SetReadBarrierPointer(moved_to);
520 DCHECK_EQ(copy->GetReadBarrierPointer(), moved_to);
521 }
522 }
523 PatchOat::PatchVisitor visitor(this, copy);
524 object->VisitReferences<true, kVerifyNone>(visitor, visitor);
525 if (object->IsArtMethod<kVerifyNone>()) {
526 FixupMethod(static_cast<mirror::ArtMethod*>(object),
527 static_cast<mirror::ArtMethod*>(copy));
528 }
529}
530
531void PatchOat::FixupMethod(mirror::ArtMethod* object, mirror::ArtMethod* copy) {
532 // Just update the entry points if it looks like we should.
Alex Lighteefbe392014-07-08 09:53:18 -0700533 // TODO: sanity check all the pointers' values
Ian Rogers63bc11e2014-09-18 08:56:45 -0700534#if defined(ART_USE_PORTABLE_COMPILER)
Alex Light53cb16b2014-06-12 11:26:29 -0700535 uintptr_t portable = reinterpret_cast<uintptr_t>(
536 object->GetEntryPointFromPortableCompiledCode<kVerifyNone>());
537 if (portable != 0) {
538 copy->SetEntryPointFromPortableCompiledCode(reinterpret_cast<void*>(portable + delta_));
539 }
Ian Rogers63bc11e2014-09-18 08:56:45 -0700540#endif
Alex Light53cb16b2014-06-12 11:26:29 -0700541 uintptr_t quick= reinterpret_cast<uintptr_t>(
542 object->GetEntryPointFromQuickCompiledCode<kVerifyNone>());
543 if (quick != 0) {
544 copy->SetEntryPointFromQuickCompiledCode(reinterpret_cast<void*>(quick + delta_));
545 }
546 uintptr_t interpreter = reinterpret_cast<uintptr_t>(
547 object->GetEntryPointFromInterpreter<kVerifyNone>());
548 if (interpreter != 0) {
549 copy->SetEntryPointFromInterpreter(
550 reinterpret_cast<mirror::EntryPointFromInterpreter*>(interpreter + delta_));
551 }
552
553 uintptr_t native_method = reinterpret_cast<uintptr_t>(object->GetNativeMethod());
554 if (native_method != 0) {
555 copy->SetNativeMethod(reinterpret_cast<void*>(native_method + delta_));
556 }
557
558 uintptr_t native_gc_map = reinterpret_cast<uintptr_t>(object->GetNativeGcMap());
559 if (native_gc_map != 0) {
560 copy->SetNativeGcMap(reinterpret_cast<uint8_t*>(native_gc_map + delta_));
561 }
562}
563
Igor Murashkin90ca5c02014-10-22 11:37:02 -0700564bool PatchOat::Patch(File* input_oat, off_t delta, File* output_oat, TimingLogger* timings,
565 bool output_oat_opened_from_fd, bool new_oat_out) {
Alex Light53cb16b2014-06-12 11:26:29 -0700566 CHECK(input_oat != nullptr);
567 CHECK(output_oat != nullptr);
568 CHECK_GE(input_oat->Fd(), 0);
569 CHECK_GE(output_oat->Fd(), 0);
Alex Lighteefbe392014-07-08 09:53:18 -0700570 TimingLogger::ScopedTiming t("Setup Oat File Patching", timings);
Alex Light53cb16b2014-06-12 11:26:29 -0700571
572 std::string error_msg;
Igor Murashkin90ca5c02014-10-22 11:37:02 -0700573 std::unique_ptr<ElfFile> elf(ElfFile::Open(input_oat,
Alex Light53cb16b2014-06-12 11:26:29 -0700574 PROT_READ | PROT_WRITE, MAP_PRIVATE, &error_msg));
575 if (elf.get() == nullptr) {
576 LOG(ERROR) << "unable to open oat file " << input_oat->GetPath() << " : " << error_msg;
577 return false;
578 }
579
Igor Murashkin90ca5c02014-10-22 11:37:02 -0700580 MaybePic is_oat_pic = IsOatPic(elf.get());
581 if (is_oat_pic >= ERROR_FIRST) {
582 // Error logged by IsOatPic
583 return false;
584 } else if (is_oat_pic == PIC) {
585 // Do not need to do ELF-file patching. Create a symlink and skip the rest.
586 // Any errors will be logged by the function call.
587 return ReplaceOatFileWithSymlink(input_oat->GetPath(),
588 output_oat->GetPath(),
589 output_oat_opened_from_fd,
590 new_oat_out);
591 } else {
592 CHECK(is_oat_pic == NOT_PIC);
593 }
594
Alex Light53cb16b2014-06-12 11:26:29 -0700595 PatchOat p(elf.release(), delta, timings);
596 t.NewTiming("Patch Oat file");
597 if (!p.PatchElf()) {
598 return false;
599 }
600
601 t.NewTiming("Writing oat file");
602 if (!p.WriteElf(output_oat)) {
603 return false;
604 }
605 return true;
606}
607
608bool PatchOat::CheckOatFile() {
609 Elf32_Shdr* patches_sec = oat_file_->FindSectionByName(".oat_patches");
610 if (patches_sec == nullptr) {
611 return false;
612 }
613 if (patches_sec->sh_type != SHT_OAT_PATCH) {
614 return false;
615 }
616 uintptr_t* patches = reinterpret_cast<uintptr_t*>(oat_file_->Begin() + patches_sec->sh_offset);
617 uintptr_t* patches_end = patches + (patches_sec->sh_size/sizeof(uintptr_t));
618 Elf32_Shdr* oat_data_sec = oat_file_->FindSectionByName(".rodata");
619 Elf32_Shdr* oat_text_sec = oat_file_->FindSectionByName(".text");
620 if (oat_data_sec == nullptr) {
621 return false;
622 }
623 if (oat_text_sec == nullptr) {
624 return false;
625 }
626 if (oat_text_sec->sh_offset <= oat_data_sec->sh_offset) {
627 return false;
628 }
629
630 for (; patches < patches_end; patches++) {
631 if (oat_text_sec->sh_size <= *patches) {
632 return false;
633 }
634 }
635
636 return true;
637}
638
Alex Lighta59dd802014-07-02 16:28:08 -0700639bool PatchOat::PatchOatHeader() {
640 Elf32_Shdr *rodata_sec = oat_file_->FindSectionByName(".rodata");
641 if (rodata_sec == nullptr) {
642 return false;
643 }
644 OatHeader* oat_header = reinterpret_cast<OatHeader*>(oat_file_->Begin() + rodata_sec->sh_offset);
645 if (!oat_header->IsValid()) {
646 LOG(ERROR) << "Elf file " << oat_file_->GetFile().GetPath() << " has an invalid oat header";
647 return false;
648 }
649 oat_header->RelocateOat(delta_);
650 return true;
651}
652
Alex Light53cb16b2014-06-12 11:26:29 -0700653bool PatchOat::PatchElf() {
Alex Lighta59dd802014-07-02 16:28:08 -0700654 TimingLogger::ScopedTiming t("Fixup Elf Text Section", timings_);
655 if (!PatchTextSection()) {
656 return false;
657 }
658
659 if (!PatchOatHeader()) {
660 return false;
661 }
662
663 bool need_fixup = false;
664 t.NewTiming("Fixup Elf Headers");
Alex Light53cb16b2014-06-12 11:26:29 -0700665 // Fixup Phdr's
666 for (unsigned int i = 0; i < oat_file_->GetProgramHeaderNum(); i++) {
Andreas Gampeafa6b8e2014-09-12 18:38:24 -0700667 Elf32_Phdr* hdr = oat_file_->GetProgramHeader(i);
668 CHECK(hdr != nullptr);
669 if (hdr->p_vaddr != 0 && hdr->p_vaddr != hdr->p_offset) {
Alex Lighta59dd802014-07-02 16:28:08 -0700670 need_fixup = true;
Andreas Gampeafa6b8e2014-09-12 18:38:24 -0700671 hdr->p_vaddr += delta_;
Alex Light53cb16b2014-06-12 11:26:29 -0700672 }
Andreas Gampeafa6b8e2014-09-12 18:38:24 -0700673 if (hdr->p_paddr != 0 && hdr->p_paddr != hdr->p_offset) {
Alex Lighta59dd802014-07-02 16:28:08 -0700674 need_fixup = true;
Andreas Gampeafa6b8e2014-09-12 18:38:24 -0700675 hdr->p_paddr += delta_;
Alex Light53cb16b2014-06-12 11:26:29 -0700676 }
677 }
Alex Lighta59dd802014-07-02 16:28:08 -0700678 if (!need_fixup) {
679 // This was never passed through ElfFixup so all headers/symbols just have their offset as
680 // their addr. Therefore we do not need to update these parts.
681 return true;
682 }
683 t.NewTiming("Fixup Section Headers");
Alex Light53cb16b2014-06-12 11:26:29 -0700684 for (unsigned int i = 0; i < oat_file_->GetSectionHeaderNum(); i++) {
Andreas Gampeafa6b8e2014-09-12 18:38:24 -0700685 Elf32_Shdr* hdr = oat_file_->GetSectionHeader(i);
686 CHECK(hdr != nullptr);
687 if (hdr->sh_addr != 0) {
688 hdr->sh_addr += delta_;
Alex Light53cb16b2014-06-12 11:26:29 -0700689 }
690 }
691
Alex Lighta59dd802014-07-02 16:28:08 -0700692 t.NewTiming("Fixup Dynamics");
Alex Light53cb16b2014-06-12 11:26:29 -0700693 for (Elf32_Word i = 0; i < oat_file_->GetDynamicNum(); i++) {
694 Elf32_Dyn& dyn = oat_file_->GetDynamic(i);
695 if (IsDynamicSectionPointer(dyn.d_tag, oat_file_->GetHeader().e_machine)) {
696 dyn.d_un.d_ptr += delta_;
697 }
698 }
699
700 t.NewTiming("Fixup Elf Symbols");
701 // Fixup dynsym
702 Elf32_Shdr* dynsym_sec = oat_file_->FindSectionByName(".dynsym");
703 CHECK(dynsym_sec != nullptr);
704 if (!PatchSymbols(dynsym_sec)) {
705 return false;
706 }
707
708 // Fixup symtab
709 Elf32_Shdr* symtab_sec = oat_file_->FindSectionByName(".symtab");
710 if (symtab_sec != nullptr) {
711 if (!PatchSymbols(symtab_sec)) {
712 return false;
713 }
714 }
715
Alex Light53cb16b2014-06-12 11:26:29 -0700716 return true;
717}
718
719bool PatchOat::PatchSymbols(Elf32_Shdr* section) {
720 Elf32_Sym* syms = reinterpret_cast<Elf32_Sym*>(oat_file_->Begin() + section->sh_offset);
721 const Elf32_Sym* last_sym =
722 reinterpret_cast<Elf32_Sym*>(oat_file_->Begin() + section->sh_offset + section->sh_size);
723 CHECK_EQ(section->sh_size % sizeof(Elf32_Sym), 0u)
724 << "Symtab section size is not multiple of symbol size";
725 for (; syms < last_sym; syms++) {
726 uint8_t sttype = ELF32_ST_TYPE(syms->st_info);
727 Elf32_Word shndx = syms->st_shndx;
728 if (shndx != SHN_ABS && shndx != SHN_COMMON && shndx != SHN_UNDEF &&
729 (sttype == STT_FUNC || sttype == STT_OBJECT)) {
730 CHECK_NE(syms->st_value, 0u);
731 syms->st_value += delta_;
732 }
733 }
734 return true;
735}
736
737bool PatchOat::PatchTextSection() {
738 Elf32_Shdr* patches_sec = oat_file_->FindSectionByName(".oat_patches");
739 if (patches_sec == nullptr) {
Alex Lighta59dd802014-07-02 16:28:08 -0700740 LOG(ERROR) << ".oat_patches section not found. Aborting patch";
Alex Light53cb16b2014-06-12 11:26:29 -0700741 return false;
742 }
743 DCHECK(CheckOatFile()) << "Oat file invalid";
744 CHECK_EQ(patches_sec->sh_type, SHT_OAT_PATCH) << "Unexpected type of .oat_patches";
745 uintptr_t* patches = reinterpret_cast<uintptr_t*>(oat_file_->Begin() + patches_sec->sh_offset);
746 uintptr_t* patches_end = patches + (patches_sec->sh_size/sizeof(uintptr_t));
747 Elf32_Shdr* oat_text_sec = oat_file_->FindSectionByName(".text");
748 CHECK(oat_text_sec != nullptr);
749 byte* to_patch = oat_file_->Begin() + oat_text_sec->sh_offset;
750 uintptr_t to_patch_end = reinterpret_cast<uintptr_t>(to_patch) + oat_text_sec->sh_size;
751
752 for (; patches < patches_end; patches++) {
753 CHECK_LT(*patches, oat_text_sec->sh_size) << "Bad Patch";
754 uint32_t* patch_loc = reinterpret_cast<uint32_t*>(to_patch + *patches);
755 CHECK_LT(reinterpret_cast<uintptr_t>(patch_loc), to_patch_end);
756 *patch_loc += delta_;
757 }
758
759 return true;
760}
761
762static int orig_argc;
763static char** orig_argv;
764
765static std::string CommandLine() {
766 std::vector<std::string> command;
767 for (int i = 0; i < orig_argc; ++i) {
768 command.push_back(orig_argv[i]);
769 }
770 return Join(command, ' ');
771}
772
773static void UsageErrorV(const char* fmt, va_list ap) {
774 std::string error;
775 StringAppendV(&error, fmt, ap);
776 LOG(ERROR) << error;
777}
778
779static void UsageError(const char* fmt, ...) {
780 va_list ap;
781 va_start(ap, fmt);
782 UsageErrorV(fmt, ap);
783 va_end(ap);
784}
785
786static void Usage(const char *fmt, ...) {
787 va_list ap;
788 va_start(ap, fmt);
789 UsageErrorV(fmt, ap);
790 va_end(ap);
791
792 UsageError("Command: %s", CommandLine().c_str());
793 UsageError("Usage: patchoat [options]...");
794 UsageError("");
795 UsageError(" --instruction-set=<isa>: Specifies the instruction set the patched code is");
796 UsageError(" compiled for. Required if you use --input-oat-location");
797 UsageError("");
798 UsageError(" --input-oat-file=<file.oat>: Specifies the exact filename of the oat file to be");
799 UsageError(" patched.");
800 UsageError("");
801 UsageError(" --input-oat-fd=<file-descriptor>: Specifies the file-descriptor of the oat file");
802 UsageError(" to be patched.");
803 UsageError("");
804 UsageError(" --input-oat-location=<file.oat>: Specifies the 'location' to read the patched");
805 UsageError(" oat file from. If used one must also supply the --instruction-set");
806 UsageError("");
807 UsageError(" --input-image-location=<file.art>: Specifies the 'location' of the image file to");
808 UsageError(" be patched. If --instruction-set is not given it will use the instruction set");
809 UsageError(" extracted from the --input-oat-file.");
810 UsageError("");
811 UsageError(" --output-oat-file=<file.oat>: Specifies the exact file to write the patched oat");
812 UsageError(" file to.");
813 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700814 UsageError(" --output-oat-fd=<file-descriptor>: Specifies the file-descriptor to write the");
815 UsageError(" the patched oat file to.");
816 UsageError("");
817 UsageError(" --output-image-file=<file.art>: Specifies the exact file to write the patched");
818 UsageError(" image file to.");
819 UsageError("");
820 UsageError(" --output-image-fd=<file-descriptor>: Specifies the file-descriptor to write the");
821 UsageError(" the patched image file to.");
822 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700823 UsageError(" --orig-base-offset=<original-base-offset>: Specify the base offset the input file");
824 UsageError(" was compiled with. This is needed if one is specifying a --base-offset");
825 UsageError("");
826 UsageError(" --base-offset=<new-base-offset>: Specify the base offset we will repatch the");
827 UsageError(" given files to use. This requires that --orig-base-offset is also given.");
828 UsageError("");
829 UsageError(" --base-offset-delta=<delta>: Specify the amount to change the old base-offset by.");
830 UsageError(" This value may be negative.");
831 UsageError("");
832 UsageError(" --patched-image-file=<file.art>: Use the same patch delta as was used to patch");
833 UsageError(" the given image file.");
834 UsageError("");
835 UsageError(" --patched-image-location=<file.art>: Use the same patch delta as was used to");
836 UsageError(" patch the given image location. If used one must also specify the");
Alex Lighta59dd802014-07-02 16:28:08 -0700837 UsageError(" --instruction-set flag. It will search for this image in the same way that");
838 UsageError(" is done when loading one.");
Alex Light53cb16b2014-06-12 11:26:29 -0700839 UsageError("");
Alex Lightcf4bf382014-07-24 11:29:14 -0700840 UsageError(" --lock-output: Obtain a flock on output oat file before starting.");
841 UsageError("");
842 UsageError(" --no-lock-output: Do not attempt to obtain a flock on output oat file.");
843 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700844 UsageError(" --dump-timings: dump out patch timing information");
845 UsageError("");
846 UsageError(" --no-dump-timings: do not dump out patch timing information");
847 UsageError("");
848
849 exit(EXIT_FAILURE);
850}
851
Alex Lighteefbe392014-07-08 09:53:18 -0700852static bool ReadBaseDelta(const char* name, off_t* delta, std::string* error_msg) {
Alex Light53cb16b2014-06-12 11:26:29 -0700853 CHECK(name != nullptr);
854 CHECK(delta != nullptr);
855 std::unique_ptr<File> file;
856 if (OS::FileExists(name)) {
857 file.reset(OS::OpenFileForReading(name));
858 if (file.get() == nullptr) {
Alex Lighteefbe392014-07-08 09:53:18 -0700859 *error_msg = "Failed to open file %s for reading";
Alex Light53cb16b2014-06-12 11:26:29 -0700860 return false;
861 }
862 } else {
Alex Lighteefbe392014-07-08 09:53:18 -0700863 *error_msg = "File %s does not exist";
Alex Light53cb16b2014-06-12 11:26:29 -0700864 return false;
865 }
866 CHECK(file.get() != nullptr);
867 ImageHeader hdr;
868 if (sizeof(hdr) != file->Read(reinterpret_cast<char*>(&hdr), sizeof(hdr), 0)) {
Alex Lighteefbe392014-07-08 09:53:18 -0700869 *error_msg = "Failed to read file %s";
Alex Light53cb16b2014-06-12 11:26:29 -0700870 return false;
871 }
872 if (!hdr.IsValid()) {
Alex Lighteefbe392014-07-08 09:53:18 -0700873 *error_msg = "%s does not contain a valid image header.";
Alex Light53cb16b2014-06-12 11:26:29 -0700874 return false;
875 }
876 *delta = hdr.GetPatchDelta();
877 return true;
878}
879
880static File* CreateOrOpen(const char* name, bool* created) {
881 if (OS::FileExists(name)) {
882 *created = false;
883 return OS::OpenFileReadWrite(name);
884 } else {
885 *created = true;
Alex Lightcf4bf382014-07-24 11:29:14 -0700886 std::unique_ptr<File> f(OS::CreateEmptyFile(name));
887 if (f.get() != nullptr) {
888 if (fchmod(f->Fd(), 0644) != 0) {
889 PLOG(ERROR) << "Unable to make " << name << " world readable";
890 unlink(name);
891 return nullptr;
892 }
893 }
894 return f.release();
Alex Light53cb16b2014-06-12 11:26:29 -0700895 }
896}
897
Alex Lighteefbe392014-07-08 09:53:18 -0700898static int patchoat(int argc, char **argv) {
Alex Light53cb16b2014-06-12 11:26:29 -0700899 InitLogging(argv);
Mathieu Chartierc54e12a2014-10-14 16:22:41 -0700900 MemMap::Init();
Alex Light53cb16b2014-06-12 11:26:29 -0700901 const bool debug = kIsDebugBuild;
902 orig_argc = argc;
903 orig_argv = argv;
904 TimingLogger timings("patcher", false, false);
905
906 InitLogging(argv);
907
908 // Skip over the command name.
909 argv++;
910 argc--;
911
912 if (argc == 0) {
913 Usage("No arguments specified");
914 }
915
916 timings.StartTiming("Patchoat");
917
918 // cmd line args
919 bool isa_set = false;
920 InstructionSet isa = kNone;
921 std::string input_oat_filename;
922 std::string input_oat_location;
923 int input_oat_fd = -1;
924 bool have_input_oat = false;
925 std::string input_image_location;
926 std::string output_oat_filename;
Alex Light53cb16b2014-06-12 11:26:29 -0700927 int output_oat_fd = -1;
928 bool have_output_oat = false;
929 std::string output_image_filename;
Alex Light53cb16b2014-06-12 11:26:29 -0700930 int output_image_fd = -1;
931 bool have_output_image = false;
932 uintptr_t base_offset = 0;
933 bool base_offset_set = false;
934 uintptr_t orig_base_offset = 0;
935 bool orig_base_offset_set = false;
936 off_t base_delta = 0;
937 bool base_delta_set = false;
938 std::string patched_image_filename;
939 std::string patched_image_location;
940 bool dump_timings = kIsDebugBuild;
Alex Lightcf4bf382014-07-24 11:29:14 -0700941 bool lock_output = true;
Alex Light53cb16b2014-06-12 11:26:29 -0700942
943 for (int i = 0; i < argc; i++) {
944 const StringPiece option(argv[i]);
945 const bool log_options = false;
946 if (log_options) {
947 LOG(INFO) << "patchoat: option[" << i << "]=" << argv[i];
948 }
Alex Light53cb16b2014-06-12 11:26:29 -0700949 if (option.starts_with("--instruction-set=")) {
950 isa_set = true;
951 const char* isa_str = option.substr(strlen("--instruction-set=")).data();
Andreas Gampeaabbb202014-08-19 17:28:06 -0700952 isa = GetInstructionSetFromString(isa_str);
953 if (isa == kNone) {
954 Usage("Unknown or invalid instruction set %s", isa_str);
Alex Light53cb16b2014-06-12 11:26:29 -0700955 }
956 } else if (option.starts_with("--input-oat-location=")) {
957 if (have_input_oat) {
958 Usage("Only one of --input-oat-file, --input-oat-location and --input-oat-fd may be used.");
959 }
960 have_input_oat = true;
961 input_oat_location = option.substr(strlen("--input-oat-location=")).data();
962 } else if (option.starts_with("--input-oat-file=")) {
963 if (have_input_oat) {
964 Usage("Only one of --input-oat-file, --input-oat-location and --input-oat-fd may be used.");
965 }
966 have_input_oat = true;
967 input_oat_filename = option.substr(strlen("--input-oat-file=")).data();
968 } else if (option.starts_with("--input-oat-fd=")) {
969 if (have_input_oat) {
970 Usage("Only one of --input-oat-file, --input-oat-location and --input-oat-fd may be used.");
971 }
972 have_input_oat = true;
973 const char* oat_fd_str = option.substr(strlen("--input-oat-fd=")).data();
974 if (!ParseInt(oat_fd_str, &input_oat_fd)) {
975 Usage("Failed to parse --input-oat-fd argument '%s' as an integer", oat_fd_str);
976 }
977 if (input_oat_fd < 0) {
978 Usage("--input-oat-fd pass a negative value %d", input_oat_fd);
979 }
980 } else if (option.starts_with("--input-image-location=")) {
981 input_image_location = option.substr(strlen("--input-image-location=")).data();
Alex Light53cb16b2014-06-12 11:26:29 -0700982 } else if (option.starts_with("--output-oat-file=")) {
983 if (have_output_oat) {
Alex Lightcf4bf382014-07-24 11:29:14 -0700984 Usage("Only one of --output-oat-file, and --output-oat-fd may be used.");
Alex Light53cb16b2014-06-12 11:26:29 -0700985 }
986 have_output_oat = true;
987 output_oat_filename = option.substr(strlen("--output-oat-file=")).data();
988 } else if (option.starts_with("--output-oat-fd=")) {
989 if (have_output_oat) {
Alex Lightcf4bf382014-07-24 11:29:14 -0700990 Usage("Only one of --output-oat-file, --output-oat-fd may be used.");
Alex Light53cb16b2014-06-12 11:26:29 -0700991 }
992 have_output_oat = true;
993 const char* oat_fd_str = option.substr(strlen("--output-oat-fd=")).data();
994 if (!ParseInt(oat_fd_str, &output_oat_fd)) {
995 Usage("Failed to parse --output-oat-fd argument '%s' as an integer", oat_fd_str);
996 }
997 if (output_oat_fd < 0) {
998 Usage("--output-oat-fd pass a negative value %d", output_oat_fd);
999 }
Alex Light53cb16b2014-06-12 11:26:29 -07001000 } else if (option.starts_with("--output-image-file=")) {
1001 if (have_output_image) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001002 Usage("Only one of --output-image-file, and --output-image-fd may be used.");
Alex Light53cb16b2014-06-12 11:26:29 -07001003 }
1004 have_output_image = true;
1005 output_image_filename = option.substr(strlen("--output-image-file=")).data();
1006 } else if (option.starts_with("--output-image-fd=")) {
1007 if (have_output_image) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001008 Usage("Only one of --output-image-file, and --output-image-fd may be used.");
Alex Light53cb16b2014-06-12 11:26:29 -07001009 }
1010 have_output_image = true;
1011 const char* image_fd_str = option.substr(strlen("--output-image-fd=")).data();
1012 if (!ParseInt(image_fd_str, &output_image_fd)) {
1013 Usage("Failed to parse --output-image-fd argument '%s' as an integer", image_fd_str);
1014 }
1015 if (output_image_fd < 0) {
1016 Usage("--output-image-fd pass a negative value %d", output_image_fd);
1017 }
1018 } else if (option.starts_with("--orig-base-offset=")) {
1019 const char* orig_base_offset_str = option.substr(strlen("--orig-base-offset=")).data();
1020 orig_base_offset_set = true;
1021 if (!ParseUint(orig_base_offset_str, &orig_base_offset)) {
1022 Usage("Failed to parse --orig-base-offset argument '%s' as an uintptr_t",
1023 orig_base_offset_str);
1024 }
1025 } else if (option.starts_with("--base-offset=")) {
1026 const char* base_offset_str = option.substr(strlen("--base-offset=")).data();
1027 base_offset_set = true;
1028 if (!ParseUint(base_offset_str, &base_offset)) {
1029 Usage("Failed to parse --base-offset argument '%s' as an uintptr_t", base_offset_str);
1030 }
1031 } else if (option.starts_with("--base-offset-delta=")) {
1032 const char* base_delta_str = option.substr(strlen("--base-offset-delta=")).data();
1033 base_delta_set = true;
1034 if (!ParseInt(base_delta_str, &base_delta)) {
1035 Usage("Failed to parse --base-offset-delta argument '%s' as an off_t", base_delta_str);
1036 }
1037 } else if (option.starts_with("--patched-image-location=")) {
1038 patched_image_location = option.substr(strlen("--patched-image-location=")).data();
1039 } else if (option.starts_with("--patched-image-file=")) {
1040 patched_image_filename = option.substr(strlen("--patched-image-file=")).data();
Alex Lightcf4bf382014-07-24 11:29:14 -07001041 } else if (option == "--lock-output") {
1042 lock_output = true;
1043 } else if (option == "--no-lock-output") {
1044 lock_output = false;
Alex Light53cb16b2014-06-12 11:26:29 -07001045 } else if (option == "--dump-timings") {
1046 dump_timings = true;
1047 } else if (option == "--no-dump-timings") {
1048 dump_timings = false;
1049 } else {
1050 Usage("Unknown argument %s", option.data());
1051 }
1052 }
1053
1054 {
1055 // Only 1 of these may be set.
1056 uint32_t cnt = 0;
1057 cnt += (base_delta_set) ? 1 : 0;
1058 cnt += (base_offset_set && orig_base_offset_set) ? 1 : 0;
1059 cnt += (!patched_image_filename.empty()) ? 1 : 0;
1060 cnt += (!patched_image_location.empty()) ? 1 : 0;
1061 if (cnt > 1) {
1062 Usage("Only one of --base-offset/--orig-base-offset, --base-offset-delta, "
1063 "--patched-image-filename or --patched-image-location may be used.");
1064 } else if (cnt == 0) {
1065 Usage("Must specify --base-offset-delta, --base-offset and --orig-base-offset, "
1066 "--patched-image-location or --patched-image-file");
1067 }
1068 }
1069
1070 if (have_input_oat != have_output_oat) {
1071 Usage("Either both input and output oat must be supplied or niether must be.");
1072 }
1073
1074 if ((!input_image_location.empty()) != have_output_image) {
1075 Usage("Either both input and output image must be supplied or niether must be.");
1076 }
1077
1078 // We know we have both the input and output so rename for clarity.
1079 bool have_image_files = have_output_image;
1080 bool have_oat_files = have_output_oat;
1081
1082 if (!have_oat_files && !have_image_files) {
1083 Usage("Must be patching either an oat or an image file or both.");
1084 }
1085
1086 if (!have_oat_files && !isa_set) {
1087 Usage("Must include ISA if patching an image file without an oat file.");
1088 }
1089
1090 if (!input_oat_location.empty()) {
1091 if (!isa_set) {
1092 Usage("specifying a location requires specifying an instruction set");
1093 }
Alex Lightcf4bf382014-07-24 11:29:14 -07001094 if (!LocationToFilename(input_oat_location, isa, &input_oat_filename)) {
1095 Usage("Unable to find filename for input oat location %s", input_oat_location.c_str());
1096 }
Alex Light53cb16b2014-06-12 11:26:29 -07001097 if (debug) {
1098 LOG(INFO) << "Using input-oat-file " << input_oat_filename;
1099 }
1100 }
Alex Light53cb16b2014-06-12 11:26:29 -07001101 if (!patched_image_location.empty()) {
1102 if (!isa_set) {
1103 Usage("specifying a location requires specifying an instruction set");
1104 }
Alex Lighta59dd802014-07-02 16:28:08 -07001105 std::string system_filename;
1106 bool has_system = false;
1107 std::string cache_filename;
1108 bool has_cache = false;
1109 bool has_android_data_unused = false;
Andreas Gampe33c36d42014-09-18 20:56:04 -07001110 bool is_global_cache = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001111 if (!gc::space::ImageSpace::FindImageFilename(patched_image_location.c_str(), isa,
1112 &system_filename, &has_system, &cache_filename,
Andreas Gampe33c36d42014-09-18 20:56:04 -07001113 &has_android_data_unused, &has_cache,
1114 &is_global_cache)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001115 Usage("Unable to determine image file for location %s", patched_image_location.c_str());
1116 }
1117 if (has_cache) {
1118 patched_image_filename = cache_filename;
1119 } else if (has_system) {
1120 LOG(WARNING) << "Only image file found was in /system for image location "
1121 << patched_image_location;
1122 patched_image_filename = system_filename;
1123 } else {
1124 Usage("Unable to determine image file for location %s", patched_image_location.c_str());
1125 }
Alex Light53cb16b2014-06-12 11:26:29 -07001126 if (debug) {
1127 LOG(INFO) << "Using patched-image-file " << patched_image_filename;
1128 }
1129 }
1130
1131 if (!base_delta_set) {
1132 if (orig_base_offset_set && base_offset_set) {
1133 base_delta_set = true;
1134 base_delta = base_offset - orig_base_offset;
1135 } else if (!patched_image_filename.empty()) {
1136 base_delta_set = true;
1137 std::string error_msg;
Alex Lighteefbe392014-07-08 09:53:18 -07001138 if (!ReadBaseDelta(patched_image_filename.c_str(), &base_delta, &error_msg)) {
Alex Light53cb16b2014-06-12 11:26:29 -07001139 Usage(error_msg.c_str(), patched_image_filename.c_str());
1140 }
1141 } else {
1142 if (base_offset_set) {
1143 Usage("Unable to determine original base offset.");
1144 } else {
1145 Usage("Must supply a desired new offset or delta.");
1146 }
1147 }
1148 }
1149
1150 if (!IsAligned<kPageSize>(base_delta)) {
1151 Usage("Base offset/delta must be alligned to a pagesize (0x%08x) boundary.", kPageSize);
1152 }
1153
1154 // Do we need to cleanup output files if we fail?
1155 bool new_image_out = false;
1156 bool new_oat_out = false;
1157
1158 std::unique_ptr<File> input_oat;
1159 std::unique_ptr<File> output_oat;
1160 std::unique_ptr<File> output_image;
1161
1162 if (have_image_files) {
1163 CHECK(!input_image_location.empty());
1164
1165 if (output_image_fd != -1) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001166 if (output_image_filename.empty()) {
1167 output_image_filename = "output-image-file";
1168 }
Alex Light53cb16b2014-06-12 11:26:29 -07001169 output_image.reset(new File(output_image_fd, output_image_filename));
1170 } else {
1171 CHECK(!output_image_filename.empty());
1172 output_image.reset(CreateOrOpen(output_image_filename.c_str(), &new_image_out));
1173 }
1174 } else {
1175 CHECK(output_image_filename.empty() && output_image_fd == -1 && input_image_location.empty());
1176 }
1177
1178 if (have_oat_files) {
1179 if (input_oat_fd != -1) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001180 if (input_oat_filename.empty()) {
1181 input_oat_filename = "input-oat-file";
1182 }
Alex Light53cb16b2014-06-12 11:26:29 -07001183 input_oat.reset(new File(input_oat_fd, input_oat_filename));
Igor Murashkin90ca5c02014-10-22 11:37:02 -07001184 if (input_oat == nullptr) {
1185 // Unlikely, but ensure exhaustive logging in non-0 exit code case
1186 LOG(ERROR) << "Failed to open input oat file by its FD" << input_oat_fd;
1187 }
Alex Light53cb16b2014-06-12 11:26:29 -07001188 } else {
1189 CHECK(!input_oat_filename.empty());
1190 input_oat.reset(OS::OpenFileForReading(input_oat_filename.c_str()));
Igor Murashkin90ca5c02014-10-22 11:37:02 -07001191 if (input_oat == nullptr) {
1192 int err = errno;
1193 LOG(ERROR) << "Failed to open input oat file " << input_oat_filename
1194 << ": " << strerror(err) << "(" << err << ")";
Andreas Gampe1c83cbc2014-07-22 18:52:29 -07001195 }
Alex Light53cb16b2014-06-12 11:26:29 -07001196 }
1197
1198 if (output_oat_fd != -1) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001199 if (output_oat_filename.empty()) {
1200 output_oat_filename = "output-oat-file";
Alex Lighta59dd802014-07-02 16:28:08 -07001201 }
Alex Lightcf4bf382014-07-24 11:29:14 -07001202 output_oat.reset(new File(output_oat_fd, output_oat_filename));
Igor Murashkin90ca5c02014-10-22 11:37:02 -07001203 if (output_oat == nullptr) {
1204 // Unlikely, but ensure exhaustive logging in non-0 exit code case
1205 LOG(ERROR) << "Failed to open output oat file by its FD" << output_oat_fd;
1206 }
Alex Light53cb16b2014-06-12 11:26:29 -07001207 } else {
1208 CHECK(!output_oat_filename.empty());
1209 output_oat.reset(CreateOrOpen(output_oat_filename.c_str(), &new_oat_out));
Igor Murashkin90ca5c02014-10-22 11:37:02 -07001210 if (output_oat == nullptr) {
1211 int err = errno;
1212 LOG(ERROR) << "Failed to open output oat file " << output_oat_filename
1213 << ": " << strerror(err) << "(" << err << ")";
1214 }
Alex Light53cb16b2014-06-12 11:26:29 -07001215 }
1216 }
1217
Igor Murashkin90ca5c02014-10-22 11:37:02 -07001218 // TODO: get rid of this.
Alex Light53cb16b2014-06-12 11:26:29 -07001219 auto cleanup = [&output_image_filename, &output_oat_filename,
1220 &new_oat_out, &new_image_out, &timings, &dump_timings](bool success) {
1221 timings.EndTiming();
1222 if (!success) {
1223 if (new_oat_out) {
1224 CHECK(!output_oat_filename.empty());
1225 unlink(output_oat_filename.c_str());
1226 }
1227 if (new_image_out) {
1228 CHECK(!output_image_filename.empty());
1229 unlink(output_image_filename.c_str());
1230 }
1231 }
1232 if (dump_timings) {
1233 LOG(INFO) << Dumpable<TimingLogger>(timings);
1234 }
Igor Murashkin90ca5c02014-10-22 11:37:02 -07001235
1236 if (kIsDebugBuild) {
1237 LOG(INFO) << "Cleaning up.. success? " << success;
1238 }
Alex Light53cb16b2014-06-12 11:26:29 -07001239 };
1240
Igor Murashkin90ca5c02014-10-22 11:37:02 -07001241 if (have_oat_files && (input_oat.get() == nullptr || output_oat.get() == nullptr)) {
1242 LOG(ERROR) << "Failed to open input/output oat files";
1243 cleanup(false);
1244 return EXIT_FAILURE;
1245 } else if (have_image_files && output_image.get() == nullptr) {
1246 LOG(ERROR) << "Failed to open output image file";
Alex Lightcf4bf382014-07-24 11:29:14 -07001247 cleanup(false);
1248 return EXIT_FAILURE;
1249 }
1250
Igor Murashkin90ca5c02014-10-22 11:37:02 -07001251 if (debug) {
1252 LOG(INFO) << "moving offset by " << base_delta
1253 << " (0x" << std::hex << base_delta << ") bytes or "
1254 << std::dec << (base_delta/kPageSize) << " pages.";
1255 }
1256
1257 // TODO: is it going to be promatic to unlink a file that was flock-ed?
Alex Lightcf4bf382014-07-24 11:29:14 -07001258 ScopedFlock output_oat_lock;
1259 if (lock_output) {
1260 std::string error_msg;
1261 if (have_oat_files && !output_oat_lock.Init(output_oat.get(), &error_msg)) {
1262 LOG(ERROR) << "Unable to lock output oat " << output_image->GetPath() << ": " << error_msg;
1263 cleanup(false);
1264 return EXIT_FAILURE;
1265 }
1266 }
1267
Alex Light53cb16b2014-06-12 11:26:29 -07001268 bool ret;
1269 if (have_image_files && have_oat_files) {
1270 TimingLogger::ScopedTiming pt("patch image and oat", &timings);
1271 ret = PatchOat::Patch(input_oat.get(), input_image_location, base_delta,
Igor Murashkin90ca5c02014-10-22 11:37:02 -07001272 output_oat.get(), output_image.get(), isa, &timings,
1273 output_oat_fd >= 0, // was it opened from FD?
1274 new_oat_out);
Alex Light53cb16b2014-06-12 11:26:29 -07001275 } else if (have_oat_files) {
1276 TimingLogger::ScopedTiming pt("patch oat", &timings);
Igor Murashkin90ca5c02014-10-22 11:37:02 -07001277 ret = PatchOat::Patch(input_oat.get(), base_delta, output_oat.get(), &timings,
1278 output_oat_fd >= 0, // was it opened from FD?
1279 new_oat_out);
1280 } else if (have_image_files) {
Alex Light53cb16b2014-06-12 11:26:29 -07001281 TimingLogger::ScopedTiming pt("patch image", &timings);
Alex Lighteefbe392014-07-08 09:53:18 -07001282 ret = PatchOat::Patch(input_image_location, base_delta, output_image.get(), isa, &timings);
Igor Murashkin90ca5c02014-10-22 11:37:02 -07001283 } else {
1284 CHECK(false);
1285 ret = true;
1286 }
1287
1288 if (kIsDebugBuild) {
1289 LOG(INFO) << "Exiting with return ... " << ret;
Alex Light53cb16b2014-06-12 11:26:29 -07001290 }
1291 cleanup(ret);
Alex Light53cb16b2014-06-12 11:26:29 -07001292 return (ret) ? EXIT_SUCCESS : EXIT_FAILURE;
1293}
1294
1295} // namespace art
1296
1297int main(int argc, char **argv) {
1298 return art::patchoat(argc, argv);
1299}