blob: 9f55c94b060729d64ada1352eb4b76136b4cea92 [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
Mathieu Chartiere832e642014-11-10 11:08:06 -0800179 PatchOat p(isa, image.release(), ispc->GetLiveBitmap(), ispc->GetMemMap(),
Alex Light53cb16b2014-06-12 11:26:29 -0700180 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
Mathieu Chartiere832e642014-11-10 11:08:06 -0800301 PatchOat p(isa, elf.release(), image.release(), ispc->GetLiveBitmap(), ispc->GetMemMap(),
Alex Light53cb16b2014-06-12 11:26:29 -0700302 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>()) {
Mathieu Chartiere832e642014-11-10 11:08:06 -0800526 FixupMethod(down_cast<mirror::ArtMethod*>(object), down_cast<mirror::ArtMethod*>(copy));
Alex Light53cb16b2014-06-12 11:26:29 -0700527 }
528}
529
530void PatchOat::FixupMethod(mirror::ArtMethod* object, mirror::ArtMethod* copy) {
Mathieu Chartiere832e642014-11-10 11:08:06 -0800531 const size_t pointer_size = InstructionSetPointerSize(isa_);
Alex Light53cb16b2014-06-12 11:26:29 -0700532 // 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>(
Mathieu Chartiere832e642014-11-10 11:08:06 -0800536 object->GetEntryPointFromPortableCompiledCodePtrSize<kVerifyNone>(pointer_size));
Alex Light53cb16b2014-06-12 11:26:29 -0700537 if (portable != 0) {
Mathieu Chartiere832e642014-11-10 11:08:06 -0800538 copy->SetEntryPointFromPortableCompiledCodePtrSize(reinterpret_cast<void*>(portable + delta_),
539 pointer_size);
Alex Light53cb16b2014-06-12 11:26:29 -0700540 }
Ian Rogers63bc11e2014-09-18 08:56:45 -0700541#endif
Alex Light53cb16b2014-06-12 11:26:29 -0700542 uintptr_t quick= reinterpret_cast<uintptr_t>(
Mathieu Chartiere832e642014-11-10 11:08:06 -0800543 object->GetEntryPointFromQuickCompiledCodePtrSize<kVerifyNone>(pointer_size));
Alex Light53cb16b2014-06-12 11:26:29 -0700544 if (quick != 0) {
Mathieu Chartiere832e642014-11-10 11:08:06 -0800545 copy->SetEntryPointFromQuickCompiledCodePtrSize(reinterpret_cast<void*>(quick + delta_),
546 pointer_size);
Alex Light53cb16b2014-06-12 11:26:29 -0700547 }
548 uintptr_t interpreter = reinterpret_cast<uintptr_t>(
Mathieu Chartiere832e642014-11-10 11:08:06 -0800549 object->GetEntryPointFromInterpreterPtrSize<kVerifyNone>(pointer_size));
Alex Light53cb16b2014-06-12 11:26:29 -0700550 if (interpreter != 0) {
Mathieu Chartiere832e642014-11-10 11:08:06 -0800551 copy->SetEntryPointFromInterpreterPtrSize(
552 reinterpret_cast<mirror::EntryPointFromInterpreter*>(interpreter + delta_), pointer_size);
Alex Light53cb16b2014-06-12 11:26:29 -0700553 }
554
Mathieu Chartiere832e642014-11-10 11:08:06 -0800555 uintptr_t native_method = reinterpret_cast<uintptr_t>(
556 object->GetEntryPointFromJniPtrSize(pointer_size));
Alex Light53cb16b2014-06-12 11:26:29 -0700557 if (native_method != 0) {
Mathieu Chartiere832e642014-11-10 11:08:06 -0800558 copy->SetEntryPointFromJniPtrSize(reinterpret_cast<void*>(native_method + delta_),
559 pointer_size);
Alex Light53cb16b2014-06-12 11:26:29 -0700560 }
561
Mathieu Chartiere832e642014-11-10 11:08:06 -0800562 uintptr_t native_gc_map = reinterpret_cast<uintptr_t>(
563 object->GetNativeGcMapPtrSize(pointer_size));
Alex Light53cb16b2014-06-12 11:26:29 -0700564 if (native_gc_map != 0) {
Mathieu Chartiere832e642014-11-10 11:08:06 -0800565 copy->SetNativeGcMapPtrSize(reinterpret_cast<uint8_t*>(native_gc_map + delta_), pointer_size);
Alex Light53cb16b2014-06-12 11:26:29 -0700566 }
567}
568
Igor Murashkin90ca5c02014-10-22 11:37:02 -0700569bool PatchOat::Patch(File* input_oat, off_t delta, File* output_oat, TimingLogger* timings,
570 bool output_oat_opened_from_fd, bool new_oat_out) {
Alex Light53cb16b2014-06-12 11:26:29 -0700571 CHECK(input_oat != nullptr);
572 CHECK(output_oat != nullptr);
573 CHECK_GE(input_oat->Fd(), 0);
574 CHECK_GE(output_oat->Fd(), 0);
Alex Lighteefbe392014-07-08 09:53:18 -0700575 TimingLogger::ScopedTiming t("Setup Oat File Patching", timings);
Alex Light53cb16b2014-06-12 11:26:29 -0700576
577 std::string error_msg;
Igor Murashkin90ca5c02014-10-22 11:37:02 -0700578 std::unique_ptr<ElfFile> elf(ElfFile::Open(input_oat,
Alex Light53cb16b2014-06-12 11:26:29 -0700579 PROT_READ | PROT_WRITE, MAP_PRIVATE, &error_msg));
580 if (elf.get() == nullptr) {
581 LOG(ERROR) << "unable to open oat file " << input_oat->GetPath() << " : " << error_msg;
582 return false;
583 }
584
Igor Murashkin90ca5c02014-10-22 11:37:02 -0700585 MaybePic is_oat_pic = IsOatPic(elf.get());
586 if (is_oat_pic >= ERROR_FIRST) {
587 // Error logged by IsOatPic
588 return false;
589 } else if (is_oat_pic == PIC) {
590 // Do not need to do ELF-file patching. Create a symlink and skip the rest.
591 // Any errors will be logged by the function call.
592 return ReplaceOatFileWithSymlink(input_oat->GetPath(),
593 output_oat->GetPath(),
594 output_oat_opened_from_fd,
595 new_oat_out);
596 } else {
597 CHECK(is_oat_pic == NOT_PIC);
598 }
599
Alex Light53cb16b2014-06-12 11:26:29 -0700600 PatchOat p(elf.release(), delta, timings);
601 t.NewTiming("Patch Oat file");
602 if (!p.PatchElf()) {
603 return false;
604 }
605
606 t.NewTiming("Writing oat file");
607 if (!p.WriteElf(output_oat)) {
608 return false;
609 }
610 return true;
611}
612
613bool PatchOat::CheckOatFile() {
614 Elf32_Shdr* patches_sec = oat_file_->FindSectionByName(".oat_patches");
615 if (patches_sec == nullptr) {
616 return false;
617 }
618 if (patches_sec->sh_type != SHT_OAT_PATCH) {
619 return false;
620 }
621 uintptr_t* patches = reinterpret_cast<uintptr_t*>(oat_file_->Begin() + patches_sec->sh_offset);
622 uintptr_t* patches_end = patches + (patches_sec->sh_size/sizeof(uintptr_t));
623 Elf32_Shdr* oat_data_sec = oat_file_->FindSectionByName(".rodata");
624 Elf32_Shdr* oat_text_sec = oat_file_->FindSectionByName(".text");
625 if (oat_data_sec == nullptr) {
626 return false;
627 }
628 if (oat_text_sec == nullptr) {
629 return false;
630 }
631 if (oat_text_sec->sh_offset <= oat_data_sec->sh_offset) {
632 return false;
633 }
634
635 for (; patches < patches_end; patches++) {
636 if (oat_text_sec->sh_size <= *patches) {
637 return false;
638 }
639 }
640
641 return true;
642}
643
Alex Lighta59dd802014-07-02 16:28:08 -0700644bool PatchOat::PatchOatHeader() {
645 Elf32_Shdr *rodata_sec = oat_file_->FindSectionByName(".rodata");
646 if (rodata_sec == nullptr) {
647 return false;
648 }
649 OatHeader* oat_header = reinterpret_cast<OatHeader*>(oat_file_->Begin() + rodata_sec->sh_offset);
650 if (!oat_header->IsValid()) {
651 LOG(ERROR) << "Elf file " << oat_file_->GetFile().GetPath() << " has an invalid oat header";
652 return false;
653 }
654 oat_header->RelocateOat(delta_);
655 return true;
656}
657
Alex Light53cb16b2014-06-12 11:26:29 -0700658bool PatchOat::PatchElf() {
Alex Lighta59dd802014-07-02 16:28:08 -0700659 TimingLogger::ScopedTiming t("Fixup Elf Text Section", timings_);
660 if (!PatchTextSection()) {
661 return false;
662 }
663
664 if (!PatchOatHeader()) {
665 return false;
666 }
667
668 bool need_fixup = false;
669 t.NewTiming("Fixup Elf Headers");
Alex Light53cb16b2014-06-12 11:26:29 -0700670 // Fixup Phdr's
671 for (unsigned int i = 0; i < oat_file_->GetProgramHeaderNum(); i++) {
Andreas Gampeafa6b8e2014-09-12 18:38:24 -0700672 Elf32_Phdr* hdr = oat_file_->GetProgramHeader(i);
673 CHECK(hdr != nullptr);
674 if (hdr->p_vaddr != 0 && hdr->p_vaddr != hdr->p_offset) {
Alex Lighta59dd802014-07-02 16:28:08 -0700675 need_fixup = true;
Andreas Gampeafa6b8e2014-09-12 18:38:24 -0700676 hdr->p_vaddr += delta_;
Alex Light53cb16b2014-06-12 11:26:29 -0700677 }
Andreas Gampeafa6b8e2014-09-12 18:38:24 -0700678 if (hdr->p_paddr != 0 && hdr->p_paddr != hdr->p_offset) {
Alex Lighta59dd802014-07-02 16:28:08 -0700679 need_fixup = true;
Andreas Gampeafa6b8e2014-09-12 18:38:24 -0700680 hdr->p_paddr += delta_;
Alex Light53cb16b2014-06-12 11:26:29 -0700681 }
682 }
Alex Lighta59dd802014-07-02 16:28:08 -0700683 if (!need_fixup) {
684 // This was never passed through ElfFixup so all headers/symbols just have their offset as
685 // their addr. Therefore we do not need to update these parts.
686 return true;
687 }
688 t.NewTiming("Fixup Section Headers");
Alex Light53cb16b2014-06-12 11:26:29 -0700689 for (unsigned int i = 0; i < oat_file_->GetSectionHeaderNum(); i++) {
Andreas Gampeafa6b8e2014-09-12 18:38:24 -0700690 Elf32_Shdr* hdr = oat_file_->GetSectionHeader(i);
691 CHECK(hdr != nullptr);
692 if (hdr->sh_addr != 0) {
693 hdr->sh_addr += delta_;
Alex Light53cb16b2014-06-12 11:26:29 -0700694 }
695 }
696
Alex Lighta59dd802014-07-02 16:28:08 -0700697 t.NewTiming("Fixup Dynamics");
Alex Light53cb16b2014-06-12 11:26:29 -0700698 for (Elf32_Word i = 0; i < oat_file_->GetDynamicNum(); i++) {
699 Elf32_Dyn& dyn = oat_file_->GetDynamic(i);
700 if (IsDynamicSectionPointer(dyn.d_tag, oat_file_->GetHeader().e_machine)) {
701 dyn.d_un.d_ptr += delta_;
702 }
703 }
704
705 t.NewTiming("Fixup Elf Symbols");
706 // Fixup dynsym
707 Elf32_Shdr* dynsym_sec = oat_file_->FindSectionByName(".dynsym");
708 CHECK(dynsym_sec != nullptr);
709 if (!PatchSymbols(dynsym_sec)) {
710 return false;
711 }
712
713 // Fixup symtab
714 Elf32_Shdr* symtab_sec = oat_file_->FindSectionByName(".symtab");
715 if (symtab_sec != nullptr) {
716 if (!PatchSymbols(symtab_sec)) {
717 return false;
718 }
719 }
720
Alex Light53cb16b2014-06-12 11:26:29 -0700721 return true;
722}
723
724bool PatchOat::PatchSymbols(Elf32_Shdr* section) {
725 Elf32_Sym* syms = reinterpret_cast<Elf32_Sym*>(oat_file_->Begin() + section->sh_offset);
726 const Elf32_Sym* last_sym =
727 reinterpret_cast<Elf32_Sym*>(oat_file_->Begin() + section->sh_offset + section->sh_size);
728 CHECK_EQ(section->sh_size % sizeof(Elf32_Sym), 0u)
729 << "Symtab section size is not multiple of symbol size";
730 for (; syms < last_sym; syms++) {
731 uint8_t sttype = ELF32_ST_TYPE(syms->st_info);
732 Elf32_Word shndx = syms->st_shndx;
733 if (shndx != SHN_ABS && shndx != SHN_COMMON && shndx != SHN_UNDEF &&
734 (sttype == STT_FUNC || sttype == STT_OBJECT)) {
735 CHECK_NE(syms->st_value, 0u);
736 syms->st_value += delta_;
737 }
738 }
739 return true;
740}
741
742bool PatchOat::PatchTextSection() {
743 Elf32_Shdr* patches_sec = oat_file_->FindSectionByName(".oat_patches");
744 if (patches_sec == nullptr) {
Alex Lighta59dd802014-07-02 16:28:08 -0700745 LOG(ERROR) << ".oat_patches section not found. Aborting patch";
Alex Light53cb16b2014-06-12 11:26:29 -0700746 return false;
747 }
748 DCHECK(CheckOatFile()) << "Oat file invalid";
749 CHECK_EQ(patches_sec->sh_type, SHT_OAT_PATCH) << "Unexpected type of .oat_patches";
750 uintptr_t* patches = reinterpret_cast<uintptr_t*>(oat_file_->Begin() + patches_sec->sh_offset);
751 uintptr_t* patches_end = patches + (patches_sec->sh_size/sizeof(uintptr_t));
752 Elf32_Shdr* oat_text_sec = oat_file_->FindSectionByName(".text");
753 CHECK(oat_text_sec != nullptr);
754 byte* to_patch = oat_file_->Begin() + oat_text_sec->sh_offset;
755 uintptr_t to_patch_end = reinterpret_cast<uintptr_t>(to_patch) + oat_text_sec->sh_size;
756
757 for (; patches < patches_end; patches++) {
758 CHECK_LT(*patches, oat_text_sec->sh_size) << "Bad Patch";
759 uint32_t* patch_loc = reinterpret_cast<uint32_t*>(to_patch + *patches);
760 CHECK_LT(reinterpret_cast<uintptr_t>(patch_loc), to_patch_end);
761 *patch_loc += delta_;
762 }
763
764 return true;
765}
766
767static int orig_argc;
768static char** orig_argv;
769
770static std::string CommandLine() {
771 std::vector<std::string> command;
772 for (int i = 0; i < orig_argc; ++i) {
773 command.push_back(orig_argv[i]);
774 }
775 return Join(command, ' ');
776}
777
778static void UsageErrorV(const char* fmt, va_list ap) {
779 std::string error;
780 StringAppendV(&error, fmt, ap);
781 LOG(ERROR) << error;
782}
783
784static void UsageError(const char* fmt, ...) {
785 va_list ap;
786 va_start(ap, fmt);
787 UsageErrorV(fmt, ap);
788 va_end(ap);
789}
790
791static void Usage(const char *fmt, ...) {
792 va_list ap;
793 va_start(ap, fmt);
794 UsageErrorV(fmt, ap);
795 va_end(ap);
796
797 UsageError("Command: %s", CommandLine().c_str());
798 UsageError("Usage: patchoat [options]...");
799 UsageError("");
800 UsageError(" --instruction-set=<isa>: Specifies the instruction set the patched code is");
801 UsageError(" compiled for. Required if you use --input-oat-location");
802 UsageError("");
803 UsageError(" --input-oat-file=<file.oat>: Specifies the exact filename of the oat file to be");
804 UsageError(" patched.");
805 UsageError("");
806 UsageError(" --input-oat-fd=<file-descriptor>: Specifies the file-descriptor of the oat file");
807 UsageError(" to be patched.");
808 UsageError("");
809 UsageError(" --input-oat-location=<file.oat>: Specifies the 'location' to read the patched");
810 UsageError(" oat file from. If used one must also supply the --instruction-set");
811 UsageError("");
812 UsageError(" --input-image-location=<file.art>: Specifies the 'location' of the image file to");
813 UsageError(" be patched. If --instruction-set is not given it will use the instruction set");
814 UsageError(" extracted from the --input-oat-file.");
815 UsageError("");
816 UsageError(" --output-oat-file=<file.oat>: Specifies the exact file to write the patched oat");
817 UsageError(" file to.");
818 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700819 UsageError(" --output-oat-fd=<file-descriptor>: Specifies the file-descriptor to write the");
820 UsageError(" the patched oat file to.");
821 UsageError("");
822 UsageError(" --output-image-file=<file.art>: Specifies the exact file to write the patched");
823 UsageError(" image file to.");
824 UsageError("");
825 UsageError(" --output-image-fd=<file-descriptor>: Specifies the file-descriptor to write the");
826 UsageError(" the patched image file to.");
827 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700828 UsageError(" --orig-base-offset=<original-base-offset>: Specify the base offset the input file");
829 UsageError(" was compiled with. This is needed if one is specifying a --base-offset");
830 UsageError("");
831 UsageError(" --base-offset=<new-base-offset>: Specify the base offset we will repatch the");
832 UsageError(" given files to use. This requires that --orig-base-offset is also given.");
833 UsageError("");
834 UsageError(" --base-offset-delta=<delta>: Specify the amount to change the old base-offset by.");
835 UsageError(" This value may be negative.");
836 UsageError("");
837 UsageError(" --patched-image-file=<file.art>: Use the same patch delta as was used to patch");
838 UsageError(" the given image file.");
839 UsageError("");
840 UsageError(" --patched-image-location=<file.art>: Use the same patch delta as was used to");
841 UsageError(" patch the given image location. If used one must also specify the");
Alex Lighta59dd802014-07-02 16:28:08 -0700842 UsageError(" --instruction-set flag. It will search for this image in the same way that");
843 UsageError(" is done when loading one.");
Alex Light53cb16b2014-06-12 11:26:29 -0700844 UsageError("");
Alex Lightcf4bf382014-07-24 11:29:14 -0700845 UsageError(" --lock-output: Obtain a flock on output oat file before starting.");
846 UsageError("");
847 UsageError(" --no-lock-output: Do not attempt to obtain a flock on output oat file.");
848 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700849 UsageError(" --dump-timings: dump out patch timing information");
850 UsageError("");
851 UsageError(" --no-dump-timings: do not dump out patch timing information");
852 UsageError("");
853
854 exit(EXIT_FAILURE);
855}
856
Alex Lighteefbe392014-07-08 09:53:18 -0700857static bool ReadBaseDelta(const char* name, off_t* delta, std::string* error_msg) {
Alex Light53cb16b2014-06-12 11:26:29 -0700858 CHECK(name != nullptr);
859 CHECK(delta != nullptr);
860 std::unique_ptr<File> file;
861 if (OS::FileExists(name)) {
862 file.reset(OS::OpenFileForReading(name));
863 if (file.get() == nullptr) {
Alex Lighteefbe392014-07-08 09:53:18 -0700864 *error_msg = "Failed to open file %s for reading";
Alex Light53cb16b2014-06-12 11:26:29 -0700865 return false;
866 }
867 } else {
Alex Lighteefbe392014-07-08 09:53:18 -0700868 *error_msg = "File %s does not exist";
Alex Light53cb16b2014-06-12 11:26:29 -0700869 return false;
870 }
871 CHECK(file.get() != nullptr);
872 ImageHeader hdr;
873 if (sizeof(hdr) != file->Read(reinterpret_cast<char*>(&hdr), sizeof(hdr), 0)) {
Alex Lighteefbe392014-07-08 09:53:18 -0700874 *error_msg = "Failed to read file %s";
Alex Light53cb16b2014-06-12 11:26:29 -0700875 return false;
876 }
877 if (!hdr.IsValid()) {
Alex Lighteefbe392014-07-08 09:53:18 -0700878 *error_msg = "%s does not contain a valid image header.";
Alex Light53cb16b2014-06-12 11:26:29 -0700879 return false;
880 }
881 *delta = hdr.GetPatchDelta();
882 return true;
883}
884
885static File* CreateOrOpen(const char* name, bool* created) {
886 if (OS::FileExists(name)) {
887 *created = false;
888 return OS::OpenFileReadWrite(name);
889 } else {
890 *created = true;
Alex Lightcf4bf382014-07-24 11:29:14 -0700891 std::unique_ptr<File> f(OS::CreateEmptyFile(name));
892 if (f.get() != nullptr) {
893 if (fchmod(f->Fd(), 0644) != 0) {
894 PLOG(ERROR) << "Unable to make " << name << " world readable";
895 unlink(name);
896 return nullptr;
897 }
898 }
899 return f.release();
Alex Light53cb16b2014-06-12 11:26:29 -0700900 }
901}
902
Alex Lighteefbe392014-07-08 09:53:18 -0700903static int patchoat(int argc, char **argv) {
Alex Light53cb16b2014-06-12 11:26:29 -0700904 InitLogging(argv);
Mathieu Chartierc54e12a2014-10-14 16:22:41 -0700905 MemMap::Init();
Alex Light53cb16b2014-06-12 11:26:29 -0700906 const bool debug = kIsDebugBuild;
907 orig_argc = argc;
908 orig_argv = argv;
909 TimingLogger timings("patcher", false, false);
910
911 InitLogging(argv);
912
913 // Skip over the command name.
914 argv++;
915 argc--;
916
917 if (argc == 0) {
918 Usage("No arguments specified");
919 }
920
921 timings.StartTiming("Patchoat");
922
923 // cmd line args
924 bool isa_set = false;
925 InstructionSet isa = kNone;
926 std::string input_oat_filename;
927 std::string input_oat_location;
928 int input_oat_fd = -1;
929 bool have_input_oat = false;
930 std::string input_image_location;
931 std::string output_oat_filename;
Alex Light53cb16b2014-06-12 11:26:29 -0700932 int output_oat_fd = -1;
933 bool have_output_oat = false;
934 std::string output_image_filename;
Alex Light53cb16b2014-06-12 11:26:29 -0700935 int output_image_fd = -1;
936 bool have_output_image = false;
937 uintptr_t base_offset = 0;
938 bool base_offset_set = false;
939 uintptr_t orig_base_offset = 0;
940 bool orig_base_offset_set = false;
941 off_t base_delta = 0;
942 bool base_delta_set = false;
943 std::string patched_image_filename;
944 std::string patched_image_location;
945 bool dump_timings = kIsDebugBuild;
Alex Lightcf4bf382014-07-24 11:29:14 -0700946 bool lock_output = true;
Alex Light53cb16b2014-06-12 11:26:29 -0700947
948 for (int i = 0; i < argc; i++) {
949 const StringPiece option(argv[i]);
950 const bool log_options = false;
951 if (log_options) {
952 LOG(INFO) << "patchoat: option[" << i << "]=" << argv[i];
953 }
Alex Light53cb16b2014-06-12 11:26:29 -0700954 if (option.starts_with("--instruction-set=")) {
955 isa_set = true;
956 const char* isa_str = option.substr(strlen("--instruction-set=")).data();
Andreas Gampeaabbb202014-08-19 17:28:06 -0700957 isa = GetInstructionSetFromString(isa_str);
958 if (isa == kNone) {
959 Usage("Unknown or invalid instruction set %s", isa_str);
Alex Light53cb16b2014-06-12 11:26:29 -0700960 }
961 } else if (option.starts_with("--input-oat-location=")) {
962 if (have_input_oat) {
963 Usage("Only one of --input-oat-file, --input-oat-location and --input-oat-fd may be used.");
964 }
965 have_input_oat = true;
966 input_oat_location = option.substr(strlen("--input-oat-location=")).data();
967 } else if (option.starts_with("--input-oat-file=")) {
968 if (have_input_oat) {
969 Usage("Only one of --input-oat-file, --input-oat-location and --input-oat-fd may be used.");
970 }
971 have_input_oat = true;
972 input_oat_filename = option.substr(strlen("--input-oat-file=")).data();
973 } else if (option.starts_with("--input-oat-fd=")) {
974 if (have_input_oat) {
975 Usage("Only one of --input-oat-file, --input-oat-location and --input-oat-fd may be used.");
976 }
977 have_input_oat = true;
978 const char* oat_fd_str = option.substr(strlen("--input-oat-fd=")).data();
979 if (!ParseInt(oat_fd_str, &input_oat_fd)) {
980 Usage("Failed to parse --input-oat-fd argument '%s' as an integer", oat_fd_str);
981 }
982 if (input_oat_fd < 0) {
983 Usage("--input-oat-fd pass a negative value %d", input_oat_fd);
984 }
985 } else if (option.starts_with("--input-image-location=")) {
986 input_image_location = option.substr(strlen("--input-image-location=")).data();
Alex Light53cb16b2014-06-12 11:26:29 -0700987 } else if (option.starts_with("--output-oat-file=")) {
988 if (have_output_oat) {
Alex Lightcf4bf382014-07-24 11:29:14 -0700989 Usage("Only one of --output-oat-file, and --output-oat-fd may be used.");
Alex Light53cb16b2014-06-12 11:26:29 -0700990 }
991 have_output_oat = true;
992 output_oat_filename = option.substr(strlen("--output-oat-file=")).data();
993 } else if (option.starts_with("--output-oat-fd=")) {
994 if (have_output_oat) {
Alex Lightcf4bf382014-07-24 11:29:14 -0700995 Usage("Only one of --output-oat-file, --output-oat-fd may be used.");
Alex Light53cb16b2014-06-12 11:26:29 -0700996 }
997 have_output_oat = true;
998 const char* oat_fd_str = option.substr(strlen("--output-oat-fd=")).data();
999 if (!ParseInt(oat_fd_str, &output_oat_fd)) {
1000 Usage("Failed to parse --output-oat-fd argument '%s' as an integer", oat_fd_str);
1001 }
1002 if (output_oat_fd < 0) {
1003 Usage("--output-oat-fd pass a negative value %d", output_oat_fd);
1004 }
Alex Light53cb16b2014-06-12 11:26:29 -07001005 } else if (option.starts_with("--output-image-file=")) {
1006 if (have_output_image) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001007 Usage("Only one of --output-image-file, and --output-image-fd may be used.");
Alex Light53cb16b2014-06-12 11:26:29 -07001008 }
1009 have_output_image = true;
1010 output_image_filename = option.substr(strlen("--output-image-file=")).data();
1011 } else if (option.starts_with("--output-image-fd=")) {
1012 if (have_output_image) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001013 Usage("Only one of --output-image-file, and --output-image-fd may be used.");
Alex Light53cb16b2014-06-12 11:26:29 -07001014 }
1015 have_output_image = true;
1016 const char* image_fd_str = option.substr(strlen("--output-image-fd=")).data();
1017 if (!ParseInt(image_fd_str, &output_image_fd)) {
1018 Usage("Failed to parse --output-image-fd argument '%s' as an integer", image_fd_str);
1019 }
1020 if (output_image_fd < 0) {
1021 Usage("--output-image-fd pass a negative value %d", output_image_fd);
1022 }
1023 } else if (option.starts_with("--orig-base-offset=")) {
1024 const char* orig_base_offset_str = option.substr(strlen("--orig-base-offset=")).data();
1025 orig_base_offset_set = true;
1026 if (!ParseUint(orig_base_offset_str, &orig_base_offset)) {
1027 Usage("Failed to parse --orig-base-offset argument '%s' as an uintptr_t",
1028 orig_base_offset_str);
1029 }
1030 } else if (option.starts_with("--base-offset=")) {
1031 const char* base_offset_str = option.substr(strlen("--base-offset=")).data();
1032 base_offset_set = true;
1033 if (!ParseUint(base_offset_str, &base_offset)) {
1034 Usage("Failed to parse --base-offset argument '%s' as an uintptr_t", base_offset_str);
1035 }
1036 } else if (option.starts_with("--base-offset-delta=")) {
1037 const char* base_delta_str = option.substr(strlen("--base-offset-delta=")).data();
1038 base_delta_set = true;
1039 if (!ParseInt(base_delta_str, &base_delta)) {
1040 Usage("Failed to parse --base-offset-delta argument '%s' as an off_t", base_delta_str);
1041 }
1042 } else if (option.starts_with("--patched-image-location=")) {
1043 patched_image_location = option.substr(strlen("--patched-image-location=")).data();
1044 } else if (option.starts_with("--patched-image-file=")) {
1045 patched_image_filename = option.substr(strlen("--patched-image-file=")).data();
Alex Lightcf4bf382014-07-24 11:29:14 -07001046 } else if (option == "--lock-output") {
1047 lock_output = true;
1048 } else if (option == "--no-lock-output") {
1049 lock_output = false;
Alex Light53cb16b2014-06-12 11:26:29 -07001050 } else if (option == "--dump-timings") {
1051 dump_timings = true;
1052 } else if (option == "--no-dump-timings") {
1053 dump_timings = false;
1054 } else {
1055 Usage("Unknown argument %s", option.data());
1056 }
1057 }
1058
1059 {
1060 // Only 1 of these may be set.
1061 uint32_t cnt = 0;
1062 cnt += (base_delta_set) ? 1 : 0;
1063 cnt += (base_offset_set && orig_base_offset_set) ? 1 : 0;
1064 cnt += (!patched_image_filename.empty()) ? 1 : 0;
1065 cnt += (!patched_image_location.empty()) ? 1 : 0;
1066 if (cnt > 1) {
1067 Usage("Only one of --base-offset/--orig-base-offset, --base-offset-delta, "
1068 "--patched-image-filename or --patched-image-location may be used.");
1069 } else if (cnt == 0) {
1070 Usage("Must specify --base-offset-delta, --base-offset and --orig-base-offset, "
1071 "--patched-image-location or --patched-image-file");
1072 }
1073 }
1074
1075 if (have_input_oat != have_output_oat) {
1076 Usage("Either both input and output oat must be supplied or niether must be.");
1077 }
1078
1079 if ((!input_image_location.empty()) != have_output_image) {
1080 Usage("Either both input and output image must be supplied or niether must be.");
1081 }
1082
1083 // We know we have both the input and output so rename for clarity.
1084 bool have_image_files = have_output_image;
1085 bool have_oat_files = have_output_oat;
1086
1087 if (!have_oat_files && !have_image_files) {
1088 Usage("Must be patching either an oat or an image file or both.");
1089 }
1090
1091 if (!have_oat_files && !isa_set) {
1092 Usage("Must include ISA if patching an image file without an oat file.");
1093 }
1094
1095 if (!input_oat_location.empty()) {
1096 if (!isa_set) {
1097 Usage("specifying a location requires specifying an instruction set");
1098 }
Alex Lightcf4bf382014-07-24 11:29:14 -07001099 if (!LocationToFilename(input_oat_location, isa, &input_oat_filename)) {
1100 Usage("Unable to find filename for input oat location %s", input_oat_location.c_str());
1101 }
Alex Light53cb16b2014-06-12 11:26:29 -07001102 if (debug) {
1103 LOG(INFO) << "Using input-oat-file " << input_oat_filename;
1104 }
1105 }
Alex Light53cb16b2014-06-12 11:26:29 -07001106 if (!patched_image_location.empty()) {
1107 if (!isa_set) {
1108 Usage("specifying a location requires specifying an instruction set");
1109 }
Alex Lighta59dd802014-07-02 16:28:08 -07001110 std::string system_filename;
1111 bool has_system = false;
1112 std::string cache_filename;
1113 bool has_cache = false;
1114 bool has_android_data_unused = false;
Andreas Gampe33c36d42014-09-18 20:56:04 -07001115 bool is_global_cache = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001116 if (!gc::space::ImageSpace::FindImageFilename(patched_image_location.c_str(), isa,
1117 &system_filename, &has_system, &cache_filename,
Andreas Gampe33c36d42014-09-18 20:56:04 -07001118 &has_android_data_unused, &has_cache,
1119 &is_global_cache)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001120 Usage("Unable to determine image file for location %s", patched_image_location.c_str());
1121 }
1122 if (has_cache) {
1123 patched_image_filename = cache_filename;
1124 } else if (has_system) {
1125 LOG(WARNING) << "Only image file found was in /system for image location "
1126 << patched_image_location;
1127 patched_image_filename = system_filename;
1128 } else {
1129 Usage("Unable to determine image file for location %s", patched_image_location.c_str());
1130 }
Alex Light53cb16b2014-06-12 11:26:29 -07001131 if (debug) {
1132 LOG(INFO) << "Using patched-image-file " << patched_image_filename;
1133 }
1134 }
1135
1136 if (!base_delta_set) {
1137 if (orig_base_offset_set && base_offset_set) {
1138 base_delta_set = true;
1139 base_delta = base_offset - orig_base_offset;
1140 } else if (!patched_image_filename.empty()) {
1141 base_delta_set = true;
1142 std::string error_msg;
Alex Lighteefbe392014-07-08 09:53:18 -07001143 if (!ReadBaseDelta(patched_image_filename.c_str(), &base_delta, &error_msg)) {
Alex Light53cb16b2014-06-12 11:26:29 -07001144 Usage(error_msg.c_str(), patched_image_filename.c_str());
1145 }
1146 } else {
1147 if (base_offset_set) {
1148 Usage("Unable to determine original base offset.");
1149 } else {
1150 Usage("Must supply a desired new offset or delta.");
1151 }
1152 }
1153 }
1154
1155 if (!IsAligned<kPageSize>(base_delta)) {
1156 Usage("Base offset/delta must be alligned to a pagesize (0x%08x) boundary.", kPageSize);
1157 }
1158
1159 // Do we need to cleanup output files if we fail?
1160 bool new_image_out = false;
1161 bool new_oat_out = false;
1162
1163 std::unique_ptr<File> input_oat;
1164 std::unique_ptr<File> output_oat;
1165 std::unique_ptr<File> output_image;
1166
1167 if (have_image_files) {
1168 CHECK(!input_image_location.empty());
1169
1170 if (output_image_fd != -1) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001171 if (output_image_filename.empty()) {
1172 output_image_filename = "output-image-file";
1173 }
Alex Light53cb16b2014-06-12 11:26:29 -07001174 output_image.reset(new File(output_image_fd, output_image_filename));
1175 } else {
1176 CHECK(!output_image_filename.empty());
1177 output_image.reset(CreateOrOpen(output_image_filename.c_str(), &new_image_out));
1178 }
1179 } else {
1180 CHECK(output_image_filename.empty() && output_image_fd == -1 && input_image_location.empty());
1181 }
1182
1183 if (have_oat_files) {
1184 if (input_oat_fd != -1) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001185 if (input_oat_filename.empty()) {
1186 input_oat_filename = "input-oat-file";
1187 }
Alex Light53cb16b2014-06-12 11:26:29 -07001188 input_oat.reset(new File(input_oat_fd, input_oat_filename));
Igor Murashkin90ca5c02014-10-22 11:37:02 -07001189 if (input_oat == nullptr) {
1190 // Unlikely, but ensure exhaustive logging in non-0 exit code case
1191 LOG(ERROR) << "Failed to open input oat file by its FD" << input_oat_fd;
1192 }
Alex Light53cb16b2014-06-12 11:26:29 -07001193 } else {
1194 CHECK(!input_oat_filename.empty());
1195 input_oat.reset(OS::OpenFileForReading(input_oat_filename.c_str()));
Igor Murashkin90ca5c02014-10-22 11:37:02 -07001196 if (input_oat == nullptr) {
1197 int err = errno;
1198 LOG(ERROR) << "Failed to open input oat file " << input_oat_filename
1199 << ": " << strerror(err) << "(" << err << ")";
Andreas Gampe1c83cbc2014-07-22 18:52:29 -07001200 }
Alex Light53cb16b2014-06-12 11:26:29 -07001201 }
1202
1203 if (output_oat_fd != -1) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001204 if (output_oat_filename.empty()) {
1205 output_oat_filename = "output-oat-file";
Alex Lighta59dd802014-07-02 16:28:08 -07001206 }
Alex Lightcf4bf382014-07-24 11:29:14 -07001207 output_oat.reset(new File(output_oat_fd, output_oat_filename));
Igor Murashkin90ca5c02014-10-22 11:37:02 -07001208 if (output_oat == nullptr) {
1209 // Unlikely, but ensure exhaustive logging in non-0 exit code case
1210 LOG(ERROR) << "Failed to open output oat file by its FD" << output_oat_fd;
1211 }
Alex Light53cb16b2014-06-12 11:26:29 -07001212 } else {
1213 CHECK(!output_oat_filename.empty());
1214 output_oat.reset(CreateOrOpen(output_oat_filename.c_str(), &new_oat_out));
Igor Murashkin90ca5c02014-10-22 11:37:02 -07001215 if (output_oat == nullptr) {
1216 int err = errno;
1217 LOG(ERROR) << "Failed to open output oat file " << output_oat_filename
1218 << ": " << strerror(err) << "(" << err << ")";
1219 }
Alex Light53cb16b2014-06-12 11:26:29 -07001220 }
1221 }
1222
Igor Murashkin90ca5c02014-10-22 11:37:02 -07001223 // TODO: get rid of this.
Alex Light53cb16b2014-06-12 11:26:29 -07001224 auto cleanup = [&output_image_filename, &output_oat_filename,
1225 &new_oat_out, &new_image_out, &timings, &dump_timings](bool success) {
1226 timings.EndTiming();
1227 if (!success) {
1228 if (new_oat_out) {
1229 CHECK(!output_oat_filename.empty());
1230 unlink(output_oat_filename.c_str());
1231 }
1232 if (new_image_out) {
1233 CHECK(!output_image_filename.empty());
1234 unlink(output_image_filename.c_str());
1235 }
1236 }
1237 if (dump_timings) {
1238 LOG(INFO) << Dumpable<TimingLogger>(timings);
1239 }
Igor Murashkin90ca5c02014-10-22 11:37:02 -07001240
1241 if (kIsDebugBuild) {
1242 LOG(INFO) << "Cleaning up.. success? " << success;
1243 }
Alex Light53cb16b2014-06-12 11:26:29 -07001244 };
1245
Igor Murashkin90ca5c02014-10-22 11:37:02 -07001246 if (have_oat_files && (input_oat.get() == nullptr || output_oat.get() == nullptr)) {
1247 LOG(ERROR) << "Failed to open input/output oat files";
1248 cleanup(false);
1249 return EXIT_FAILURE;
1250 } else if (have_image_files && output_image.get() == nullptr) {
1251 LOG(ERROR) << "Failed to open output image file";
Alex Lightcf4bf382014-07-24 11:29:14 -07001252 cleanup(false);
1253 return EXIT_FAILURE;
1254 }
1255
Igor Murashkin90ca5c02014-10-22 11:37:02 -07001256 if (debug) {
1257 LOG(INFO) << "moving offset by " << base_delta
1258 << " (0x" << std::hex << base_delta << ") bytes or "
1259 << std::dec << (base_delta/kPageSize) << " pages.";
1260 }
1261
1262 // TODO: is it going to be promatic to unlink a file that was flock-ed?
Alex Lightcf4bf382014-07-24 11:29:14 -07001263 ScopedFlock output_oat_lock;
1264 if (lock_output) {
1265 std::string error_msg;
1266 if (have_oat_files && !output_oat_lock.Init(output_oat.get(), &error_msg)) {
1267 LOG(ERROR) << "Unable to lock output oat " << output_image->GetPath() << ": " << error_msg;
1268 cleanup(false);
1269 return EXIT_FAILURE;
1270 }
1271 }
1272
Alex Light53cb16b2014-06-12 11:26:29 -07001273 bool ret;
1274 if (have_image_files && have_oat_files) {
1275 TimingLogger::ScopedTiming pt("patch image and oat", &timings);
1276 ret = PatchOat::Patch(input_oat.get(), input_image_location, base_delta,
Igor Murashkin90ca5c02014-10-22 11:37:02 -07001277 output_oat.get(), output_image.get(), isa, &timings,
1278 output_oat_fd >= 0, // was it opened from FD?
1279 new_oat_out);
Alex Light53cb16b2014-06-12 11:26:29 -07001280 } else if (have_oat_files) {
1281 TimingLogger::ScopedTiming pt("patch oat", &timings);
Igor Murashkin90ca5c02014-10-22 11:37:02 -07001282 ret = PatchOat::Patch(input_oat.get(), base_delta, output_oat.get(), &timings,
1283 output_oat_fd >= 0, // was it opened from FD?
1284 new_oat_out);
1285 } else if (have_image_files) {
Alex Light53cb16b2014-06-12 11:26:29 -07001286 TimingLogger::ScopedTiming pt("patch image", &timings);
Alex Lighteefbe392014-07-08 09:53:18 -07001287 ret = PatchOat::Patch(input_image_location, base_delta, output_image.get(), isa, &timings);
Igor Murashkin90ca5c02014-10-22 11:37:02 -07001288 } else {
1289 CHECK(false);
1290 ret = true;
1291 }
1292
1293 if (kIsDebugBuild) {
1294 LOG(INFO) << "Exiting with return ... " << ret;
Alex Light53cb16b2014-06-12 11:26:29 -07001295 }
1296 cleanup(ret);
Alex Light53cb16b2014-06-12 11:26:29 -07001297 return (ret) ? EXIT_SUCCESS : EXIT_FAILURE;
1298}
1299
1300} // namespace art
1301
1302int main(int argc, char **argv) {
1303 return art::patchoat(argc, argv);
1304}