blob: 75160ca3d5254b21a7b4f68badbcce86c294f369 [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"
37#include "instruction_set.h"
38#include "mirror/art_field.h"
39#include "mirror/art_field-inl.h"
40#include "mirror/art_method.h"
41#include "mirror/art_method-inl.h"
42#include "mirror/object.h"
43#include "mirror/object-inl.h"
44#include "mirror/reference.h"
45#include "noop_compiler_callbacks.h"
46#include "offsets.h"
47#include "os.h"
48#include "runtime.h"
49#include "scoped_thread_state_change.h"
50#include "thread.h"
51#include "utils.h"
52
53namespace art {
54
55static InstructionSet ElfISAToInstructionSet(Elf32_Word isa) {
56 switch (isa) {
57 case EM_ARM:
58 return kArm;
59 case EM_AARCH64:
60 return kArm64;
61 case EM_386:
62 return kX86;
63 case EM_X86_64:
64 return kX86_64;
65 case EM_MIPS:
66 return kMips;
67 default:
68 return kNone;
69 }
70}
71
Alex Lightcf4bf382014-07-24 11:29:14 -070072static bool LocationToFilename(const std::string& location, InstructionSet isa,
73 std::string* filename) {
74 bool has_system = false;
75 bool has_cache = false;
76 // image_location = /system/framework/boot.art
Igor Murashkin46774762014-10-22 11:37:02 -070077 // system_image_filename = /system/framework/<image_isa>/boot.art
Alex Lightcf4bf382014-07-24 11:29:14 -070078 std::string system_filename(GetSystemImageFilename(location.c_str(), isa));
79 if (OS::FileExists(system_filename.c_str())) {
80 has_system = true;
81 }
82
83 bool have_android_data = false;
84 bool dalvik_cache_exists = false;
Andreas Gampe3c13a792014-09-18 20:56:04 -070085 bool is_global_cache = false;
Alex Lightcf4bf382014-07-24 11:29:14 -070086 std::string dalvik_cache;
87 GetDalvikCache(GetInstructionSetString(isa), false, &dalvik_cache,
Andreas Gampe3c13a792014-09-18 20:56:04 -070088 &have_android_data, &dalvik_cache_exists, &is_global_cache);
Alex Lightcf4bf382014-07-24 11:29:14 -070089
90 std::string cache_filename;
91 if (have_android_data && dalvik_cache_exists) {
92 // Always set output location even if it does not exist,
93 // so that the caller knows where to create the image.
94 //
95 // image_location = /system/framework/boot.art
96 // *image_filename = /data/dalvik-cache/<image_isa>/boot.art
97 std::string error_msg;
98 if (GetDalvikCacheFilename(location.c_str(), dalvik_cache.c_str(),
99 &cache_filename, &error_msg)) {
100 has_cache = true;
101 }
102 }
103 if (has_system) {
104 *filename = system_filename;
105 return true;
106 } else if (has_cache) {
107 *filename = cache_filename;
108 return true;
109 } else {
110 return false;
111 }
112}
113
Alex Light53cb16b2014-06-12 11:26:29 -0700114bool PatchOat::Patch(const std::string& image_location, off_t delta,
115 File* output_image, InstructionSet isa,
Alex Lighteefbe392014-07-08 09:53:18 -0700116 TimingLogger* timings) {
Alex Light53cb16b2014-06-12 11:26:29 -0700117 CHECK(Runtime::Current() == nullptr);
118 CHECK(output_image != nullptr);
119 CHECK_GE(output_image->Fd(), 0);
120 CHECK(!image_location.empty()) << "image file must have a filename.";
121 CHECK_NE(isa, kNone);
122
Alex Lighteefbe392014-07-08 09:53:18 -0700123 TimingLogger::ScopedTiming t("Runtime Setup", timings);
Alex Light53cb16b2014-06-12 11:26:29 -0700124 const char *isa_name = GetInstructionSetString(isa);
Alex Lightcf4bf382014-07-24 11:29:14 -0700125 std::string image_filename;
126 if (!LocationToFilename(image_location, isa, &image_filename)) {
127 LOG(ERROR) << "Unable to find image at location " << image_location;
128 return false;
129 }
Alex Light53cb16b2014-06-12 11:26:29 -0700130 std::unique_ptr<File> input_image(OS::OpenFileForReading(image_filename.c_str()));
131 if (input_image.get() == nullptr) {
Alex Lightcf4bf382014-07-24 11:29:14 -0700132 LOG(ERROR) << "unable to open input image file at " << image_filename
133 << " for location " << image_location;
Alex Light53cb16b2014-06-12 11:26:29 -0700134 return false;
135 }
Igor Murashkin46774762014-10-22 11:37:02 -0700136
Alex Light53cb16b2014-06-12 11:26:29 -0700137 int64_t image_len = input_image->GetLength();
138 if (image_len < 0) {
139 LOG(ERROR) << "Error while getting image length";
140 return false;
141 }
142 ImageHeader image_header;
143 if (sizeof(image_header) != input_image->Read(reinterpret_cast<char*>(&image_header),
144 sizeof(image_header), 0)) {
145 LOG(ERROR) << "Unable to read image header from image file " << input_image->GetPath();
146 return false;
147 }
148
Igor Murashkin46774762014-10-22 11:37:02 -0700149 /*bool is_image_pic = */IsImagePic(image_header, input_image->GetPath());
150 // Nothing special to do right now since the image always needs to get patched.
151 // Perhaps in some far-off future we may have images with relative addresses that are true-PIC.
152
Alex Light53cb16b2014-06-12 11:26:29 -0700153 // Set up the runtime
Ian Rogerse63db272014-07-15 15:36:11 -0700154 RuntimeOptions options;
Alex Light53cb16b2014-06-12 11:26:29 -0700155 NoopCompilerCallbacks callbacks;
156 options.push_back(std::make_pair("compilercallbacks", &callbacks));
157 std::string img = "-Ximage:" + image_location;
158 options.push_back(std::make_pair(img.c_str(), nullptr));
159 options.push_back(std::make_pair("imageinstructionset", reinterpret_cast<const void*>(isa_name)));
160 if (!Runtime::Create(options, false)) {
161 LOG(ERROR) << "Unable to initialize runtime";
162 return false;
163 }
164 // Runtime::Create acquired the mutator_lock_ that is normally given away when we Runtime::Start,
165 // give it away now and then switch to a more manageable ScopedObjectAccess.
166 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
167 ScopedObjectAccess soa(Thread::Current());
168
169 t.NewTiming("Image and oat Patching setup");
170 // Create the map where we will write the image patches to.
Alex Lighteefbe392014-07-08 09:53:18 -0700171 std::string error_msg;
Alex Light53cb16b2014-06-12 11:26:29 -0700172 std::unique_ptr<MemMap> image(MemMap::MapFile(image_len, PROT_READ | PROT_WRITE, MAP_PRIVATE,
173 input_image->Fd(), 0,
174 input_image->GetPath().c_str(),
175 &error_msg));
176 if (image.get() == nullptr) {
177 LOG(ERROR) << "unable to map image file " << input_image->GetPath() << " : " << error_msg;
178 return false;
179 }
180 gc::space::ImageSpace* ispc = Runtime::Current()->GetHeap()->GetImageSpace();
181
182 PatchOat p(image.release(), ispc->GetLiveBitmap(), ispc->GetMemMap(),
183 delta, timings);
184 t.NewTiming("Patching files");
185 if (!p.PatchImage()) {
Alex Lighta59dd802014-07-02 16:28:08 -0700186 LOG(ERROR) << "Failed to patch image file " << input_image->GetPath();
Alex Light53cb16b2014-06-12 11:26:29 -0700187 return false;
188 }
189
190 t.NewTiming("Writing files");
191 if (!p.WriteImage(output_image)) {
192 return false;
193 }
194 return true;
195}
196
Igor Murashkin46774762014-10-22 11:37:02 -0700197bool PatchOat::Patch(File* input_oat, const std::string& image_location, off_t delta,
Alex Light53cb16b2014-06-12 11:26:29 -0700198 File* output_oat, File* output_image, InstructionSet isa,
Igor Murashkin46774762014-10-22 11:37:02 -0700199 TimingLogger* timings,
200 bool output_oat_opened_from_fd,
201 bool new_oat_out) {
Alex Light53cb16b2014-06-12 11:26:29 -0700202 CHECK(Runtime::Current() == nullptr);
203 CHECK(output_image != nullptr);
204 CHECK_GE(output_image->Fd(), 0);
205 CHECK(input_oat != nullptr);
206 CHECK(output_oat != nullptr);
207 CHECK_GE(input_oat->Fd(), 0);
208 CHECK_GE(output_oat->Fd(), 0);
209 CHECK(!image_location.empty()) << "image file must have a filename.";
210
Alex Lighteefbe392014-07-08 09:53:18 -0700211 TimingLogger::ScopedTiming t("Runtime Setup", timings);
Alex Light53cb16b2014-06-12 11:26:29 -0700212
213 if (isa == kNone) {
214 Elf32_Ehdr elf_hdr;
215 if (sizeof(elf_hdr) != input_oat->Read(reinterpret_cast<char*>(&elf_hdr), sizeof(elf_hdr), 0)) {
216 LOG(ERROR) << "unable to read elf header";
217 return false;
218 }
219 isa = ElfISAToInstructionSet(elf_hdr.e_machine);
220 }
221 const char* isa_name = GetInstructionSetString(isa);
Alex Lightcf4bf382014-07-24 11:29:14 -0700222 std::string image_filename;
223 if (!LocationToFilename(image_location, isa, &image_filename)) {
224 LOG(ERROR) << "Unable to find image at location " << image_location;
225 return false;
226 }
Alex Light53cb16b2014-06-12 11:26:29 -0700227 std::unique_ptr<File> input_image(OS::OpenFileForReading(image_filename.c_str()));
228 if (input_image.get() == nullptr) {
Alex Lightcf4bf382014-07-24 11:29:14 -0700229 LOG(ERROR) << "unable to open input image file at " << image_filename
230 << " for location " << image_location;
Alex Light53cb16b2014-06-12 11:26:29 -0700231 return false;
232 }
233 int64_t image_len = input_image->GetLength();
234 if (image_len < 0) {
235 LOG(ERROR) << "Error while getting image length";
236 return false;
237 }
238 ImageHeader image_header;
239 if (sizeof(image_header) != input_image->Read(reinterpret_cast<char*>(&image_header),
240 sizeof(image_header), 0)) {
241 LOG(ERROR) << "Unable to read image header from image file " << input_image->GetPath();
242 }
243
Igor Murashkin46774762014-10-22 11:37:02 -0700244 /*bool is_image_pic = */IsImagePic(image_header, input_image->GetPath());
245 // Nothing special to do right now since the image always needs to get patched.
246 // Perhaps in some far-off future we may have images with relative addresses that are true-PIC.
247
Alex Light53cb16b2014-06-12 11:26:29 -0700248 // Set up the runtime
Ian Rogerse63db272014-07-15 15:36:11 -0700249 RuntimeOptions options;
Alex Light53cb16b2014-06-12 11:26:29 -0700250 NoopCompilerCallbacks callbacks;
251 options.push_back(std::make_pair("compilercallbacks", &callbacks));
252 std::string img = "-Ximage:" + image_location;
253 options.push_back(std::make_pair(img.c_str(), nullptr));
254 options.push_back(std::make_pair("imageinstructionset", reinterpret_cast<const void*>(isa_name)));
255 if (!Runtime::Create(options, false)) {
256 LOG(ERROR) << "Unable to initialize runtime";
257 return false;
258 }
259 // Runtime::Create acquired the mutator_lock_ that is normally given away when we Runtime::Start,
260 // give it away now and then switch to a more manageable ScopedObjectAccess.
261 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
262 ScopedObjectAccess soa(Thread::Current());
263
264 t.NewTiming("Image and oat Patching setup");
265 // Create the map where we will write the image patches to.
Alex Lighteefbe392014-07-08 09:53:18 -0700266 std::string error_msg;
Alex Light53cb16b2014-06-12 11:26:29 -0700267 std::unique_ptr<MemMap> image(MemMap::MapFile(image_len, PROT_READ | PROT_WRITE, MAP_PRIVATE,
268 input_image->Fd(), 0,
269 input_image->GetPath().c_str(),
270 &error_msg));
271 if (image.get() == nullptr) {
272 LOG(ERROR) << "unable to map image file " << input_image->GetPath() << " : " << error_msg;
273 return false;
274 }
275 gc::space::ImageSpace* ispc = Runtime::Current()->GetHeap()->GetImageSpace();
276
Igor Murashkin46774762014-10-22 11:37:02 -0700277 std::unique_ptr<ElfFile> elf(ElfFile::Open(input_oat,
Alex Light53cb16b2014-06-12 11:26:29 -0700278 PROT_READ | PROT_WRITE, MAP_PRIVATE, &error_msg));
279 if (elf.get() == nullptr) {
280 LOG(ERROR) << "unable to open oat file " << input_oat->GetPath() << " : " << error_msg;
281 return false;
282 }
283
Igor Murashkin46774762014-10-22 11:37:02 -0700284 bool skip_patching_oat = false;
285 MaybePic is_oat_pic = IsOatPic(elf.get());
286 if (is_oat_pic >= ERROR_FIRST) {
287 // Error logged by IsOatPic
288 return false;
289 } else if (is_oat_pic == PIC) {
290 // Do not need to do ELF-file patching. Create a symlink and skip the ELF patching.
291 if (!ReplaceOatFileWithSymlink(input_oat->GetPath(),
292 output_oat->GetPath(),
293 output_oat_opened_from_fd,
294 new_oat_out)) {
295 // Errors already logged by above call.
296 return false;
297 }
298 // Don't patch the OAT, since we just symlinked it. Image still needs patching.
299 skip_patching_oat = true;
300 } else {
301 CHECK(is_oat_pic == NOT_PIC);
302 }
303
Alex Light53cb16b2014-06-12 11:26:29 -0700304 PatchOat p(elf.release(), image.release(), ispc->GetLiveBitmap(), ispc->GetMemMap(),
305 delta, timings);
306 t.NewTiming("Patching files");
Igor Murashkin46774762014-10-22 11:37:02 -0700307 if (!skip_patching_oat && !p.PatchElf()) {
Alex Lighta59dd802014-07-02 16:28:08 -0700308 LOG(ERROR) << "Failed to patch oat file " << input_oat->GetPath();
Alex Light53cb16b2014-06-12 11:26:29 -0700309 return false;
310 }
311 if (!p.PatchImage()) {
Alex Lighta59dd802014-07-02 16:28:08 -0700312 LOG(ERROR) << "Failed to patch image file " << input_image->GetPath();
Alex Light53cb16b2014-06-12 11:26:29 -0700313 return false;
314 }
315
316 t.NewTiming("Writing files");
Igor Murashkin46774762014-10-22 11:37:02 -0700317 if (!skip_patching_oat && !p.WriteElf(output_oat)) {
318 LOG(ERROR) << "Failed to write oat file " << input_oat->GetPath();
Alex Light53cb16b2014-06-12 11:26:29 -0700319 return false;
320 }
321 if (!p.WriteImage(output_image)) {
Igor Murashkin46774762014-10-22 11:37:02 -0700322 LOG(ERROR) << "Failed to write image file " << input_image->GetPath();
Alex Light53cb16b2014-06-12 11:26:29 -0700323 return false;
324 }
325 return true;
326}
327
328bool PatchOat::WriteElf(File* out) {
Alex Lighteefbe392014-07-08 09:53:18 -0700329 TimingLogger::ScopedTiming t("Writing Elf File", timings_);
Alex Lighta59dd802014-07-02 16:28:08 -0700330
Alex Light53cb16b2014-06-12 11:26:29 -0700331 CHECK(oat_file_.get() != nullptr);
332 CHECK(out != nullptr);
333 size_t expect = oat_file_->Size();
334 if (out->WriteFully(reinterpret_cast<char*>(oat_file_->Begin()), expect) &&
335 out->SetLength(expect) == 0) {
336 return true;
337 } else {
338 LOG(ERROR) << "Writing to oat file " << out->GetPath() << " failed.";
339 return false;
340 }
341}
342
343bool PatchOat::WriteImage(File* out) {
Alex Lighteefbe392014-07-08 09:53:18 -0700344 TimingLogger::ScopedTiming t("Writing image File", timings_);
Alex Lighta59dd802014-07-02 16:28:08 -0700345 std::string error_msg;
346
Alex Lightcf4bf382014-07-24 11:29:14 -0700347 ScopedFlock img_flock;
348 img_flock.Init(out, &error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -0700349
Alex Light53cb16b2014-06-12 11:26:29 -0700350 CHECK(image_ != nullptr);
351 CHECK(out != nullptr);
352 size_t expect = image_->Size();
353 if (out->WriteFully(reinterpret_cast<char*>(image_->Begin()), expect) &&
354 out->SetLength(expect) == 0) {
355 return true;
356 } else {
357 LOG(ERROR) << "Writing to image file " << out->GetPath() << " failed.";
358 return false;
359 }
360}
361
Igor Murashkin46774762014-10-22 11:37:02 -0700362bool PatchOat::IsImagePic(const ImageHeader& image_header, const std::string& image_path) {
363 if (!image_header.CompilePic()) {
364 if (kIsDebugBuild) {
365 LOG(INFO) << "image at location " << image_path << " was *not* compiled pic";
366 }
367 return false;
368 }
369
370 if (kIsDebugBuild) {
371 LOG(INFO) << "image at location " << image_path << " was compiled PIC";
372 }
373
374 return true;
375}
376
377PatchOat::MaybePic PatchOat::IsOatPic(const ElfFile* oat_in) {
378 if (oat_in == nullptr) {
379 LOG(ERROR) << "No ELF input oat fie available";
380 return ERROR_OAT_FILE;
381 }
382
383 const std::string& file_path = oat_in->GetFile().GetPath();
384
385 const OatHeader* oat_header = GetOatHeader(oat_in);
386 if (oat_header == nullptr) {
387 LOG(ERROR) << "Failed to find oat header in oat file " << file_path;
388 return ERROR_OAT_FILE;
389 }
390
391 if (!oat_header->IsValid()) {
392 LOG(ERROR) << "Elf file " << file_path << " has an invalid oat header";
393 return ERROR_OAT_FILE;
394 }
395
396 bool is_pic = oat_header->IsPic();
397 if (kIsDebugBuild) {
398 LOG(INFO) << "Oat file at " << file_path << " is " << (is_pic ? "PIC" : "not pic");
399 }
400
401 return is_pic ? PIC : NOT_PIC;
402}
403
404bool PatchOat::ReplaceOatFileWithSymlink(const std::string& input_oat_filename,
405 const std::string& output_oat_filename,
406 bool output_oat_opened_from_fd,
407 bool new_oat_out) {
408 // Need a file when we are PIC, since we symlink over it. Refusing to symlink into FD.
409 if (output_oat_opened_from_fd) {
410 // TODO: installd uses --output-oat-fd. Should we change class linking logic for PIC?
411 LOG(ERROR) << "No output oat filename specified, needs filename for when we are PIC";
412 return false;
413 }
414
415 // Image was PIC. Create symlink where the oat is supposed to go.
416 if (!new_oat_out) {
417 LOG(ERROR) << "Oat file " << output_oat_filename << " already exists, refusing to overwrite";
418 return false;
419 }
420
421 // Delete the original file, since we won't need it.
422 TEMP_FAILURE_RETRY(unlink(output_oat_filename.c_str()));
423
424 // Create a symlink from the old oat to the new oat
425 if (symlink(input_oat_filename.c_str(), output_oat_filename.c_str()) < 0) {
426 int err = errno;
427 LOG(ERROR) << "Failed to create symlink at " << output_oat_filename
428 << " error(" << err << "): " << strerror(err);
429 return false;
430 }
431
432 if (kIsDebugBuild) {
433 LOG(INFO) << "Created symlink " << output_oat_filename << " -> " << input_oat_filename;
434 }
435
436 return true;
437}
438
Alex Light53cb16b2014-06-12 11:26:29 -0700439bool PatchOat::PatchImage() {
440 ImageHeader* image_header = reinterpret_cast<ImageHeader*>(image_->Begin());
441 CHECK_GT(image_->Size(), sizeof(ImageHeader));
442 // These are the roots from the original file.
443 mirror::Object* img_roots = image_header->GetImageRoots();
444 image_header->RelocateImage(delta_);
445
446 VisitObject(img_roots);
447 if (!image_header->IsValid()) {
448 LOG(ERROR) << "reloction renders image header invalid";
449 return false;
450 }
451
452 {
Alex Lighteefbe392014-07-08 09:53:18 -0700453 TimingLogger::ScopedTiming t("Walk Bitmap", timings_);
Alex Light53cb16b2014-06-12 11:26:29 -0700454 // Walk the bitmap.
455 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
456 bitmap_->Walk(PatchOat::BitmapCallback, this);
457 }
458 return true;
459}
460
461bool PatchOat::InHeap(mirror::Object* o) {
462 uintptr_t begin = reinterpret_cast<uintptr_t>(heap_->Begin());
463 uintptr_t end = reinterpret_cast<uintptr_t>(heap_->End());
464 uintptr_t obj = reinterpret_cast<uintptr_t>(o);
465 return o == nullptr || (begin <= obj && obj < end);
466}
467
468void PatchOat::PatchVisitor::operator() (mirror::Object* obj, MemberOffset off,
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700469 bool is_static_unused ATTRIBUTE_UNUSED) const {
Alex Light53cb16b2014-06-12 11:26:29 -0700470 mirror::Object* referent = obj->GetFieldObject<mirror::Object, kVerifyNone>(off);
471 DCHECK(patcher_->InHeap(referent)) << "Referent is not in the heap.";
472 mirror::Object* moved_object = patcher_->RelocatedAddressOf(referent);
473 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(off, moved_object);
474}
475
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700476void PatchOat::PatchVisitor::operator() (mirror::Class* cls ATTRIBUTE_UNUSED,
477 mirror::Reference* ref) const {
Alex Light53cb16b2014-06-12 11:26:29 -0700478 MemberOffset off = mirror::Reference::ReferentOffset();
479 mirror::Object* referent = ref->GetReferent();
480 DCHECK(patcher_->InHeap(referent)) << "Referent is not in the heap.";
481 mirror::Object* moved_object = patcher_->RelocatedAddressOf(referent);
482 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(off, moved_object);
483}
484
485mirror::Object* PatchOat::RelocatedCopyOf(mirror::Object* obj) {
486 if (obj == nullptr) {
487 return nullptr;
488 }
489 DCHECK_GT(reinterpret_cast<uintptr_t>(obj), reinterpret_cast<uintptr_t>(heap_->Begin()));
490 DCHECK_LT(reinterpret_cast<uintptr_t>(obj), reinterpret_cast<uintptr_t>(heap_->End()));
491 uintptr_t heap_off =
492 reinterpret_cast<uintptr_t>(obj) - reinterpret_cast<uintptr_t>(heap_->Begin());
493 DCHECK_LT(heap_off, image_->Size());
494 return reinterpret_cast<mirror::Object*>(image_->Begin() + heap_off);
495}
496
497mirror::Object* PatchOat::RelocatedAddressOf(mirror::Object* obj) {
498 if (obj == nullptr) {
499 return nullptr;
500 } else {
Ian Rogers13735952014-10-08 12:43:28 -0700501 return reinterpret_cast<mirror::Object*>(reinterpret_cast<uint8_t*>(obj) + delta_);
Alex Light53cb16b2014-06-12 11:26:29 -0700502 }
503}
504
Igor Murashkin46774762014-10-22 11:37:02 -0700505const OatHeader* PatchOat::GetOatHeader(const ElfFile* elf_file) {
506 if (elf_file->Is64Bit()) {
507 return GetOatHeader<ElfFileImpl64>(elf_file->GetImpl64());
508 } else {
509 return GetOatHeader<ElfFileImpl32>(elf_file->GetImpl32());
510 }
511}
512
513template <typename ElfFileImpl>
514const OatHeader* PatchOat::GetOatHeader(const ElfFileImpl* elf_file) {
515 auto rodata_sec = elf_file->FindSectionByName(".rodata");
516 if (rodata_sec == nullptr) {
517 return nullptr;
518 }
519
520 OatHeader* oat_header = reinterpret_cast<OatHeader*>(elf_file->Begin() + rodata_sec->sh_offset);
521 return oat_header;
522}
523
Alex Light53cb16b2014-06-12 11:26:29 -0700524// Called by BitmapCallback
525void PatchOat::VisitObject(mirror::Object* object) {
526 mirror::Object* copy = RelocatedCopyOf(object);
527 CHECK(copy != nullptr);
528 if (kUseBakerOrBrooksReadBarrier) {
529 object->AssertReadBarrierPointer();
530 if (kUseBrooksReadBarrier) {
531 mirror::Object* moved_to = RelocatedAddressOf(object);
532 copy->SetReadBarrierPointer(moved_to);
533 DCHECK_EQ(copy->GetReadBarrierPointer(), moved_to);
534 }
535 }
536 PatchOat::PatchVisitor visitor(this, copy);
537 object->VisitReferences<true, kVerifyNone>(visitor, visitor);
538 if (object->IsArtMethod<kVerifyNone>()) {
539 FixupMethod(static_cast<mirror::ArtMethod*>(object),
540 static_cast<mirror::ArtMethod*>(copy));
541 }
542}
543
544void PatchOat::FixupMethod(mirror::ArtMethod* object, mirror::ArtMethod* copy) {
545 // Just update the entry points if it looks like we should.
Alex Lighteefbe392014-07-08 09:53:18 -0700546 // TODO: sanity check all the pointers' values
Alex Light53cb16b2014-06-12 11:26:29 -0700547 uintptr_t portable = reinterpret_cast<uintptr_t>(
548 object->GetEntryPointFromPortableCompiledCode<kVerifyNone>());
549 if (portable != 0) {
550 copy->SetEntryPointFromPortableCompiledCode(reinterpret_cast<void*>(portable + delta_));
551 }
552 uintptr_t quick= reinterpret_cast<uintptr_t>(
553 object->GetEntryPointFromQuickCompiledCode<kVerifyNone>());
554 if (quick != 0) {
555 copy->SetEntryPointFromQuickCompiledCode(reinterpret_cast<void*>(quick + delta_));
556 }
557 uintptr_t interpreter = reinterpret_cast<uintptr_t>(
558 object->GetEntryPointFromInterpreter<kVerifyNone>());
559 if (interpreter != 0) {
560 copy->SetEntryPointFromInterpreter(
561 reinterpret_cast<mirror::EntryPointFromInterpreter*>(interpreter + delta_));
562 }
563
564 uintptr_t native_method = reinterpret_cast<uintptr_t>(object->GetNativeMethod());
565 if (native_method != 0) {
566 copy->SetNativeMethod(reinterpret_cast<void*>(native_method + delta_));
567 }
568
569 uintptr_t native_gc_map = reinterpret_cast<uintptr_t>(object->GetNativeGcMap());
570 if (native_gc_map != 0) {
571 copy->SetNativeGcMap(reinterpret_cast<uint8_t*>(native_gc_map + delta_));
572 }
573}
574
Igor Murashkin46774762014-10-22 11:37:02 -0700575bool PatchOat::Patch(File* input_oat, off_t delta, File* output_oat, TimingLogger* timings,
576 bool output_oat_opened_from_fd, bool new_oat_out) {
Alex Light53cb16b2014-06-12 11:26:29 -0700577 CHECK(input_oat != nullptr);
578 CHECK(output_oat != nullptr);
579 CHECK_GE(input_oat->Fd(), 0);
580 CHECK_GE(output_oat->Fd(), 0);
Alex Lighteefbe392014-07-08 09:53:18 -0700581 TimingLogger::ScopedTiming t("Setup Oat File Patching", timings);
Alex Light53cb16b2014-06-12 11:26:29 -0700582
583 std::string error_msg;
Igor Murashkin46774762014-10-22 11:37:02 -0700584 std::unique_ptr<ElfFile> elf(ElfFile::Open(input_oat,
Alex Light53cb16b2014-06-12 11:26:29 -0700585 PROT_READ | PROT_WRITE, MAP_PRIVATE, &error_msg));
586 if (elf.get() == nullptr) {
587 LOG(ERROR) << "unable to open oat file " << input_oat->GetPath() << " : " << error_msg;
588 return false;
589 }
590
Igor Murashkin46774762014-10-22 11:37:02 -0700591 MaybePic is_oat_pic = IsOatPic(elf.get());
592 if (is_oat_pic >= ERROR_FIRST) {
593 // Error logged by IsOatPic
594 return false;
595 } else if (is_oat_pic == PIC) {
596 // Do not need to do ELF-file patching. Create a symlink and skip the rest.
597 // Any errors will be logged by the function call.
598 return ReplaceOatFileWithSymlink(input_oat->GetPath(),
599 output_oat->GetPath(),
600 output_oat_opened_from_fd,
601 new_oat_out);
602 } else {
603 CHECK(is_oat_pic == NOT_PIC);
604 }
605
Alex Light53cb16b2014-06-12 11:26:29 -0700606 PatchOat p(elf.release(), delta, timings);
607 t.NewTiming("Patch Oat file");
608 if (!p.PatchElf()) {
609 return false;
610 }
611
612 t.NewTiming("Writing oat file");
613 if (!p.WriteElf(output_oat)) {
614 return false;
615 }
616 return true;
617}
618
Tong Shen62d1ca32014-09-03 17:24:56 -0700619template <typename ElfFileImpl, typename ptr_t>
620bool PatchOat::CheckOatFile(ElfFileImpl* oat_file) {
621 auto patches_sec = oat_file->FindSectionByName(".oat_patches");
622 if (patches_sec->sh_type != SHT_OAT_PATCH) {
Alex Light53cb16b2014-06-12 11:26:29 -0700623 return false;
624 }
Tong Shen62d1ca32014-09-03 17:24:56 -0700625 ptr_t* patches = reinterpret_cast<ptr_t*>(oat_file->Begin() + patches_sec->sh_offset);
626 ptr_t* patches_end = patches + (patches_sec->sh_size / sizeof(ptr_t));
627 auto oat_data_sec = oat_file->FindSectionByName(".rodata");
628 auto oat_text_sec = oat_file->FindSectionByName(".text");
Alex Light53cb16b2014-06-12 11:26:29 -0700629 if (oat_data_sec == nullptr) {
630 return false;
631 }
632 if (oat_text_sec == nullptr) {
633 return false;
634 }
635 if (oat_text_sec->sh_offset <= oat_data_sec->sh_offset) {
636 return false;
637 }
638
639 for (; patches < patches_end; patches++) {
640 if (oat_text_sec->sh_size <= *patches) {
641 return false;
642 }
643 }
644
645 return true;
646}
647
Tong Shen62d1ca32014-09-03 17:24:56 -0700648template <typename ElfFileImpl>
649bool PatchOat::PatchOatHeader(ElfFileImpl* oat_file) {
650 auto rodata_sec = oat_file->FindSectionByName(".rodata");
Alex Lighta59dd802014-07-02 16:28:08 -0700651 if (rodata_sec == nullptr) {
652 return false;
653 }
Tong Shen62d1ca32014-09-03 17:24:56 -0700654 OatHeader* oat_header = reinterpret_cast<OatHeader*>(oat_file->Begin() + rodata_sec->sh_offset);
Alex Lighta59dd802014-07-02 16:28:08 -0700655 if (!oat_header->IsValid()) {
Tong Shen62d1ca32014-09-03 17:24:56 -0700656 LOG(ERROR) << "Elf file " << oat_file->GetFile().GetPath() << " has an invalid oat header";
Alex Lighta59dd802014-07-02 16:28:08 -0700657 return false;
658 }
659 oat_header->RelocateOat(delta_);
660 return true;
661}
662
Alex Light53cb16b2014-06-12 11:26:29 -0700663bool PatchOat::PatchElf() {
Ian Rogersd4c4d952014-10-16 20:31:53 -0700664 if (oat_file_->Is64Bit())
Tong Shen62d1ca32014-09-03 17:24:56 -0700665 return PatchElf<ElfFileImpl64>(oat_file_->GetImpl64());
666 else
667 return PatchElf<ElfFileImpl32>(oat_file_->GetImpl32());
668}
669
670template <typename ElfFileImpl>
671bool PatchOat::PatchElf(ElfFileImpl* oat_file) {
Alex Lighta59dd802014-07-02 16:28:08 -0700672 TimingLogger::ScopedTiming t("Fixup Elf Text Section", timings_);
Tong Shen62d1ca32014-09-03 17:24:56 -0700673 if (!PatchTextSection<ElfFileImpl>(oat_file)) {
Alex Lighta59dd802014-07-02 16:28:08 -0700674 return false;
675 }
676
Tong Shen62d1ca32014-09-03 17:24:56 -0700677 if (!PatchOatHeader<ElfFileImpl>(oat_file)) {
Alex Lighta59dd802014-07-02 16:28:08 -0700678 return false;
679 }
680
681 bool need_fixup = false;
Ian Rogersd4c4d952014-10-16 20:31:53 -0700682 for (unsigned int i = 0; i < oat_file->GetProgramHeaderNum(); ++i) {
Tong Shen62d1ca32014-09-03 17:24:56 -0700683 auto hdr = oat_file->GetProgramHeader(i);
Ian Rogersd4c4d952014-10-16 20:31:53 -0700684 if ((hdr->p_vaddr != 0 && hdr->p_vaddr != hdr->p_offset) ||
685 (hdr->p_paddr != 0 && hdr->p_paddr != hdr->p_offset)) {
Alex Lighta59dd802014-07-02 16:28:08 -0700686 need_fixup = true;
Ian Rogersd4c4d952014-10-16 20:31:53 -0700687 break;
Alex Light53cb16b2014-06-12 11:26:29 -0700688 }
689 }
Alex Lighta59dd802014-07-02 16:28:08 -0700690 if (!need_fixup) {
691 // This was never passed through ElfFixup so all headers/symbols just have their offset as
692 // their addr. Therefore we do not need to update these parts.
693 return true;
694 }
Tong Shen62d1ca32014-09-03 17:24:56 -0700695
696 t.NewTiming("Fixup Elf Headers");
697 // Fixup Phdr's
698 oat_file->FixupProgramHeaders(delta_);
699
Alex Lighta59dd802014-07-02 16:28:08 -0700700 t.NewTiming("Fixup Section Headers");
Tong Shen62d1ca32014-09-03 17:24:56 -0700701 // Fixup Shdr's
702 oat_file->FixupSectionHeaders(delta_);
Alex Light53cb16b2014-06-12 11:26:29 -0700703
Alex Lighta59dd802014-07-02 16:28:08 -0700704 t.NewTiming("Fixup Dynamics");
Tong Shen62d1ca32014-09-03 17:24:56 -0700705 oat_file->FixupDynamic(delta_);
Alex Light53cb16b2014-06-12 11:26:29 -0700706
707 t.NewTiming("Fixup Elf Symbols");
708 // Fixup dynsym
Tong Shen62d1ca32014-09-03 17:24:56 -0700709 if (!oat_file->FixupSymbols(delta_, true)) {
Alex Light53cb16b2014-06-12 11:26:29 -0700710 return false;
711 }
Alex Light53cb16b2014-06-12 11:26:29 -0700712 // Fixup symtab
Tong Shen62d1ca32014-09-03 17:24:56 -0700713 if (!oat_file->FixupSymbols(delta_, false)) {
714 return false;
Alex Light53cb16b2014-06-12 11:26:29 -0700715 }
716
Yevgeny Roubane3ea8382014-08-08 16:29:38 +0700717 t.NewTiming("Fixup Debug Sections");
Tong Shen62d1ca32014-09-03 17:24:56 -0700718 if (!oat_file->FixupDebugSections(delta_)) {
Yevgeny Roubane3ea8382014-08-08 16:29:38 +0700719 return false;
720 }
721
Alex Light53cb16b2014-06-12 11:26:29 -0700722 return true;
723}
724
Tong Shen62d1ca32014-09-03 17:24:56 -0700725template <typename ElfFileImpl>
726bool PatchOat::PatchTextSection(ElfFileImpl* oat_file) {
727 auto patches_sec = oat_file->FindSectionByName(".oat_patches");
Alex Light53cb16b2014-06-12 11:26:29 -0700728 if (patches_sec == nullptr) {
Alex Lighta59dd802014-07-02 16:28:08 -0700729 LOG(ERROR) << ".oat_patches section not found. Aborting patch";
Alex Light53cb16b2014-06-12 11:26:29 -0700730 return false;
731 }
Alex Light4b0d2d92014-08-06 13:37:23 -0700732 if (patches_sec->sh_type != SHT_OAT_PATCH) {
733 LOG(ERROR) << "Unexpected type of .oat_patches";
734 return false;
735 }
736
737 switch (patches_sec->sh_entsize) {
738 case sizeof(uint32_t):
Tong Shen62d1ca32014-09-03 17:24:56 -0700739 return PatchTextSection<ElfFileImpl, uint32_t>(oat_file);
Alex Light4b0d2d92014-08-06 13:37:23 -0700740 case sizeof(uint64_t):
Tong Shen62d1ca32014-09-03 17:24:56 -0700741 return PatchTextSection<ElfFileImpl, uint64_t>(oat_file);
Alex Light4b0d2d92014-08-06 13:37:23 -0700742 default:
743 LOG(ERROR) << ".oat_patches Entsize of " << patches_sec->sh_entsize << "bits "
744 << "is not valid";
745 return false;
746 }
747}
748
Tong Shen62d1ca32014-09-03 17:24:56 -0700749template <typename ElfFileImpl, typename patch_loc_t>
750bool PatchOat::PatchTextSection(ElfFileImpl* oat_file) {
751 bool oat_file_valid = CheckOatFile<ElfFileImpl, patch_loc_t>(oat_file);
752 CHECK(oat_file_valid) << "Oat file invalid";
753 auto patches_sec = oat_file->FindSectionByName(".oat_patches");
754 patch_loc_t* patches = reinterpret_cast<patch_loc_t*>(oat_file->Begin() + patches_sec->sh_offset);
755 patch_loc_t* patches_end = patches + (patches_sec->sh_size / sizeof(patch_loc_t));
756 auto oat_text_sec = oat_file->FindSectionByName(".text");
Alex Light53cb16b2014-06-12 11:26:29 -0700757 CHECK(oat_text_sec != nullptr);
Ian Rogers13735952014-10-08 12:43:28 -0700758 uint8_t* to_patch = oat_file->Begin() + oat_text_sec->sh_offset;
Alex Light53cb16b2014-06-12 11:26:29 -0700759 uintptr_t to_patch_end = reinterpret_cast<uintptr_t>(to_patch) + oat_text_sec->sh_size;
760
761 for (; patches < patches_end; patches++) {
762 CHECK_LT(*patches, oat_text_sec->sh_size) << "Bad Patch";
763 uint32_t* patch_loc = reinterpret_cast<uint32_t*>(to_patch + *patches);
764 CHECK_LT(reinterpret_cast<uintptr_t>(patch_loc), to_patch_end);
765 *patch_loc += delta_;
766 }
Alex Light53cb16b2014-06-12 11:26:29 -0700767 return true;
768}
769
770static int orig_argc;
771static char** orig_argv;
772
773static std::string CommandLine() {
774 std::vector<std::string> command;
775 for (int i = 0; i < orig_argc; ++i) {
776 command.push_back(orig_argv[i]);
777 }
778 return Join(command, ' ');
779}
780
781static void UsageErrorV(const char* fmt, va_list ap) {
782 std::string error;
783 StringAppendV(&error, fmt, ap);
784 LOG(ERROR) << error;
785}
786
787static void UsageError(const char* fmt, ...) {
788 va_list ap;
789 va_start(ap, fmt);
790 UsageErrorV(fmt, ap);
791 va_end(ap);
792}
793
Ian Rogers7223d442014-10-10 20:05:39 -0700794[[noreturn]] static void Usage(const char *fmt, ...) {
Alex Light53cb16b2014-06-12 11:26:29 -0700795 va_list ap;
796 va_start(ap, fmt);
797 UsageErrorV(fmt, ap);
798 va_end(ap);
799
800 UsageError("Command: %s", CommandLine().c_str());
801 UsageError("Usage: patchoat [options]...");
802 UsageError("");
803 UsageError(" --instruction-set=<isa>: Specifies the instruction set the patched code is");
804 UsageError(" compiled for. Required if you use --input-oat-location");
805 UsageError("");
806 UsageError(" --input-oat-file=<file.oat>: Specifies the exact filename of the oat file to be");
807 UsageError(" patched.");
808 UsageError("");
809 UsageError(" --input-oat-fd=<file-descriptor>: Specifies the file-descriptor of the oat file");
810 UsageError(" to be patched.");
811 UsageError("");
812 UsageError(" --input-oat-location=<file.oat>: Specifies the 'location' to read the patched");
813 UsageError(" oat file from. If used one must also supply the --instruction-set");
814 UsageError("");
815 UsageError(" --input-image-location=<file.art>: Specifies the 'location' of the image file to");
816 UsageError(" be patched. If --instruction-set is not given it will use the instruction set");
817 UsageError(" extracted from the --input-oat-file.");
818 UsageError("");
819 UsageError(" --output-oat-file=<file.oat>: Specifies the exact file to write the patched oat");
820 UsageError(" file to.");
821 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700822 UsageError(" --output-oat-fd=<file-descriptor>: Specifies the file-descriptor to write the");
823 UsageError(" the patched oat file to.");
824 UsageError("");
825 UsageError(" --output-image-file=<file.art>: Specifies the exact file to write the patched");
826 UsageError(" image file to.");
827 UsageError("");
828 UsageError(" --output-image-fd=<file-descriptor>: Specifies the file-descriptor to write the");
829 UsageError(" the patched image file to.");
830 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700831 UsageError(" --orig-base-offset=<original-base-offset>: Specify the base offset the input file");
832 UsageError(" was compiled with. This is needed if one is specifying a --base-offset");
833 UsageError("");
834 UsageError(" --base-offset=<new-base-offset>: Specify the base offset we will repatch the");
835 UsageError(" given files to use. This requires that --orig-base-offset is also given.");
836 UsageError("");
837 UsageError(" --base-offset-delta=<delta>: Specify the amount to change the old base-offset by.");
838 UsageError(" This value may be negative.");
839 UsageError("");
840 UsageError(" --patched-image-file=<file.art>: Use the same patch delta as was used to patch");
841 UsageError(" the given image file.");
842 UsageError("");
843 UsageError(" --patched-image-location=<file.art>: Use the same patch delta as was used to");
844 UsageError(" patch the given image location. If used one must also specify the");
Alex Lighta59dd802014-07-02 16:28:08 -0700845 UsageError(" --instruction-set flag. It will search for this image in the same way that");
846 UsageError(" is done when loading one.");
Alex Light53cb16b2014-06-12 11:26:29 -0700847 UsageError("");
Alex Lightcf4bf382014-07-24 11:29:14 -0700848 UsageError(" --lock-output: Obtain a flock on output oat file before starting.");
849 UsageError("");
850 UsageError(" --no-lock-output: Do not attempt to obtain a flock on output oat file.");
851 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700852 UsageError(" --dump-timings: dump out patch timing information");
853 UsageError("");
854 UsageError(" --no-dump-timings: do not dump out patch timing information");
855 UsageError("");
856
857 exit(EXIT_FAILURE);
858}
859
Alex Lighteefbe392014-07-08 09:53:18 -0700860static bool ReadBaseDelta(const char* name, off_t* delta, std::string* error_msg) {
Alex Light53cb16b2014-06-12 11:26:29 -0700861 CHECK(name != nullptr);
862 CHECK(delta != nullptr);
863 std::unique_ptr<File> file;
864 if (OS::FileExists(name)) {
865 file.reset(OS::OpenFileForReading(name));
866 if (file.get() == nullptr) {
Alex Lighteefbe392014-07-08 09:53:18 -0700867 *error_msg = "Failed to open file %s for reading";
Alex Light53cb16b2014-06-12 11:26:29 -0700868 return false;
869 }
870 } else {
Alex Lighteefbe392014-07-08 09:53:18 -0700871 *error_msg = "File %s does not exist";
Alex Light53cb16b2014-06-12 11:26:29 -0700872 return false;
873 }
874 CHECK(file.get() != nullptr);
875 ImageHeader hdr;
876 if (sizeof(hdr) != file->Read(reinterpret_cast<char*>(&hdr), sizeof(hdr), 0)) {
Alex Lighteefbe392014-07-08 09:53:18 -0700877 *error_msg = "Failed to read file %s";
Alex Light53cb16b2014-06-12 11:26:29 -0700878 return false;
879 }
880 if (!hdr.IsValid()) {
Alex Lighteefbe392014-07-08 09:53:18 -0700881 *error_msg = "%s does not contain a valid image header.";
Alex Light53cb16b2014-06-12 11:26:29 -0700882 return false;
883 }
884 *delta = hdr.GetPatchDelta();
885 return true;
886}
887
888static File* CreateOrOpen(const char* name, bool* created) {
889 if (OS::FileExists(name)) {
890 *created = false;
891 return OS::OpenFileReadWrite(name);
892 } else {
893 *created = true;
Alex Lightcf4bf382014-07-24 11:29:14 -0700894 std::unique_ptr<File> f(OS::CreateEmptyFile(name));
895 if (f.get() != nullptr) {
896 if (fchmod(f->Fd(), 0644) != 0) {
897 PLOG(ERROR) << "Unable to make " << name << " world readable";
Brian Carlstrom8c52a3f2014-09-30 16:18:01 -0700898 TEMP_FAILURE_RETRY(unlink(name));
Alex Lightcf4bf382014-07-24 11:29:14 -0700899 return nullptr;
900 }
901 }
902 return f.release();
Alex Light53cb16b2014-06-12 11:26:29 -0700903 }
904}
905
Alex Lighteefbe392014-07-08 09:53:18 -0700906static int patchoat(int argc, char **argv) {
Alex Light53cb16b2014-06-12 11:26:29 -0700907 InitLogging(argv);
Mathieu Chartier6e88ef62014-10-14 15:01:24 -0700908 MemMap::Init();
Alex Light53cb16b2014-06-12 11:26:29 -0700909 const bool debug = kIsDebugBuild;
910 orig_argc = argc;
911 orig_argv = argv;
912 TimingLogger timings("patcher", false, false);
913
914 InitLogging(argv);
915
916 // Skip over the command name.
917 argv++;
918 argc--;
919
920 if (argc == 0) {
921 Usage("No arguments specified");
922 }
923
924 timings.StartTiming("Patchoat");
925
926 // cmd line args
927 bool isa_set = false;
928 InstructionSet isa = kNone;
929 std::string input_oat_filename;
930 std::string input_oat_location;
931 int input_oat_fd = -1;
932 bool have_input_oat = false;
933 std::string input_image_location;
934 std::string output_oat_filename;
Alex Light53cb16b2014-06-12 11:26:29 -0700935 int output_oat_fd = -1;
936 bool have_output_oat = false;
937 std::string output_image_filename;
Alex Light53cb16b2014-06-12 11:26:29 -0700938 int output_image_fd = -1;
939 bool have_output_image = false;
940 uintptr_t base_offset = 0;
941 bool base_offset_set = false;
942 uintptr_t orig_base_offset = 0;
943 bool orig_base_offset_set = false;
944 off_t base_delta = 0;
945 bool base_delta_set = false;
946 std::string patched_image_filename;
947 std::string patched_image_location;
948 bool dump_timings = kIsDebugBuild;
Alex Lightcf4bf382014-07-24 11:29:14 -0700949 bool lock_output = true;
Alex Light53cb16b2014-06-12 11:26:29 -0700950
Ian Rogersd4c4d952014-10-16 20:31:53 -0700951 for (int i = 0; i < argc; ++i) {
Alex Light53cb16b2014-06-12 11:26:29 -0700952 const StringPiece option(argv[i]);
953 const bool log_options = false;
954 if (log_options) {
955 LOG(INFO) << "patchoat: option[" << i << "]=" << argv[i];
956 }
Alex Light53cb16b2014-06-12 11:26:29 -0700957 if (option.starts_with("--instruction-set=")) {
958 isa_set = true;
959 const char* isa_str = option.substr(strlen("--instruction-set=")).data();
Andreas Gampe20c89302014-08-19 17:28:06 -0700960 isa = GetInstructionSetFromString(isa_str);
961 if (isa == kNone) {
962 Usage("Unknown or invalid instruction set %s", isa_str);
Alex Light53cb16b2014-06-12 11:26:29 -0700963 }
964 } else if (option.starts_with("--input-oat-location=")) {
965 if (have_input_oat) {
966 Usage("Only one of --input-oat-file, --input-oat-location and --input-oat-fd may be used.");
967 }
968 have_input_oat = true;
969 input_oat_location = option.substr(strlen("--input-oat-location=")).data();
970 } else if (option.starts_with("--input-oat-file=")) {
971 if (have_input_oat) {
972 Usage("Only one of --input-oat-file, --input-oat-location and --input-oat-fd may be used.");
973 }
974 have_input_oat = true;
975 input_oat_filename = option.substr(strlen("--input-oat-file=")).data();
976 } else if (option.starts_with("--input-oat-fd=")) {
977 if (have_input_oat) {
978 Usage("Only one of --input-oat-file, --input-oat-location and --input-oat-fd may be used.");
979 }
980 have_input_oat = true;
981 const char* oat_fd_str = option.substr(strlen("--input-oat-fd=")).data();
982 if (!ParseInt(oat_fd_str, &input_oat_fd)) {
983 Usage("Failed to parse --input-oat-fd argument '%s' as an integer", oat_fd_str);
984 }
985 if (input_oat_fd < 0) {
986 Usage("--input-oat-fd pass a negative value %d", input_oat_fd);
987 }
988 } else if (option.starts_with("--input-image-location=")) {
989 input_image_location = option.substr(strlen("--input-image-location=")).data();
Alex Light53cb16b2014-06-12 11:26:29 -0700990 } else if (option.starts_with("--output-oat-file=")) {
991 if (have_output_oat) {
Alex Lightcf4bf382014-07-24 11:29:14 -0700992 Usage("Only one of --output-oat-file, and --output-oat-fd may be used.");
Alex Light53cb16b2014-06-12 11:26:29 -0700993 }
994 have_output_oat = true;
995 output_oat_filename = option.substr(strlen("--output-oat-file=")).data();
996 } else if (option.starts_with("--output-oat-fd=")) {
997 if (have_output_oat) {
Alex Lightcf4bf382014-07-24 11:29:14 -0700998 Usage("Only one of --output-oat-file, --output-oat-fd may be used.");
Alex Light53cb16b2014-06-12 11:26:29 -0700999 }
1000 have_output_oat = true;
1001 const char* oat_fd_str = option.substr(strlen("--output-oat-fd=")).data();
1002 if (!ParseInt(oat_fd_str, &output_oat_fd)) {
1003 Usage("Failed to parse --output-oat-fd argument '%s' as an integer", oat_fd_str);
1004 }
1005 if (output_oat_fd < 0) {
1006 Usage("--output-oat-fd pass a negative value %d", output_oat_fd);
1007 }
Alex Light53cb16b2014-06-12 11:26:29 -07001008 } else if (option.starts_with("--output-image-file=")) {
1009 if (have_output_image) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001010 Usage("Only one of --output-image-file, and --output-image-fd may be used.");
Alex Light53cb16b2014-06-12 11:26:29 -07001011 }
1012 have_output_image = true;
1013 output_image_filename = option.substr(strlen("--output-image-file=")).data();
1014 } else if (option.starts_with("--output-image-fd=")) {
1015 if (have_output_image) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001016 Usage("Only one of --output-image-file, and --output-image-fd may be used.");
Alex Light53cb16b2014-06-12 11:26:29 -07001017 }
1018 have_output_image = true;
1019 const char* image_fd_str = option.substr(strlen("--output-image-fd=")).data();
1020 if (!ParseInt(image_fd_str, &output_image_fd)) {
1021 Usage("Failed to parse --output-image-fd argument '%s' as an integer", image_fd_str);
1022 }
1023 if (output_image_fd < 0) {
1024 Usage("--output-image-fd pass a negative value %d", output_image_fd);
1025 }
1026 } else if (option.starts_with("--orig-base-offset=")) {
1027 const char* orig_base_offset_str = option.substr(strlen("--orig-base-offset=")).data();
1028 orig_base_offset_set = true;
1029 if (!ParseUint(orig_base_offset_str, &orig_base_offset)) {
1030 Usage("Failed to parse --orig-base-offset argument '%s' as an uintptr_t",
1031 orig_base_offset_str);
1032 }
1033 } else if (option.starts_with("--base-offset=")) {
1034 const char* base_offset_str = option.substr(strlen("--base-offset=")).data();
1035 base_offset_set = true;
1036 if (!ParseUint(base_offset_str, &base_offset)) {
1037 Usage("Failed to parse --base-offset argument '%s' as an uintptr_t", base_offset_str);
1038 }
1039 } else if (option.starts_with("--base-offset-delta=")) {
1040 const char* base_delta_str = option.substr(strlen("--base-offset-delta=")).data();
1041 base_delta_set = true;
1042 if (!ParseInt(base_delta_str, &base_delta)) {
1043 Usage("Failed to parse --base-offset-delta argument '%s' as an off_t", base_delta_str);
1044 }
1045 } else if (option.starts_with("--patched-image-location=")) {
1046 patched_image_location = option.substr(strlen("--patched-image-location=")).data();
1047 } else if (option.starts_with("--patched-image-file=")) {
1048 patched_image_filename = option.substr(strlen("--patched-image-file=")).data();
Alex Lightcf4bf382014-07-24 11:29:14 -07001049 } else if (option == "--lock-output") {
1050 lock_output = true;
1051 } else if (option == "--no-lock-output") {
1052 lock_output = false;
Alex Light53cb16b2014-06-12 11:26:29 -07001053 } else if (option == "--dump-timings") {
1054 dump_timings = true;
1055 } else if (option == "--no-dump-timings") {
1056 dump_timings = false;
1057 } else {
1058 Usage("Unknown argument %s", option.data());
1059 }
1060 }
1061
1062 {
1063 // Only 1 of these may be set.
1064 uint32_t cnt = 0;
1065 cnt += (base_delta_set) ? 1 : 0;
1066 cnt += (base_offset_set && orig_base_offset_set) ? 1 : 0;
1067 cnt += (!patched_image_filename.empty()) ? 1 : 0;
1068 cnt += (!patched_image_location.empty()) ? 1 : 0;
1069 if (cnt > 1) {
1070 Usage("Only one of --base-offset/--orig-base-offset, --base-offset-delta, "
1071 "--patched-image-filename or --patched-image-location may be used.");
1072 } else if (cnt == 0) {
1073 Usage("Must specify --base-offset-delta, --base-offset and --orig-base-offset, "
1074 "--patched-image-location or --patched-image-file");
1075 }
1076 }
1077
1078 if (have_input_oat != have_output_oat) {
1079 Usage("Either both input and output oat must be supplied or niether must be.");
1080 }
1081
1082 if ((!input_image_location.empty()) != have_output_image) {
1083 Usage("Either both input and output image must be supplied or niether must be.");
1084 }
1085
1086 // We know we have both the input and output so rename for clarity.
1087 bool have_image_files = have_output_image;
1088 bool have_oat_files = have_output_oat;
1089
1090 if (!have_oat_files && !have_image_files) {
1091 Usage("Must be patching either an oat or an image file or both.");
1092 }
1093
1094 if (!have_oat_files && !isa_set) {
1095 Usage("Must include ISA if patching an image file without an oat file.");
1096 }
1097
1098 if (!input_oat_location.empty()) {
1099 if (!isa_set) {
1100 Usage("specifying a location requires specifying an instruction set");
1101 }
Alex Lightcf4bf382014-07-24 11:29:14 -07001102 if (!LocationToFilename(input_oat_location, isa, &input_oat_filename)) {
1103 Usage("Unable to find filename for input oat location %s", input_oat_location.c_str());
1104 }
Alex Light53cb16b2014-06-12 11:26:29 -07001105 if (debug) {
1106 LOG(INFO) << "Using input-oat-file " << input_oat_filename;
1107 }
1108 }
Alex Light53cb16b2014-06-12 11:26:29 -07001109 if (!patched_image_location.empty()) {
1110 if (!isa_set) {
1111 Usage("specifying a location requires specifying an instruction set");
1112 }
Alex Lighta59dd802014-07-02 16:28:08 -07001113 std::string system_filename;
1114 bool has_system = false;
1115 std::string cache_filename;
1116 bool has_cache = false;
1117 bool has_android_data_unused = false;
Andreas Gampe3c13a792014-09-18 20:56:04 -07001118 bool is_global_cache = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001119 if (!gc::space::ImageSpace::FindImageFilename(patched_image_location.c_str(), isa,
1120 &system_filename, &has_system, &cache_filename,
Andreas Gampe3c13a792014-09-18 20:56:04 -07001121 &has_android_data_unused, &has_cache,
1122 &is_global_cache)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001123 Usage("Unable to determine image file for location %s", patched_image_location.c_str());
1124 }
1125 if (has_cache) {
1126 patched_image_filename = cache_filename;
1127 } else if (has_system) {
1128 LOG(WARNING) << "Only image file found was in /system for image location "
1129 << patched_image_location;
1130 patched_image_filename = system_filename;
1131 } else {
1132 Usage("Unable to determine image file for location %s", patched_image_location.c_str());
1133 }
Alex Light53cb16b2014-06-12 11:26:29 -07001134 if (debug) {
1135 LOG(INFO) << "Using patched-image-file " << patched_image_filename;
1136 }
1137 }
1138
1139 if (!base_delta_set) {
1140 if (orig_base_offset_set && base_offset_set) {
1141 base_delta_set = true;
1142 base_delta = base_offset - orig_base_offset;
1143 } else if (!patched_image_filename.empty()) {
1144 base_delta_set = true;
1145 std::string error_msg;
Alex Lighteefbe392014-07-08 09:53:18 -07001146 if (!ReadBaseDelta(patched_image_filename.c_str(), &base_delta, &error_msg)) {
Alex Light53cb16b2014-06-12 11:26:29 -07001147 Usage(error_msg.c_str(), patched_image_filename.c_str());
1148 }
1149 } else {
1150 if (base_offset_set) {
1151 Usage("Unable to determine original base offset.");
1152 } else {
1153 Usage("Must supply a desired new offset or delta.");
1154 }
1155 }
1156 }
1157
1158 if (!IsAligned<kPageSize>(base_delta)) {
1159 Usage("Base offset/delta must be alligned to a pagesize (0x%08x) boundary.", kPageSize);
1160 }
1161
1162 // Do we need to cleanup output files if we fail?
1163 bool new_image_out = false;
1164 bool new_oat_out = false;
1165
1166 std::unique_ptr<File> input_oat;
1167 std::unique_ptr<File> output_oat;
1168 std::unique_ptr<File> output_image;
1169
1170 if (have_image_files) {
1171 CHECK(!input_image_location.empty());
1172
1173 if (output_image_fd != -1) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001174 if (output_image_filename.empty()) {
1175 output_image_filename = "output-image-file";
1176 }
Alex Light53cb16b2014-06-12 11:26:29 -07001177 output_image.reset(new File(output_image_fd, output_image_filename));
1178 } else {
1179 CHECK(!output_image_filename.empty());
1180 output_image.reset(CreateOrOpen(output_image_filename.c_str(), &new_image_out));
1181 }
1182 } else {
1183 CHECK(output_image_filename.empty() && output_image_fd == -1 && input_image_location.empty());
1184 }
1185
1186 if (have_oat_files) {
1187 if (input_oat_fd != -1) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001188 if (input_oat_filename.empty()) {
1189 input_oat_filename = "input-oat-file";
1190 }
Alex Light53cb16b2014-06-12 11:26:29 -07001191 input_oat.reset(new File(input_oat_fd, input_oat_filename));
Igor Murashkin46774762014-10-22 11:37:02 -07001192 if (input_oat == nullptr) {
1193 // Unlikely, but ensure exhaustive logging in non-0 exit code case
1194 LOG(ERROR) << "Failed to open input oat file by its FD" << input_oat_fd;
1195 }
Alex Light53cb16b2014-06-12 11:26:29 -07001196 } else {
1197 CHECK(!input_oat_filename.empty());
1198 input_oat.reset(OS::OpenFileForReading(input_oat_filename.c_str()));
Igor Murashkin46774762014-10-22 11:37:02 -07001199 if (input_oat == nullptr) {
1200 int err = errno;
1201 LOG(ERROR) << "Failed to open input oat file " << input_oat_filename
1202 << ": " << strerror(err) << "(" << err << ")";
Andreas Gampe1c83cbc2014-07-22 18:52:29 -07001203 }
Alex Light53cb16b2014-06-12 11:26:29 -07001204 }
1205
1206 if (output_oat_fd != -1) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001207 if (output_oat_filename.empty()) {
1208 output_oat_filename = "output-oat-file";
Alex Lighta59dd802014-07-02 16:28:08 -07001209 }
Alex Lightcf4bf382014-07-24 11:29:14 -07001210 output_oat.reset(new File(output_oat_fd, output_oat_filename));
Igor Murashkin46774762014-10-22 11:37:02 -07001211 if (output_oat == nullptr) {
1212 // Unlikely, but ensure exhaustive logging in non-0 exit code case
1213 LOG(ERROR) << "Failed to open output oat file by its FD" << output_oat_fd;
1214 }
Alex Light53cb16b2014-06-12 11:26:29 -07001215 } else {
1216 CHECK(!output_oat_filename.empty());
1217 output_oat.reset(CreateOrOpen(output_oat_filename.c_str(), &new_oat_out));
Igor Murashkin46774762014-10-22 11:37:02 -07001218 if (output_oat == nullptr) {
1219 int err = errno;
1220 LOG(ERROR) << "Failed to open output oat file " << output_oat_filename
1221 << ": " << strerror(err) << "(" << err << ")";
1222 }
Alex Light53cb16b2014-06-12 11:26:29 -07001223 }
1224 }
1225
Igor Murashkin46774762014-10-22 11:37:02 -07001226 // TODO: get rid of this.
Alex Light53cb16b2014-06-12 11:26:29 -07001227 auto cleanup = [&output_image_filename, &output_oat_filename,
1228 &new_oat_out, &new_image_out, &timings, &dump_timings](bool success) {
1229 timings.EndTiming();
1230 if (!success) {
1231 if (new_oat_out) {
1232 CHECK(!output_oat_filename.empty());
Brian Carlstrom8c52a3f2014-09-30 16:18:01 -07001233 TEMP_FAILURE_RETRY(unlink(output_oat_filename.c_str()));
Alex Light53cb16b2014-06-12 11:26:29 -07001234 }
1235 if (new_image_out) {
1236 CHECK(!output_image_filename.empty());
Brian Carlstrom8c52a3f2014-09-30 16:18:01 -07001237 TEMP_FAILURE_RETRY(unlink(output_image_filename.c_str()));
Alex Light53cb16b2014-06-12 11:26:29 -07001238 }
1239 }
1240 if (dump_timings) {
1241 LOG(INFO) << Dumpable<TimingLogger>(timings);
1242 }
Igor Murashkin46774762014-10-22 11:37:02 -07001243
1244 if (kIsDebugBuild) {
1245 LOG(INFO) << "Cleaning up.. success? " << success;
1246 }
Alex Light53cb16b2014-06-12 11:26:29 -07001247 };
1248
Igor Murashkin46774762014-10-22 11:37:02 -07001249 if (have_oat_files && (input_oat.get() == nullptr || output_oat.get() == nullptr)) {
1250 LOG(ERROR) << "Failed to open input/output oat files";
1251 cleanup(false);
1252 return EXIT_FAILURE;
1253 } else if (have_image_files && output_image.get() == nullptr) {
1254 LOG(ERROR) << "Failed to open output image file";
Alex Lightcf4bf382014-07-24 11:29:14 -07001255 cleanup(false);
1256 return EXIT_FAILURE;
1257 }
1258
Igor Murashkin46774762014-10-22 11:37:02 -07001259 if (debug) {
1260 LOG(INFO) << "moving offset by " << base_delta
1261 << " (0x" << std::hex << base_delta << ") bytes or "
1262 << std::dec << (base_delta/kPageSize) << " pages.";
1263 }
1264
1265 // TODO: is it going to be promatic to unlink a file that was flock-ed?
Alex Lightcf4bf382014-07-24 11:29:14 -07001266 ScopedFlock output_oat_lock;
1267 if (lock_output) {
1268 std::string error_msg;
1269 if (have_oat_files && !output_oat_lock.Init(output_oat.get(), &error_msg)) {
1270 LOG(ERROR) << "Unable to lock output oat " << output_image->GetPath() << ": " << error_msg;
1271 cleanup(false);
1272 return EXIT_FAILURE;
1273 }
1274 }
1275
Alex Light53cb16b2014-06-12 11:26:29 -07001276 bool ret;
1277 if (have_image_files && have_oat_files) {
1278 TimingLogger::ScopedTiming pt("patch image and oat", &timings);
1279 ret = PatchOat::Patch(input_oat.get(), input_image_location, base_delta,
Igor Murashkin46774762014-10-22 11:37:02 -07001280 output_oat.get(), output_image.get(), isa, &timings,
1281 output_oat_fd >= 0, // was it opened from FD?
1282 new_oat_out);
Alex Light53cb16b2014-06-12 11:26:29 -07001283 } else if (have_oat_files) {
1284 TimingLogger::ScopedTiming pt("patch oat", &timings);
Igor Murashkin46774762014-10-22 11:37:02 -07001285 ret = PatchOat::Patch(input_oat.get(), base_delta, output_oat.get(), &timings,
1286 output_oat_fd >= 0, // was it opened from FD?
1287 new_oat_out);
1288 } else if (have_image_files) {
Alex Light53cb16b2014-06-12 11:26:29 -07001289 TimingLogger::ScopedTiming pt("patch image", &timings);
Alex Lighteefbe392014-07-08 09:53:18 -07001290 ret = PatchOat::Patch(input_image_location, base_delta, output_image.get(), isa, &timings);
Igor Murashkin46774762014-10-22 11:37:02 -07001291 } else {
1292 CHECK(false);
1293 ret = true;
1294 }
1295
1296 if (kIsDebugBuild) {
1297 LOG(INFO) << "Exiting with return ... " << ret;
Alex Light53cb16b2014-06-12 11:26:29 -07001298 }
1299 cleanup(ret);
Alex Light53cb16b2014-06-12 11:26:29 -07001300 return (ret) ? EXIT_SUCCESS : EXIT_FAILURE;
1301}
1302
1303} // namespace art
1304
1305int main(int argc, char **argv) {
1306 return art::patchoat(argc, argv);
1307}