blob: 281649e0710912116da64d989b78745011624269 [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
Ian Rogersc7dd2952014-10-21 23:31:19 -070027#include "base/dumpable.h"
Alex Lighta59dd802014-07-02 16:28:08 -070028#include "base/scoped_flock.h"
Alex Light53cb16b2014-06-12 11:26:29 -070029#include "base/stringpiece.h"
30#include "base/stringprintf.h"
Ian Rogersd4c4d952014-10-16 20:31:53 -070031#include "base/unix_file/fd_file.h"
Alex Light53cb16b2014-06-12 11:26:29 -070032#include "elf_utils.h"
33#include "elf_file.h"
Tong Shen62d1ca32014-09-03 17:24:56 -070034#include "elf_file_impl.h"
Ian Rogerse63db272014-07-15 15:36:11 -070035#include "gc/space/image_space.h"
Alex Light53cb16b2014-06-12 11:26:29 -070036#include "image.h"
Alex Light53cb16b2014-06-12 11:26:29 -070037#include "mirror/art_field-inl.h"
Alex Light53cb16b2014-06-12 11:26:29 -070038#include "mirror/art_method-inl.h"
Alex Light53cb16b2014-06-12 11:26:29 -070039#include "mirror/object-inl.h"
40#include "mirror/reference.h"
41#include "noop_compiler_callbacks.h"
42#include "offsets.h"
43#include "os.h"
44#include "runtime.h"
45#include "scoped_thread_state_change.h"
46#include "thread.h"
47#include "utils.h"
48
49namespace art {
50
51static InstructionSet ElfISAToInstructionSet(Elf32_Word isa) {
52 switch (isa) {
53 case EM_ARM:
54 return kArm;
55 case EM_AARCH64:
56 return kArm64;
57 case EM_386:
58 return kX86;
59 case EM_X86_64:
60 return kX86_64;
61 case EM_MIPS:
62 return kMips;
63 default:
64 return kNone;
65 }
66}
67
Alex Lightcf4bf382014-07-24 11:29:14 -070068static bool LocationToFilename(const std::string& location, InstructionSet isa,
69 std::string* filename) {
70 bool has_system = false;
71 bool has_cache = false;
72 // image_location = /system/framework/boot.art
Igor Murashkin46774762014-10-22 11:37:02 -070073 // system_image_filename = /system/framework/<image_isa>/boot.art
Alex Lightcf4bf382014-07-24 11:29:14 -070074 std::string system_filename(GetSystemImageFilename(location.c_str(), isa));
75 if (OS::FileExists(system_filename.c_str())) {
76 has_system = true;
77 }
78
79 bool have_android_data = false;
80 bool dalvik_cache_exists = false;
Andreas Gampe3c13a792014-09-18 20:56:04 -070081 bool is_global_cache = false;
Alex Lightcf4bf382014-07-24 11:29:14 -070082 std::string dalvik_cache;
83 GetDalvikCache(GetInstructionSetString(isa), false, &dalvik_cache,
Andreas Gampe3c13a792014-09-18 20:56:04 -070084 &have_android_data, &dalvik_cache_exists, &is_global_cache);
Alex Lightcf4bf382014-07-24 11:29:14 -070085
86 std::string cache_filename;
87 if (have_android_data && dalvik_cache_exists) {
88 // Always set output location even if it does not exist,
89 // so that the caller knows where to create the image.
90 //
91 // image_location = /system/framework/boot.art
92 // *image_filename = /data/dalvik-cache/<image_isa>/boot.art
93 std::string error_msg;
94 if (GetDalvikCacheFilename(location.c_str(), dalvik_cache.c_str(),
95 &cache_filename, &error_msg)) {
96 has_cache = true;
97 }
98 }
99 if (has_system) {
100 *filename = system_filename;
101 return true;
102 } else if (has_cache) {
103 *filename = cache_filename;
104 return true;
105 } else {
106 return false;
107 }
108}
109
Alex Light53cb16b2014-06-12 11:26:29 -0700110bool PatchOat::Patch(const std::string& image_location, off_t delta,
111 File* output_image, InstructionSet isa,
Alex Lighteefbe392014-07-08 09:53:18 -0700112 TimingLogger* timings) {
Alex Light53cb16b2014-06-12 11:26:29 -0700113 CHECK(Runtime::Current() == nullptr);
114 CHECK(output_image != nullptr);
115 CHECK_GE(output_image->Fd(), 0);
116 CHECK(!image_location.empty()) << "image file must have a filename.";
117 CHECK_NE(isa, kNone);
118
Alex Lighteefbe392014-07-08 09:53:18 -0700119 TimingLogger::ScopedTiming t("Runtime Setup", timings);
Alex Light53cb16b2014-06-12 11:26:29 -0700120 const char *isa_name = GetInstructionSetString(isa);
Alex Lightcf4bf382014-07-24 11:29:14 -0700121 std::string image_filename;
122 if (!LocationToFilename(image_location, isa, &image_filename)) {
123 LOG(ERROR) << "Unable to find image at location " << image_location;
124 return false;
125 }
Alex Light53cb16b2014-06-12 11:26:29 -0700126 std::unique_ptr<File> input_image(OS::OpenFileForReading(image_filename.c_str()));
127 if (input_image.get() == nullptr) {
Alex Lightcf4bf382014-07-24 11:29:14 -0700128 LOG(ERROR) << "unable to open input image file at " << image_filename
129 << " for location " << image_location;
Alex Light53cb16b2014-06-12 11:26:29 -0700130 return false;
131 }
Igor Murashkin46774762014-10-22 11:37:02 -0700132
Alex Light53cb16b2014-06-12 11:26:29 -0700133 int64_t image_len = input_image->GetLength();
134 if (image_len < 0) {
135 LOG(ERROR) << "Error while getting image length";
136 return false;
137 }
138 ImageHeader image_header;
139 if (sizeof(image_header) != input_image->Read(reinterpret_cast<char*>(&image_header),
140 sizeof(image_header), 0)) {
141 LOG(ERROR) << "Unable to read image header from image file " << input_image->GetPath();
142 return false;
143 }
144
Igor Murashkin46774762014-10-22 11:37:02 -0700145 /*bool is_image_pic = */IsImagePic(image_header, input_image->GetPath());
146 // Nothing special to do right now since the image always needs to get patched.
147 // Perhaps in some far-off future we may have images with relative addresses that are true-PIC.
148
Alex Light53cb16b2014-06-12 11:26:29 -0700149 // Set up the runtime
Ian Rogerse63db272014-07-15 15:36:11 -0700150 RuntimeOptions options;
Alex Light53cb16b2014-06-12 11:26:29 -0700151 NoopCompilerCallbacks callbacks;
152 options.push_back(std::make_pair("compilercallbacks", &callbacks));
153 std::string img = "-Ximage:" + image_location;
154 options.push_back(std::make_pair(img.c_str(), nullptr));
155 options.push_back(std::make_pair("imageinstructionset", reinterpret_cast<const void*>(isa_name)));
156 if (!Runtime::Create(options, false)) {
157 LOG(ERROR) << "Unable to initialize runtime";
158 return false;
159 }
160 // Runtime::Create acquired the mutator_lock_ that is normally given away when we Runtime::Start,
161 // give it away now and then switch to a more manageable ScopedObjectAccess.
162 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
163 ScopedObjectAccess soa(Thread::Current());
164
165 t.NewTiming("Image and oat Patching setup");
166 // Create the map where we will write the image patches to.
Alex Lighteefbe392014-07-08 09:53:18 -0700167 std::string error_msg;
Alex Light53cb16b2014-06-12 11:26:29 -0700168 std::unique_ptr<MemMap> image(MemMap::MapFile(image_len, PROT_READ | PROT_WRITE, MAP_PRIVATE,
169 input_image->Fd(), 0,
170 input_image->GetPath().c_str(),
171 &error_msg));
172 if (image.get() == nullptr) {
173 LOG(ERROR) << "unable to map image file " << input_image->GetPath() << " : " << error_msg;
174 return false;
175 }
176 gc::space::ImageSpace* ispc = Runtime::Current()->GetHeap()->GetImageSpace();
177
Mathieu Chartier2d721012014-11-10 11:08:06 -0800178 PatchOat p(isa, image.release(), ispc->GetLiveBitmap(), ispc->GetMemMap(),
Alex Light53cb16b2014-06-12 11:26:29 -0700179 delta, timings);
180 t.NewTiming("Patching files");
181 if (!p.PatchImage()) {
Alex Lighta59dd802014-07-02 16:28:08 -0700182 LOG(ERROR) << "Failed to patch image file " << input_image->GetPath();
Alex Light53cb16b2014-06-12 11:26:29 -0700183 return false;
184 }
185
186 t.NewTiming("Writing files");
187 if (!p.WriteImage(output_image)) {
188 return false;
189 }
190 return true;
191}
192
Igor Murashkin46774762014-10-22 11:37:02 -0700193bool PatchOat::Patch(File* input_oat, const std::string& image_location, off_t delta,
Alex Light53cb16b2014-06-12 11:26:29 -0700194 File* output_oat, File* output_image, InstructionSet isa,
Igor Murashkin46774762014-10-22 11:37:02 -0700195 TimingLogger* timings,
196 bool output_oat_opened_from_fd,
197 bool new_oat_out) {
Alex Light53cb16b2014-06-12 11:26:29 -0700198 CHECK(Runtime::Current() == nullptr);
199 CHECK(output_image != nullptr);
200 CHECK_GE(output_image->Fd(), 0);
201 CHECK(input_oat != nullptr);
202 CHECK(output_oat != nullptr);
203 CHECK_GE(input_oat->Fd(), 0);
204 CHECK_GE(output_oat->Fd(), 0);
205 CHECK(!image_location.empty()) << "image file must have a filename.";
206
Alex Lighteefbe392014-07-08 09:53:18 -0700207 TimingLogger::ScopedTiming t("Runtime Setup", timings);
Alex Light53cb16b2014-06-12 11:26:29 -0700208
209 if (isa == kNone) {
210 Elf32_Ehdr elf_hdr;
211 if (sizeof(elf_hdr) != input_oat->Read(reinterpret_cast<char*>(&elf_hdr), sizeof(elf_hdr), 0)) {
212 LOG(ERROR) << "unable to read elf header";
213 return false;
214 }
215 isa = ElfISAToInstructionSet(elf_hdr.e_machine);
216 }
217 const char* isa_name = GetInstructionSetString(isa);
Alex Lightcf4bf382014-07-24 11:29:14 -0700218 std::string image_filename;
219 if (!LocationToFilename(image_location, isa, &image_filename)) {
220 LOG(ERROR) << "Unable to find image at location " << image_location;
221 return false;
222 }
Alex Light53cb16b2014-06-12 11:26:29 -0700223 std::unique_ptr<File> input_image(OS::OpenFileForReading(image_filename.c_str()));
224 if (input_image.get() == nullptr) {
Alex Lightcf4bf382014-07-24 11:29:14 -0700225 LOG(ERROR) << "unable to open input image file at " << image_filename
226 << " for location " << image_location;
Alex Light53cb16b2014-06-12 11:26:29 -0700227 return false;
228 }
229 int64_t image_len = input_image->GetLength();
230 if (image_len < 0) {
231 LOG(ERROR) << "Error while getting image length";
232 return false;
233 }
234 ImageHeader image_header;
235 if (sizeof(image_header) != input_image->Read(reinterpret_cast<char*>(&image_header),
236 sizeof(image_header), 0)) {
237 LOG(ERROR) << "Unable to read image header from image file " << input_image->GetPath();
238 }
239
Igor Murashkin46774762014-10-22 11:37:02 -0700240 /*bool is_image_pic = */IsImagePic(image_header, input_image->GetPath());
241 // Nothing special to do right now since the image always needs to get patched.
242 // Perhaps in some far-off future we may have images with relative addresses that are true-PIC.
243
Alex Light53cb16b2014-06-12 11:26:29 -0700244 // Set up the runtime
Ian Rogerse63db272014-07-15 15:36:11 -0700245 RuntimeOptions options;
Alex Light53cb16b2014-06-12 11:26:29 -0700246 NoopCompilerCallbacks callbacks;
247 options.push_back(std::make_pair("compilercallbacks", &callbacks));
248 std::string img = "-Ximage:" + image_location;
249 options.push_back(std::make_pair(img.c_str(), nullptr));
250 options.push_back(std::make_pair("imageinstructionset", reinterpret_cast<const void*>(isa_name)));
251 if (!Runtime::Create(options, false)) {
252 LOG(ERROR) << "Unable to initialize runtime";
253 return false;
254 }
255 // Runtime::Create acquired the mutator_lock_ that is normally given away when we Runtime::Start,
256 // give it away now and then switch to a more manageable ScopedObjectAccess.
257 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
258 ScopedObjectAccess soa(Thread::Current());
259
260 t.NewTiming("Image and oat Patching setup");
261 // Create the map where we will write the image patches to.
Alex Lighteefbe392014-07-08 09:53:18 -0700262 std::string error_msg;
Alex Light53cb16b2014-06-12 11:26:29 -0700263 std::unique_ptr<MemMap> image(MemMap::MapFile(image_len, PROT_READ | PROT_WRITE, MAP_PRIVATE,
264 input_image->Fd(), 0,
265 input_image->GetPath().c_str(),
266 &error_msg));
267 if (image.get() == nullptr) {
268 LOG(ERROR) << "unable to map image file " << input_image->GetPath() << " : " << error_msg;
269 return false;
270 }
271 gc::space::ImageSpace* ispc = Runtime::Current()->GetHeap()->GetImageSpace();
272
Igor Murashkin46774762014-10-22 11:37:02 -0700273 std::unique_ptr<ElfFile> elf(ElfFile::Open(input_oat,
Alex Light53cb16b2014-06-12 11:26:29 -0700274 PROT_READ | PROT_WRITE, MAP_PRIVATE, &error_msg));
275 if (elf.get() == nullptr) {
276 LOG(ERROR) << "unable to open oat file " << input_oat->GetPath() << " : " << error_msg;
277 return false;
278 }
279
Igor Murashkin46774762014-10-22 11:37:02 -0700280 bool skip_patching_oat = false;
281 MaybePic is_oat_pic = IsOatPic(elf.get());
282 if (is_oat_pic >= ERROR_FIRST) {
283 // Error logged by IsOatPic
284 return false;
285 } else if (is_oat_pic == PIC) {
286 // Do not need to do ELF-file patching. Create a symlink and skip the ELF patching.
287 if (!ReplaceOatFileWithSymlink(input_oat->GetPath(),
288 output_oat->GetPath(),
289 output_oat_opened_from_fd,
290 new_oat_out)) {
291 // Errors already logged by above call.
292 return false;
293 }
294 // Don't patch the OAT, since we just symlinked it. Image still needs patching.
295 skip_patching_oat = true;
296 } else {
297 CHECK(is_oat_pic == NOT_PIC);
298 }
299
Mathieu Chartier2d721012014-11-10 11:08:06 -0800300 PatchOat p(isa, elf.release(), image.release(), ispc->GetLiveBitmap(), ispc->GetMemMap(),
Alex Light53cb16b2014-06-12 11:26:29 -0700301 delta, timings);
302 t.NewTiming("Patching files");
Igor Murashkin46774762014-10-22 11:37:02 -0700303 if (!skip_patching_oat && !p.PatchElf()) {
Alex Lighta59dd802014-07-02 16:28:08 -0700304 LOG(ERROR) << "Failed to patch oat file " << input_oat->GetPath();
Alex Light53cb16b2014-06-12 11:26:29 -0700305 return false;
306 }
307 if (!p.PatchImage()) {
Alex Lighta59dd802014-07-02 16:28:08 -0700308 LOG(ERROR) << "Failed to patch image file " << input_image->GetPath();
Alex Light53cb16b2014-06-12 11:26:29 -0700309 return false;
310 }
311
312 t.NewTiming("Writing files");
Igor Murashkin46774762014-10-22 11:37:02 -0700313 if (!skip_patching_oat && !p.WriteElf(output_oat)) {
314 LOG(ERROR) << "Failed to write oat file " << input_oat->GetPath();
Alex Light53cb16b2014-06-12 11:26:29 -0700315 return false;
316 }
317 if (!p.WriteImage(output_image)) {
Igor Murashkin46774762014-10-22 11:37:02 -0700318 LOG(ERROR) << "Failed to write image file " << input_image->GetPath();
Alex Light53cb16b2014-06-12 11:26:29 -0700319 return false;
320 }
321 return true;
322}
323
324bool PatchOat::WriteElf(File* out) {
Alex Lighteefbe392014-07-08 09:53:18 -0700325 TimingLogger::ScopedTiming t("Writing Elf File", timings_);
Alex Lighta59dd802014-07-02 16:28:08 -0700326
Alex Light53cb16b2014-06-12 11:26:29 -0700327 CHECK(oat_file_.get() != nullptr);
328 CHECK(out != nullptr);
329 size_t expect = oat_file_->Size();
330 if (out->WriteFully(reinterpret_cast<char*>(oat_file_->Begin()), expect) &&
331 out->SetLength(expect) == 0) {
332 return true;
333 } else {
334 LOG(ERROR) << "Writing to oat file " << out->GetPath() << " failed.";
335 return false;
336 }
337}
338
339bool PatchOat::WriteImage(File* out) {
Alex Lighteefbe392014-07-08 09:53:18 -0700340 TimingLogger::ScopedTiming t("Writing image File", timings_);
Alex Lighta59dd802014-07-02 16:28:08 -0700341 std::string error_msg;
342
Alex Lightcf4bf382014-07-24 11:29:14 -0700343 ScopedFlock img_flock;
344 img_flock.Init(out, &error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -0700345
Alex Light53cb16b2014-06-12 11:26:29 -0700346 CHECK(image_ != nullptr);
347 CHECK(out != nullptr);
348 size_t expect = image_->Size();
349 if (out->WriteFully(reinterpret_cast<char*>(image_->Begin()), expect) &&
350 out->SetLength(expect) == 0) {
351 return true;
352 } else {
353 LOG(ERROR) << "Writing to image file " << out->GetPath() << " failed.";
354 return false;
355 }
356}
357
Igor Murashkin46774762014-10-22 11:37:02 -0700358bool PatchOat::IsImagePic(const ImageHeader& image_header, const std::string& image_path) {
359 if (!image_header.CompilePic()) {
360 if (kIsDebugBuild) {
361 LOG(INFO) << "image at location " << image_path << " was *not* compiled pic";
362 }
363 return false;
364 }
365
366 if (kIsDebugBuild) {
367 LOG(INFO) << "image at location " << image_path << " was compiled PIC";
368 }
369
370 return true;
371}
372
373PatchOat::MaybePic PatchOat::IsOatPic(const ElfFile* oat_in) {
374 if (oat_in == nullptr) {
375 LOG(ERROR) << "No ELF input oat fie available";
376 return ERROR_OAT_FILE;
377 }
378
379 const std::string& file_path = oat_in->GetFile().GetPath();
380
381 const OatHeader* oat_header = GetOatHeader(oat_in);
382 if (oat_header == nullptr) {
383 LOG(ERROR) << "Failed to find oat header in oat file " << file_path;
384 return ERROR_OAT_FILE;
385 }
386
387 if (!oat_header->IsValid()) {
388 LOG(ERROR) << "Elf file " << file_path << " has an invalid oat header";
389 return ERROR_OAT_FILE;
390 }
391
392 bool is_pic = oat_header->IsPic();
393 if (kIsDebugBuild) {
394 LOG(INFO) << "Oat file at " << file_path << " is " << (is_pic ? "PIC" : "not pic");
395 }
396
397 return is_pic ? PIC : NOT_PIC;
398}
399
400bool PatchOat::ReplaceOatFileWithSymlink(const std::string& input_oat_filename,
401 const std::string& output_oat_filename,
402 bool output_oat_opened_from_fd,
403 bool new_oat_out) {
404 // Need a file when we are PIC, since we symlink over it. Refusing to symlink into FD.
405 if (output_oat_opened_from_fd) {
406 // TODO: installd uses --output-oat-fd. Should we change class linking logic for PIC?
407 LOG(ERROR) << "No output oat filename specified, needs filename for when we are PIC";
408 return false;
409 }
410
411 // Image was PIC. Create symlink where the oat is supposed to go.
412 if (!new_oat_out) {
413 LOG(ERROR) << "Oat file " << output_oat_filename << " already exists, refusing to overwrite";
414 return false;
415 }
416
417 // Delete the original file, since we won't need it.
418 TEMP_FAILURE_RETRY(unlink(output_oat_filename.c_str()));
419
420 // Create a symlink from the old oat to the new oat
421 if (symlink(input_oat_filename.c_str(), output_oat_filename.c_str()) < 0) {
422 int err = errno;
423 LOG(ERROR) << "Failed to create symlink at " << output_oat_filename
424 << " error(" << err << "): " << strerror(err);
425 return false;
426 }
427
428 if (kIsDebugBuild) {
429 LOG(INFO) << "Created symlink " << output_oat_filename << " -> " << input_oat_filename;
430 }
431
432 return true;
433}
434
Alex Light53cb16b2014-06-12 11:26:29 -0700435bool PatchOat::PatchImage() {
436 ImageHeader* image_header = reinterpret_cast<ImageHeader*>(image_->Begin());
437 CHECK_GT(image_->Size(), sizeof(ImageHeader));
438 // These are the roots from the original file.
439 mirror::Object* img_roots = image_header->GetImageRoots();
440 image_header->RelocateImage(delta_);
441
442 VisitObject(img_roots);
443 if (!image_header->IsValid()) {
444 LOG(ERROR) << "reloction renders image header invalid";
445 return false;
446 }
447
448 {
Alex Lighteefbe392014-07-08 09:53:18 -0700449 TimingLogger::ScopedTiming t("Walk Bitmap", timings_);
Alex Light53cb16b2014-06-12 11:26:29 -0700450 // Walk the bitmap.
451 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
452 bitmap_->Walk(PatchOat::BitmapCallback, this);
453 }
454 return true;
455}
456
457bool PatchOat::InHeap(mirror::Object* o) {
458 uintptr_t begin = reinterpret_cast<uintptr_t>(heap_->Begin());
459 uintptr_t end = reinterpret_cast<uintptr_t>(heap_->End());
460 uintptr_t obj = reinterpret_cast<uintptr_t>(o);
461 return o == nullptr || (begin <= obj && obj < end);
462}
463
464void PatchOat::PatchVisitor::operator() (mirror::Object* obj, MemberOffset off,
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700465 bool is_static_unused ATTRIBUTE_UNUSED) const {
Alex Light53cb16b2014-06-12 11:26:29 -0700466 mirror::Object* referent = obj->GetFieldObject<mirror::Object, kVerifyNone>(off);
467 DCHECK(patcher_->InHeap(referent)) << "Referent is not in the heap.";
468 mirror::Object* moved_object = patcher_->RelocatedAddressOf(referent);
469 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(off, moved_object);
470}
471
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700472void PatchOat::PatchVisitor::operator() (mirror::Class* cls ATTRIBUTE_UNUSED,
473 mirror::Reference* ref) const {
Alex Light53cb16b2014-06-12 11:26:29 -0700474 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 {
Ian Rogers13735952014-10-08 12:43:28 -0700497 return reinterpret_cast<mirror::Object*>(reinterpret_cast<uint8_t*>(obj) + delta_);
Alex Light53cb16b2014-06-12 11:26:29 -0700498 }
499}
500
Igor Murashkin46774762014-10-22 11:37:02 -0700501const OatHeader* PatchOat::GetOatHeader(const ElfFile* elf_file) {
502 if (elf_file->Is64Bit()) {
503 return GetOatHeader<ElfFileImpl64>(elf_file->GetImpl64());
504 } else {
505 return GetOatHeader<ElfFileImpl32>(elf_file->GetImpl32());
506 }
507}
508
509template <typename ElfFileImpl>
510const OatHeader* PatchOat::GetOatHeader(const ElfFileImpl* elf_file) {
511 auto rodata_sec = elf_file->FindSectionByName(".rodata");
512 if (rodata_sec == nullptr) {
513 return nullptr;
514 }
515
516 OatHeader* oat_header = reinterpret_cast<OatHeader*>(elf_file->Begin() + rodata_sec->sh_offset);
517 return oat_header;
518}
519
Alex Light53cb16b2014-06-12 11:26:29 -0700520// Called by BitmapCallback
521void PatchOat::VisitObject(mirror::Object* object) {
522 mirror::Object* copy = RelocatedCopyOf(object);
523 CHECK(copy != nullptr);
524 if (kUseBakerOrBrooksReadBarrier) {
525 object->AssertReadBarrierPointer();
526 if (kUseBrooksReadBarrier) {
527 mirror::Object* moved_to = RelocatedAddressOf(object);
528 copy->SetReadBarrierPointer(moved_to);
529 DCHECK_EQ(copy->GetReadBarrierPointer(), moved_to);
530 }
531 }
532 PatchOat::PatchVisitor visitor(this, copy);
533 object->VisitReferences<true, kVerifyNone>(visitor, visitor);
534 if (object->IsArtMethod<kVerifyNone>()) {
Mathieu Chartier2d721012014-11-10 11:08:06 -0800535 FixupMethod(down_cast<mirror::ArtMethod*>(object), down_cast<mirror::ArtMethod*>(copy));
Alex Light53cb16b2014-06-12 11:26:29 -0700536 }
537}
538
539void PatchOat::FixupMethod(mirror::ArtMethod* object, mirror::ArtMethod* copy) {
Mathieu Chartier2d721012014-11-10 11:08:06 -0800540 const size_t pointer_size = InstructionSetPointerSize(isa_);
Alex Light53cb16b2014-06-12 11:26:29 -0700541 // Just update the entry points if it looks like we should.
Alex Lighteefbe392014-07-08 09:53:18 -0700542 // TODO: sanity check all the pointers' values
Alex Light53cb16b2014-06-12 11:26:29 -0700543 uintptr_t portable = reinterpret_cast<uintptr_t>(
Mathieu Chartier2d721012014-11-10 11:08:06 -0800544 object->GetEntryPointFromPortableCompiledCodePtrSize<kVerifyNone>(pointer_size));
Alex Light53cb16b2014-06-12 11:26:29 -0700545 if (portable != 0) {
Mathieu Chartier2d721012014-11-10 11:08:06 -0800546 copy->SetEntryPointFromPortableCompiledCodePtrSize(reinterpret_cast<void*>(portable + delta_),
547 pointer_size);
Alex Light53cb16b2014-06-12 11:26:29 -0700548 }
549 uintptr_t quick= reinterpret_cast<uintptr_t>(
Mathieu Chartier2d721012014-11-10 11:08:06 -0800550 object->GetEntryPointFromQuickCompiledCodePtrSize<kVerifyNone>(pointer_size));
Alex Light53cb16b2014-06-12 11:26:29 -0700551 if (quick != 0) {
Mathieu Chartier2d721012014-11-10 11:08:06 -0800552 copy->SetEntryPointFromQuickCompiledCodePtrSize(reinterpret_cast<void*>(quick + delta_),
553 pointer_size);
Alex Light53cb16b2014-06-12 11:26:29 -0700554 }
555 uintptr_t interpreter = reinterpret_cast<uintptr_t>(
Mathieu Chartier2d721012014-11-10 11:08:06 -0800556 object->GetEntryPointFromInterpreterPtrSize<kVerifyNone>(pointer_size));
Alex Light53cb16b2014-06-12 11:26:29 -0700557 if (interpreter != 0) {
Mathieu Chartier2d721012014-11-10 11:08:06 -0800558 copy->SetEntryPointFromInterpreterPtrSize(
559 reinterpret_cast<mirror::EntryPointFromInterpreter*>(interpreter + delta_), pointer_size);
Alex Light53cb16b2014-06-12 11:26:29 -0700560 }
561
Mathieu Chartier2d721012014-11-10 11:08:06 -0800562 uintptr_t native_method = reinterpret_cast<uintptr_t>(
563 object->GetEntryPointFromJniPtrSize(pointer_size));
Alex Light53cb16b2014-06-12 11:26:29 -0700564 if (native_method != 0) {
Mathieu Chartier2d721012014-11-10 11:08:06 -0800565 copy->SetEntryPointFromJniPtrSize(reinterpret_cast<void*>(native_method + delta_),
566 pointer_size);
Alex Light53cb16b2014-06-12 11:26:29 -0700567 }
568
Mathieu Chartier2d721012014-11-10 11:08:06 -0800569 uintptr_t native_gc_map = reinterpret_cast<uintptr_t>(
570 object->GetNativeGcMapPtrSize(pointer_size));
Alex Light53cb16b2014-06-12 11:26:29 -0700571 if (native_gc_map != 0) {
Mathieu Chartier2d721012014-11-10 11:08:06 -0800572 copy->SetNativeGcMapPtrSize(reinterpret_cast<uint8_t*>(native_gc_map + delta_), pointer_size);
Alex Light53cb16b2014-06-12 11:26:29 -0700573 }
574}
575
Igor Murashkin46774762014-10-22 11:37:02 -0700576bool PatchOat::Patch(File* input_oat, off_t delta, File* output_oat, TimingLogger* timings,
577 bool output_oat_opened_from_fd, bool new_oat_out) {
Alex Light53cb16b2014-06-12 11:26:29 -0700578 CHECK(input_oat != nullptr);
579 CHECK(output_oat != nullptr);
580 CHECK_GE(input_oat->Fd(), 0);
581 CHECK_GE(output_oat->Fd(), 0);
Alex Lighteefbe392014-07-08 09:53:18 -0700582 TimingLogger::ScopedTiming t("Setup Oat File Patching", timings);
Alex Light53cb16b2014-06-12 11:26:29 -0700583
584 std::string error_msg;
Igor Murashkin46774762014-10-22 11:37:02 -0700585 std::unique_ptr<ElfFile> elf(ElfFile::Open(input_oat,
Alex Light53cb16b2014-06-12 11:26:29 -0700586 PROT_READ | PROT_WRITE, MAP_PRIVATE, &error_msg));
587 if (elf.get() == nullptr) {
588 LOG(ERROR) << "unable to open oat file " << input_oat->GetPath() << " : " << error_msg;
589 return false;
590 }
591
Igor Murashkin46774762014-10-22 11:37:02 -0700592 MaybePic is_oat_pic = IsOatPic(elf.get());
593 if (is_oat_pic >= ERROR_FIRST) {
594 // Error logged by IsOatPic
595 return false;
596 } else if (is_oat_pic == PIC) {
597 // Do not need to do ELF-file patching. Create a symlink and skip the rest.
598 // Any errors will be logged by the function call.
599 return ReplaceOatFileWithSymlink(input_oat->GetPath(),
600 output_oat->GetPath(),
601 output_oat_opened_from_fd,
602 new_oat_out);
603 } else {
604 CHECK(is_oat_pic == NOT_PIC);
605 }
606
Alex Light53cb16b2014-06-12 11:26:29 -0700607 PatchOat p(elf.release(), delta, timings);
608 t.NewTiming("Patch Oat file");
609 if (!p.PatchElf()) {
610 return false;
611 }
612
613 t.NewTiming("Writing oat file");
614 if (!p.WriteElf(output_oat)) {
615 return false;
616 }
617 return true;
618}
619
Tong Shen62d1ca32014-09-03 17:24:56 -0700620template <typename ElfFileImpl, typename ptr_t>
621bool PatchOat::CheckOatFile(ElfFileImpl* oat_file) {
622 auto patches_sec = oat_file->FindSectionByName(".oat_patches");
623 if (patches_sec->sh_type != SHT_OAT_PATCH) {
Alex Light53cb16b2014-06-12 11:26:29 -0700624 return false;
625 }
Tong Shen62d1ca32014-09-03 17:24:56 -0700626 ptr_t* patches = reinterpret_cast<ptr_t*>(oat_file->Begin() + patches_sec->sh_offset);
627 ptr_t* patches_end = patches + (patches_sec->sh_size / sizeof(ptr_t));
628 auto oat_data_sec = oat_file->FindSectionByName(".rodata");
629 auto oat_text_sec = oat_file->FindSectionByName(".text");
Alex Light53cb16b2014-06-12 11:26:29 -0700630 if (oat_data_sec == nullptr) {
631 return false;
632 }
633 if (oat_text_sec == nullptr) {
634 return false;
635 }
636 if (oat_text_sec->sh_offset <= oat_data_sec->sh_offset) {
637 return false;
638 }
639
640 for (; patches < patches_end; patches++) {
641 if (oat_text_sec->sh_size <= *patches) {
642 return false;
643 }
644 }
645
646 return true;
647}
648
Tong Shen62d1ca32014-09-03 17:24:56 -0700649template <typename ElfFileImpl>
650bool PatchOat::PatchOatHeader(ElfFileImpl* oat_file) {
651 auto rodata_sec = oat_file->FindSectionByName(".rodata");
Alex Lighta59dd802014-07-02 16:28:08 -0700652 if (rodata_sec == nullptr) {
653 return false;
654 }
Tong Shen62d1ca32014-09-03 17:24:56 -0700655 OatHeader* oat_header = reinterpret_cast<OatHeader*>(oat_file->Begin() + rodata_sec->sh_offset);
Alex Lighta59dd802014-07-02 16:28:08 -0700656 if (!oat_header->IsValid()) {
Tong Shen62d1ca32014-09-03 17:24:56 -0700657 LOG(ERROR) << "Elf file " << oat_file->GetFile().GetPath() << " has an invalid oat header";
Alex Lighta59dd802014-07-02 16:28:08 -0700658 return false;
659 }
660 oat_header->RelocateOat(delta_);
661 return true;
662}
663
Alex Light53cb16b2014-06-12 11:26:29 -0700664bool PatchOat::PatchElf() {
Ian Rogersd4c4d952014-10-16 20:31:53 -0700665 if (oat_file_->Is64Bit())
Tong Shen62d1ca32014-09-03 17:24:56 -0700666 return PatchElf<ElfFileImpl64>(oat_file_->GetImpl64());
667 else
668 return PatchElf<ElfFileImpl32>(oat_file_->GetImpl32());
669}
670
671template <typename ElfFileImpl>
672bool PatchOat::PatchElf(ElfFileImpl* oat_file) {
Alex Lighta59dd802014-07-02 16:28:08 -0700673 TimingLogger::ScopedTiming t("Fixup Elf Text Section", timings_);
Tong Shen62d1ca32014-09-03 17:24:56 -0700674 if (!PatchTextSection<ElfFileImpl>(oat_file)) {
Alex Lighta59dd802014-07-02 16:28:08 -0700675 return false;
676 }
677
Tong Shen62d1ca32014-09-03 17:24:56 -0700678 if (!PatchOatHeader<ElfFileImpl>(oat_file)) {
Alex Lighta59dd802014-07-02 16:28:08 -0700679 return false;
680 }
681
682 bool need_fixup = false;
Ian Rogersd4c4d952014-10-16 20:31:53 -0700683 for (unsigned int i = 0; i < oat_file->GetProgramHeaderNum(); ++i) {
Tong Shen62d1ca32014-09-03 17:24:56 -0700684 auto hdr = oat_file->GetProgramHeader(i);
Ian Rogersd4c4d952014-10-16 20:31:53 -0700685 if ((hdr->p_vaddr != 0 && hdr->p_vaddr != hdr->p_offset) ||
686 (hdr->p_paddr != 0 && hdr->p_paddr != hdr->p_offset)) {
Alex Lighta59dd802014-07-02 16:28:08 -0700687 need_fixup = true;
Ian Rogersd4c4d952014-10-16 20:31:53 -0700688 break;
Alex Light53cb16b2014-06-12 11:26:29 -0700689 }
690 }
Alex Lighta59dd802014-07-02 16:28:08 -0700691 if (!need_fixup) {
692 // This was never passed through ElfFixup so all headers/symbols just have their offset as
693 // their addr. Therefore we do not need to update these parts.
694 return true;
695 }
Tong Shen62d1ca32014-09-03 17:24:56 -0700696
697 t.NewTiming("Fixup Elf Headers");
698 // Fixup Phdr's
699 oat_file->FixupProgramHeaders(delta_);
700
Alex Lighta59dd802014-07-02 16:28:08 -0700701 t.NewTiming("Fixup Section Headers");
Tong Shen62d1ca32014-09-03 17:24:56 -0700702 // Fixup Shdr's
703 oat_file->FixupSectionHeaders(delta_);
Alex Light53cb16b2014-06-12 11:26:29 -0700704
Alex Lighta59dd802014-07-02 16:28:08 -0700705 t.NewTiming("Fixup Dynamics");
Tong Shen62d1ca32014-09-03 17:24:56 -0700706 oat_file->FixupDynamic(delta_);
Alex Light53cb16b2014-06-12 11:26:29 -0700707
708 t.NewTiming("Fixup Elf Symbols");
709 // Fixup dynsym
Tong Shen62d1ca32014-09-03 17:24:56 -0700710 if (!oat_file->FixupSymbols(delta_, true)) {
Alex Light53cb16b2014-06-12 11:26:29 -0700711 return false;
712 }
Alex Light53cb16b2014-06-12 11:26:29 -0700713 // Fixup symtab
Tong Shen62d1ca32014-09-03 17:24:56 -0700714 if (!oat_file->FixupSymbols(delta_, false)) {
715 return false;
Alex Light53cb16b2014-06-12 11:26:29 -0700716 }
717
Yevgeny Roubane3ea8382014-08-08 16:29:38 +0700718 t.NewTiming("Fixup Debug Sections");
Tong Shen62d1ca32014-09-03 17:24:56 -0700719 if (!oat_file->FixupDebugSections(delta_)) {
Yevgeny Roubane3ea8382014-08-08 16:29:38 +0700720 return false;
721 }
722
Alex Light53cb16b2014-06-12 11:26:29 -0700723 return true;
724}
725
Tong Shen62d1ca32014-09-03 17:24:56 -0700726template <typename ElfFileImpl>
727bool PatchOat::PatchTextSection(ElfFileImpl* oat_file) {
728 auto patches_sec = oat_file->FindSectionByName(".oat_patches");
Alex Light53cb16b2014-06-12 11:26:29 -0700729 if (patches_sec == nullptr) {
Alex Lighta59dd802014-07-02 16:28:08 -0700730 LOG(ERROR) << ".oat_patches section not found. Aborting patch";
Alex Light53cb16b2014-06-12 11:26:29 -0700731 return false;
732 }
Alex Light4b0d2d92014-08-06 13:37:23 -0700733 if (patches_sec->sh_type != SHT_OAT_PATCH) {
734 LOG(ERROR) << "Unexpected type of .oat_patches";
735 return false;
736 }
737
738 switch (patches_sec->sh_entsize) {
739 case sizeof(uint32_t):
Tong Shen62d1ca32014-09-03 17:24:56 -0700740 return PatchTextSection<ElfFileImpl, uint32_t>(oat_file);
Alex Light4b0d2d92014-08-06 13:37:23 -0700741 case sizeof(uint64_t):
Tong Shen62d1ca32014-09-03 17:24:56 -0700742 return PatchTextSection<ElfFileImpl, uint64_t>(oat_file);
Alex Light4b0d2d92014-08-06 13:37:23 -0700743 default:
744 LOG(ERROR) << ".oat_patches Entsize of " << patches_sec->sh_entsize << "bits "
745 << "is not valid";
746 return false;
747 }
748}
749
Tong Shen62d1ca32014-09-03 17:24:56 -0700750template <typename ElfFileImpl, typename patch_loc_t>
751bool PatchOat::PatchTextSection(ElfFileImpl* oat_file) {
752 bool oat_file_valid = CheckOatFile<ElfFileImpl, patch_loc_t>(oat_file);
753 CHECK(oat_file_valid) << "Oat file invalid";
754 auto patches_sec = oat_file->FindSectionByName(".oat_patches");
755 patch_loc_t* patches = reinterpret_cast<patch_loc_t*>(oat_file->Begin() + patches_sec->sh_offset);
756 patch_loc_t* patches_end = patches + (patches_sec->sh_size / sizeof(patch_loc_t));
757 auto oat_text_sec = oat_file->FindSectionByName(".text");
Alex Light53cb16b2014-06-12 11:26:29 -0700758 CHECK(oat_text_sec != nullptr);
Ian Rogers13735952014-10-08 12:43:28 -0700759 uint8_t* to_patch = oat_file->Begin() + oat_text_sec->sh_offset;
Alex Light53cb16b2014-06-12 11:26:29 -0700760 uintptr_t to_patch_end = reinterpret_cast<uintptr_t>(to_patch) + oat_text_sec->sh_size;
761
762 for (; patches < patches_end; patches++) {
763 CHECK_LT(*patches, oat_text_sec->sh_size) << "Bad Patch";
764 uint32_t* patch_loc = reinterpret_cast<uint32_t*>(to_patch + *patches);
765 CHECK_LT(reinterpret_cast<uintptr_t>(patch_loc), to_patch_end);
766 *patch_loc += delta_;
767 }
Alex Light53cb16b2014-06-12 11:26:29 -0700768 return true;
769}
770
771static int orig_argc;
772static char** orig_argv;
773
774static std::string CommandLine() {
775 std::vector<std::string> command;
776 for (int i = 0; i < orig_argc; ++i) {
777 command.push_back(orig_argv[i]);
778 }
779 return Join(command, ' ');
780}
781
782static void UsageErrorV(const char* fmt, va_list ap) {
783 std::string error;
784 StringAppendV(&error, fmt, ap);
785 LOG(ERROR) << error;
786}
787
788static void UsageError(const char* fmt, ...) {
789 va_list ap;
790 va_start(ap, fmt);
791 UsageErrorV(fmt, ap);
792 va_end(ap);
793}
794
Ian Rogers7223d442014-10-10 20:05:39 -0700795[[noreturn]] static void Usage(const char *fmt, ...) {
Alex Light53cb16b2014-06-12 11:26:29 -0700796 va_list ap;
797 va_start(ap, fmt);
798 UsageErrorV(fmt, ap);
799 va_end(ap);
800
801 UsageError("Command: %s", CommandLine().c_str());
802 UsageError("Usage: patchoat [options]...");
803 UsageError("");
804 UsageError(" --instruction-set=<isa>: Specifies the instruction set the patched code is");
805 UsageError(" compiled for. Required if you use --input-oat-location");
806 UsageError("");
807 UsageError(" --input-oat-file=<file.oat>: Specifies the exact filename of the oat file to be");
808 UsageError(" patched.");
809 UsageError("");
810 UsageError(" --input-oat-fd=<file-descriptor>: Specifies the file-descriptor of the oat file");
811 UsageError(" to be patched.");
812 UsageError("");
813 UsageError(" --input-oat-location=<file.oat>: Specifies the 'location' to read the patched");
814 UsageError(" oat file from. If used one must also supply the --instruction-set");
815 UsageError("");
816 UsageError(" --input-image-location=<file.art>: Specifies the 'location' of the image file to");
817 UsageError(" be patched. If --instruction-set is not given it will use the instruction set");
818 UsageError(" extracted from the --input-oat-file.");
819 UsageError("");
820 UsageError(" --output-oat-file=<file.oat>: Specifies the exact file to write the patched oat");
821 UsageError(" file to.");
822 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700823 UsageError(" --output-oat-fd=<file-descriptor>: Specifies the file-descriptor to write the");
824 UsageError(" the patched oat file to.");
825 UsageError("");
826 UsageError(" --output-image-file=<file.art>: Specifies the exact file to write the patched");
827 UsageError(" image file to.");
828 UsageError("");
829 UsageError(" --output-image-fd=<file-descriptor>: Specifies the file-descriptor to write the");
830 UsageError(" the patched image file to.");
831 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700832 UsageError(" --orig-base-offset=<original-base-offset>: Specify the base offset the input file");
833 UsageError(" was compiled with. This is needed if one is specifying a --base-offset");
834 UsageError("");
835 UsageError(" --base-offset=<new-base-offset>: Specify the base offset we will repatch the");
836 UsageError(" given files to use. This requires that --orig-base-offset is also given.");
837 UsageError("");
838 UsageError(" --base-offset-delta=<delta>: Specify the amount to change the old base-offset by.");
839 UsageError(" This value may be negative.");
840 UsageError("");
841 UsageError(" --patched-image-file=<file.art>: Use the same patch delta as was used to patch");
842 UsageError(" the given image file.");
843 UsageError("");
844 UsageError(" --patched-image-location=<file.art>: Use the same patch delta as was used to");
845 UsageError(" patch the given image location. If used one must also specify the");
Alex Lighta59dd802014-07-02 16:28:08 -0700846 UsageError(" --instruction-set flag. It will search for this image in the same way that");
847 UsageError(" is done when loading one.");
Alex Light53cb16b2014-06-12 11:26:29 -0700848 UsageError("");
Alex Lightcf4bf382014-07-24 11:29:14 -0700849 UsageError(" --lock-output: Obtain a flock on output oat file before starting.");
850 UsageError("");
851 UsageError(" --no-lock-output: Do not attempt to obtain a flock on output oat file.");
852 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700853 UsageError(" --dump-timings: dump out patch timing information");
854 UsageError("");
855 UsageError(" --no-dump-timings: do not dump out patch timing information");
856 UsageError("");
857
858 exit(EXIT_FAILURE);
859}
860
Alex Lighteefbe392014-07-08 09:53:18 -0700861static bool ReadBaseDelta(const char* name, off_t* delta, std::string* error_msg) {
Alex Light53cb16b2014-06-12 11:26:29 -0700862 CHECK(name != nullptr);
863 CHECK(delta != nullptr);
864 std::unique_ptr<File> file;
865 if (OS::FileExists(name)) {
866 file.reset(OS::OpenFileForReading(name));
867 if (file.get() == nullptr) {
Alex Lighteefbe392014-07-08 09:53:18 -0700868 *error_msg = "Failed to open file %s for reading";
Alex Light53cb16b2014-06-12 11:26:29 -0700869 return false;
870 }
871 } else {
Alex Lighteefbe392014-07-08 09:53:18 -0700872 *error_msg = "File %s does not exist";
Alex Light53cb16b2014-06-12 11:26:29 -0700873 return false;
874 }
875 CHECK(file.get() != nullptr);
876 ImageHeader hdr;
877 if (sizeof(hdr) != file->Read(reinterpret_cast<char*>(&hdr), sizeof(hdr), 0)) {
Alex Lighteefbe392014-07-08 09:53:18 -0700878 *error_msg = "Failed to read file %s";
Alex Light53cb16b2014-06-12 11:26:29 -0700879 return false;
880 }
881 if (!hdr.IsValid()) {
Alex Lighteefbe392014-07-08 09:53:18 -0700882 *error_msg = "%s does not contain a valid image header.";
Alex Light53cb16b2014-06-12 11:26:29 -0700883 return false;
884 }
885 *delta = hdr.GetPatchDelta();
886 return true;
887}
888
889static File* CreateOrOpen(const char* name, bool* created) {
890 if (OS::FileExists(name)) {
891 *created = false;
892 return OS::OpenFileReadWrite(name);
893 } else {
894 *created = true;
Alex Lightcf4bf382014-07-24 11:29:14 -0700895 std::unique_ptr<File> f(OS::CreateEmptyFile(name));
896 if (f.get() != nullptr) {
897 if (fchmod(f->Fd(), 0644) != 0) {
898 PLOG(ERROR) << "Unable to make " << name << " world readable";
Brian Carlstrom8c52a3f2014-09-30 16:18:01 -0700899 TEMP_FAILURE_RETRY(unlink(name));
Alex Lightcf4bf382014-07-24 11:29:14 -0700900 return nullptr;
901 }
902 }
903 return f.release();
Alex Light53cb16b2014-06-12 11:26:29 -0700904 }
905}
906
Alex Lighteefbe392014-07-08 09:53:18 -0700907static int patchoat(int argc, char **argv) {
Alex Light53cb16b2014-06-12 11:26:29 -0700908 InitLogging(argv);
Mathieu Chartier6e88ef62014-10-14 15:01:24 -0700909 MemMap::Init();
Alex Light53cb16b2014-06-12 11:26:29 -0700910 const bool debug = kIsDebugBuild;
911 orig_argc = argc;
912 orig_argv = argv;
913 TimingLogger timings("patcher", false, false);
914
915 InitLogging(argv);
916
917 // Skip over the command name.
918 argv++;
919 argc--;
920
921 if (argc == 0) {
922 Usage("No arguments specified");
923 }
924
925 timings.StartTiming("Patchoat");
926
927 // cmd line args
928 bool isa_set = false;
929 InstructionSet isa = kNone;
930 std::string input_oat_filename;
931 std::string input_oat_location;
932 int input_oat_fd = -1;
933 bool have_input_oat = false;
934 std::string input_image_location;
935 std::string output_oat_filename;
Alex Light53cb16b2014-06-12 11:26:29 -0700936 int output_oat_fd = -1;
937 bool have_output_oat = false;
938 std::string output_image_filename;
Alex Light53cb16b2014-06-12 11:26:29 -0700939 int output_image_fd = -1;
940 bool have_output_image = false;
941 uintptr_t base_offset = 0;
942 bool base_offset_set = false;
943 uintptr_t orig_base_offset = 0;
944 bool orig_base_offset_set = false;
945 off_t base_delta = 0;
946 bool base_delta_set = false;
947 std::string patched_image_filename;
948 std::string patched_image_location;
949 bool dump_timings = kIsDebugBuild;
Alex Lightcf4bf382014-07-24 11:29:14 -0700950 bool lock_output = true;
Alex Light53cb16b2014-06-12 11:26:29 -0700951
Ian Rogersd4c4d952014-10-16 20:31:53 -0700952 for (int i = 0; i < argc; ++i) {
Alex Light53cb16b2014-06-12 11:26:29 -0700953 const StringPiece option(argv[i]);
954 const bool log_options = false;
955 if (log_options) {
956 LOG(INFO) << "patchoat: option[" << i << "]=" << argv[i];
957 }
Alex Light53cb16b2014-06-12 11:26:29 -0700958 if (option.starts_with("--instruction-set=")) {
959 isa_set = true;
960 const char* isa_str = option.substr(strlen("--instruction-set=")).data();
Andreas Gampe20c89302014-08-19 17:28:06 -0700961 isa = GetInstructionSetFromString(isa_str);
962 if (isa == kNone) {
963 Usage("Unknown or invalid instruction set %s", isa_str);
Alex Light53cb16b2014-06-12 11:26:29 -0700964 }
965 } else if (option.starts_with("--input-oat-location=")) {
966 if (have_input_oat) {
967 Usage("Only one of --input-oat-file, --input-oat-location and --input-oat-fd may be used.");
968 }
969 have_input_oat = true;
970 input_oat_location = option.substr(strlen("--input-oat-location=")).data();
971 } else if (option.starts_with("--input-oat-file=")) {
972 if (have_input_oat) {
973 Usage("Only one of --input-oat-file, --input-oat-location and --input-oat-fd may be used.");
974 }
975 have_input_oat = true;
976 input_oat_filename = option.substr(strlen("--input-oat-file=")).data();
977 } else if (option.starts_with("--input-oat-fd=")) {
978 if (have_input_oat) {
979 Usage("Only one of --input-oat-file, --input-oat-location and --input-oat-fd may be used.");
980 }
981 have_input_oat = true;
982 const char* oat_fd_str = option.substr(strlen("--input-oat-fd=")).data();
983 if (!ParseInt(oat_fd_str, &input_oat_fd)) {
984 Usage("Failed to parse --input-oat-fd argument '%s' as an integer", oat_fd_str);
985 }
986 if (input_oat_fd < 0) {
987 Usage("--input-oat-fd pass a negative value %d", input_oat_fd);
988 }
989 } else if (option.starts_with("--input-image-location=")) {
990 input_image_location = option.substr(strlen("--input-image-location=")).data();
Alex Light53cb16b2014-06-12 11:26:29 -0700991 } else if (option.starts_with("--output-oat-file=")) {
992 if (have_output_oat) {
Alex Lightcf4bf382014-07-24 11:29:14 -0700993 Usage("Only one of --output-oat-file, and --output-oat-fd may be used.");
Alex Light53cb16b2014-06-12 11:26:29 -0700994 }
995 have_output_oat = true;
996 output_oat_filename = option.substr(strlen("--output-oat-file=")).data();
997 } else if (option.starts_with("--output-oat-fd=")) {
998 if (have_output_oat) {
Alex Lightcf4bf382014-07-24 11:29:14 -0700999 Usage("Only one of --output-oat-file, --output-oat-fd may be used.");
Alex Light53cb16b2014-06-12 11:26:29 -07001000 }
1001 have_output_oat = true;
1002 const char* oat_fd_str = option.substr(strlen("--output-oat-fd=")).data();
1003 if (!ParseInt(oat_fd_str, &output_oat_fd)) {
1004 Usage("Failed to parse --output-oat-fd argument '%s' as an integer", oat_fd_str);
1005 }
1006 if (output_oat_fd < 0) {
1007 Usage("--output-oat-fd pass a negative value %d", output_oat_fd);
1008 }
Alex Light53cb16b2014-06-12 11:26:29 -07001009 } else if (option.starts_with("--output-image-file=")) {
1010 if (have_output_image) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001011 Usage("Only one of --output-image-file, and --output-image-fd may be used.");
Alex Light53cb16b2014-06-12 11:26:29 -07001012 }
1013 have_output_image = true;
1014 output_image_filename = option.substr(strlen("--output-image-file=")).data();
1015 } else if (option.starts_with("--output-image-fd=")) {
1016 if (have_output_image) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001017 Usage("Only one of --output-image-file, and --output-image-fd may be used.");
Alex Light53cb16b2014-06-12 11:26:29 -07001018 }
1019 have_output_image = true;
1020 const char* image_fd_str = option.substr(strlen("--output-image-fd=")).data();
1021 if (!ParseInt(image_fd_str, &output_image_fd)) {
1022 Usage("Failed to parse --output-image-fd argument '%s' as an integer", image_fd_str);
1023 }
1024 if (output_image_fd < 0) {
1025 Usage("--output-image-fd pass a negative value %d", output_image_fd);
1026 }
1027 } else if (option.starts_with("--orig-base-offset=")) {
1028 const char* orig_base_offset_str = option.substr(strlen("--orig-base-offset=")).data();
1029 orig_base_offset_set = true;
1030 if (!ParseUint(orig_base_offset_str, &orig_base_offset)) {
1031 Usage("Failed to parse --orig-base-offset argument '%s' as an uintptr_t",
1032 orig_base_offset_str);
1033 }
1034 } else if (option.starts_with("--base-offset=")) {
1035 const char* base_offset_str = option.substr(strlen("--base-offset=")).data();
1036 base_offset_set = true;
1037 if (!ParseUint(base_offset_str, &base_offset)) {
1038 Usage("Failed to parse --base-offset argument '%s' as an uintptr_t", base_offset_str);
1039 }
1040 } else if (option.starts_with("--base-offset-delta=")) {
1041 const char* base_delta_str = option.substr(strlen("--base-offset-delta=")).data();
1042 base_delta_set = true;
1043 if (!ParseInt(base_delta_str, &base_delta)) {
1044 Usage("Failed to parse --base-offset-delta argument '%s' as an off_t", base_delta_str);
1045 }
1046 } else if (option.starts_with("--patched-image-location=")) {
1047 patched_image_location = option.substr(strlen("--patched-image-location=")).data();
1048 } else if (option.starts_with("--patched-image-file=")) {
1049 patched_image_filename = option.substr(strlen("--patched-image-file=")).data();
Alex Lightcf4bf382014-07-24 11:29:14 -07001050 } else if (option == "--lock-output") {
1051 lock_output = true;
1052 } else if (option == "--no-lock-output") {
1053 lock_output = false;
Alex Light53cb16b2014-06-12 11:26:29 -07001054 } else if (option == "--dump-timings") {
1055 dump_timings = true;
1056 } else if (option == "--no-dump-timings") {
1057 dump_timings = false;
1058 } else {
1059 Usage("Unknown argument %s", option.data());
1060 }
1061 }
1062
1063 {
1064 // Only 1 of these may be set.
1065 uint32_t cnt = 0;
1066 cnt += (base_delta_set) ? 1 : 0;
1067 cnt += (base_offset_set && orig_base_offset_set) ? 1 : 0;
1068 cnt += (!patched_image_filename.empty()) ? 1 : 0;
1069 cnt += (!patched_image_location.empty()) ? 1 : 0;
1070 if (cnt > 1) {
1071 Usage("Only one of --base-offset/--orig-base-offset, --base-offset-delta, "
1072 "--patched-image-filename or --patched-image-location may be used.");
1073 } else if (cnt == 0) {
1074 Usage("Must specify --base-offset-delta, --base-offset and --orig-base-offset, "
1075 "--patched-image-location or --patched-image-file");
1076 }
1077 }
1078
1079 if (have_input_oat != have_output_oat) {
1080 Usage("Either both input and output oat must be supplied or niether must be.");
1081 }
1082
1083 if ((!input_image_location.empty()) != have_output_image) {
1084 Usage("Either both input and output image must be supplied or niether must be.");
1085 }
1086
1087 // We know we have both the input and output so rename for clarity.
1088 bool have_image_files = have_output_image;
1089 bool have_oat_files = have_output_oat;
1090
1091 if (!have_oat_files && !have_image_files) {
1092 Usage("Must be patching either an oat or an image file or both.");
1093 }
1094
1095 if (!have_oat_files && !isa_set) {
1096 Usage("Must include ISA if patching an image file without an oat file.");
1097 }
1098
1099 if (!input_oat_location.empty()) {
1100 if (!isa_set) {
1101 Usage("specifying a location requires specifying an instruction set");
1102 }
Alex Lightcf4bf382014-07-24 11:29:14 -07001103 if (!LocationToFilename(input_oat_location, isa, &input_oat_filename)) {
1104 Usage("Unable to find filename for input oat location %s", input_oat_location.c_str());
1105 }
Alex Light53cb16b2014-06-12 11:26:29 -07001106 if (debug) {
1107 LOG(INFO) << "Using input-oat-file " << input_oat_filename;
1108 }
1109 }
Alex Light53cb16b2014-06-12 11:26:29 -07001110 if (!patched_image_location.empty()) {
1111 if (!isa_set) {
1112 Usage("specifying a location requires specifying an instruction set");
1113 }
Alex Lighta59dd802014-07-02 16:28:08 -07001114 std::string system_filename;
1115 bool has_system = false;
1116 std::string cache_filename;
1117 bool has_cache = false;
1118 bool has_android_data_unused = false;
Andreas Gampe3c13a792014-09-18 20:56:04 -07001119 bool is_global_cache = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001120 if (!gc::space::ImageSpace::FindImageFilename(patched_image_location.c_str(), isa,
1121 &system_filename, &has_system, &cache_filename,
Andreas Gampe3c13a792014-09-18 20:56:04 -07001122 &has_android_data_unused, &has_cache,
1123 &is_global_cache)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001124 Usage("Unable to determine image file for location %s", patched_image_location.c_str());
1125 }
1126 if (has_cache) {
1127 patched_image_filename = cache_filename;
1128 } else if (has_system) {
1129 LOG(WARNING) << "Only image file found was in /system for image location "
1130 << patched_image_location;
1131 patched_image_filename = system_filename;
1132 } else {
1133 Usage("Unable to determine image file for location %s", patched_image_location.c_str());
1134 }
Alex Light53cb16b2014-06-12 11:26:29 -07001135 if (debug) {
1136 LOG(INFO) << "Using patched-image-file " << patched_image_filename;
1137 }
1138 }
1139
1140 if (!base_delta_set) {
1141 if (orig_base_offset_set && base_offset_set) {
1142 base_delta_set = true;
1143 base_delta = base_offset - orig_base_offset;
1144 } else if (!patched_image_filename.empty()) {
1145 base_delta_set = true;
1146 std::string error_msg;
Alex Lighteefbe392014-07-08 09:53:18 -07001147 if (!ReadBaseDelta(patched_image_filename.c_str(), &base_delta, &error_msg)) {
Alex Light53cb16b2014-06-12 11:26:29 -07001148 Usage(error_msg.c_str(), patched_image_filename.c_str());
1149 }
1150 } else {
1151 if (base_offset_set) {
1152 Usage("Unable to determine original base offset.");
1153 } else {
1154 Usage("Must supply a desired new offset or delta.");
1155 }
1156 }
1157 }
1158
1159 if (!IsAligned<kPageSize>(base_delta)) {
1160 Usage("Base offset/delta must be alligned to a pagesize (0x%08x) boundary.", kPageSize);
1161 }
1162
1163 // Do we need to cleanup output files if we fail?
1164 bool new_image_out = false;
1165 bool new_oat_out = false;
1166
1167 std::unique_ptr<File> input_oat;
1168 std::unique_ptr<File> output_oat;
1169 std::unique_ptr<File> output_image;
1170
1171 if (have_image_files) {
1172 CHECK(!input_image_location.empty());
1173
1174 if (output_image_fd != -1) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001175 if (output_image_filename.empty()) {
1176 output_image_filename = "output-image-file";
1177 }
Alex Light53cb16b2014-06-12 11:26:29 -07001178 output_image.reset(new File(output_image_fd, output_image_filename));
1179 } else {
1180 CHECK(!output_image_filename.empty());
1181 output_image.reset(CreateOrOpen(output_image_filename.c_str(), &new_image_out));
1182 }
1183 } else {
1184 CHECK(output_image_filename.empty() && output_image_fd == -1 && input_image_location.empty());
1185 }
1186
1187 if (have_oat_files) {
1188 if (input_oat_fd != -1) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001189 if (input_oat_filename.empty()) {
1190 input_oat_filename = "input-oat-file";
1191 }
Alex Light53cb16b2014-06-12 11:26:29 -07001192 input_oat.reset(new File(input_oat_fd, input_oat_filename));
Igor Murashkin46774762014-10-22 11:37:02 -07001193 if (input_oat == nullptr) {
1194 // Unlikely, but ensure exhaustive logging in non-0 exit code case
1195 LOG(ERROR) << "Failed to open input oat file by its FD" << input_oat_fd;
1196 }
Alex Light53cb16b2014-06-12 11:26:29 -07001197 } else {
1198 CHECK(!input_oat_filename.empty());
1199 input_oat.reset(OS::OpenFileForReading(input_oat_filename.c_str()));
Igor Murashkin46774762014-10-22 11:37:02 -07001200 if (input_oat == nullptr) {
1201 int err = errno;
1202 LOG(ERROR) << "Failed to open input oat file " << input_oat_filename
1203 << ": " << strerror(err) << "(" << err << ")";
Andreas Gampe1c83cbc2014-07-22 18:52:29 -07001204 }
Alex Light53cb16b2014-06-12 11:26:29 -07001205 }
1206
1207 if (output_oat_fd != -1) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001208 if (output_oat_filename.empty()) {
1209 output_oat_filename = "output-oat-file";
Alex Lighta59dd802014-07-02 16:28:08 -07001210 }
Alex Lightcf4bf382014-07-24 11:29:14 -07001211 output_oat.reset(new File(output_oat_fd, output_oat_filename));
Igor Murashkin46774762014-10-22 11:37:02 -07001212 if (output_oat == nullptr) {
1213 // Unlikely, but ensure exhaustive logging in non-0 exit code case
1214 LOG(ERROR) << "Failed to open output oat file by its FD" << output_oat_fd;
1215 }
Alex Light53cb16b2014-06-12 11:26:29 -07001216 } else {
1217 CHECK(!output_oat_filename.empty());
1218 output_oat.reset(CreateOrOpen(output_oat_filename.c_str(), &new_oat_out));
Igor Murashkin46774762014-10-22 11:37:02 -07001219 if (output_oat == nullptr) {
1220 int err = errno;
1221 LOG(ERROR) << "Failed to open output oat file " << output_oat_filename
1222 << ": " << strerror(err) << "(" << err << ")";
1223 }
Alex Light53cb16b2014-06-12 11:26:29 -07001224 }
1225 }
1226
Igor Murashkin46774762014-10-22 11:37:02 -07001227 // TODO: get rid of this.
Alex Light53cb16b2014-06-12 11:26:29 -07001228 auto cleanup = [&output_image_filename, &output_oat_filename,
1229 &new_oat_out, &new_image_out, &timings, &dump_timings](bool success) {
1230 timings.EndTiming();
1231 if (!success) {
1232 if (new_oat_out) {
1233 CHECK(!output_oat_filename.empty());
Brian Carlstrom8c52a3f2014-09-30 16:18:01 -07001234 TEMP_FAILURE_RETRY(unlink(output_oat_filename.c_str()));
Alex Light53cb16b2014-06-12 11:26:29 -07001235 }
1236 if (new_image_out) {
1237 CHECK(!output_image_filename.empty());
Brian Carlstrom8c52a3f2014-09-30 16:18:01 -07001238 TEMP_FAILURE_RETRY(unlink(output_image_filename.c_str()));
Alex Light53cb16b2014-06-12 11:26:29 -07001239 }
1240 }
1241 if (dump_timings) {
1242 LOG(INFO) << Dumpable<TimingLogger>(timings);
1243 }
Igor Murashkin46774762014-10-22 11:37:02 -07001244
1245 if (kIsDebugBuild) {
1246 LOG(INFO) << "Cleaning up.. success? " << success;
1247 }
Alex Light53cb16b2014-06-12 11:26:29 -07001248 };
1249
Igor Murashkin46774762014-10-22 11:37:02 -07001250 if (have_oat_files && (input_oat.get() == nullptr || output_oat.get() == nullptr)) {
1251 LOG(ERROR) << "Failed to open input/output oat files";
1252 cleanup(false);
1253 return EXIT_FAILURE;
1254 } else if (have_image_files && output_image.get() == nullptr) {
1255 LOG(ERROR) << "Failed to open output image file";
Alex Lightcf4bf382014-07-24 11:29:14 -07001256 cleanup(false);
1257 return EXIT_FAILURE;
1258 }
1259
Igor Murashkin46774762014-10-22 11:37:02 -07001260 if (debug) {
1261 LOG(INFO) << "moving offset by " << base_delta
1262 << " (0x" << std::hex << base_delta << ") bytes or "
1263 << std::dec << (base_delta/kPageSize) << " pages.";
1264 }
1265
1266 // TODO: is it going to be promatic to unlink a file that was flock-ed?
Alex Lightcf4bf382014-07-24 11:29:14 -07001267 ScopedFlock output_oat_lock;
1268 if (lock_output) {
1269 std::string error_msg;
1270 if (have_oat_files && !output_oat_lock.Init(output_oat.get(), &error_msg)) {
1271 LOG(ERROR) << "Unable to lock output oat " << output_image->GetPath() << ": " << error_msg;
1272 cleanup(false);
1273 return EXIT_FAILURE;
1274 }
1275 }
1276
Alex Light53cb16b2014-06-12 11:26:29 -07001277 bool ret;
1278 if (have_image_files && have_oat_files) {
1279 TimingLogger::ScopedTiming pt("patch image and oat", &timings);
1280 ret = PatchOat::Patch(input_oat.get(), input_image_location, base_delta,
Igor Murashkin46774762014-10-22 11:37:02 -07001281 output_oat.get(), output_image.get(), isa, &timings,
1282 output_oat_fd >= 0, // was it opened from FD?
1283 new_oat_out);
Alex Light53cb16b2014-06-12 11:26:29 -07001284 } else if (have_oat_files) {
1285 TimingLogger::ScopedTiming pt("patch oat", &timings);
Igor Murashkin46774762014-10-22 11:37:02 -07001286 ret = PatchOat::Patch(input_oat.get(), base_delta, output_oat.get(), &timings,
1287 output_oat_fd >= 0, // was it opened from FD?
1288 new_oat_out);
1289 } else if (have_image_files) {
Alex Light53cb16b2014-06-12 11:26:29 -07001290 TimingLogger::ScopedTiming pt("patch image", &timings);
Alex Lighteefbe392014-07-08 09:53:18 -07001291 ret = PatchOat::Patch(input_image_location, base_delta, output_image.get(), isa, &timings);
Igor Murashkin46774762014-10-22 11:37:02 -07001292 } else {
1293 CHECK(false);
1294 ret = true;
1295 }
1296
1297 if (kIsDebugBuild) {
1298 LOG(INFO) << "Exiting with return ... " << ret;
Alex Light53cb16b2014-06-12 11:26:29 -07001299 }
1300 cleanup(ret);
Alex Light53cb16b2014-06-12 11:26:29 -07001301 return (ret) ? EXIT_SUCCESS : EXIT_FAILURE;
1302}
1303
1304} // namespace art
1305
1306int main(int argc, char **argv) {
1307 return art::patchoat(argc, argv);
1308}