blob: 28f966826b09b60e568724c942d0cf31c2297acf [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
Andreas Gampec5a3ea72015-01-13 16:41:53 -080051static InstructionSet ElfISAToInstructionSet(Elf32_Word isa, Elf32_Word e_flags) {
Alex Light53cb16b2014-06-12 11:26:29 -070052 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:
Andreas Gampec5a3ea72015-01-13 16:41:53 -080062 if (((e_flags & EF_MIPS_ARCH) == EF_MIPS_ARCH_32R2) ||
63 ((e_flags & EF_MIPS_ARCH) == EF_MIPS_ARCH_32R6)) {
64 return kMips;
65 } else {
66 return kNone;
67 }
Alex Light53cb16b2014-06-12 11:26:29 -070068 default:
69 return kNone;
70 }
71}
72
Alex Lightcf4bf382014-07-24 11:29:14 -070073static bool LocationToFilename(const std::string& location, InstructionSet isa,
74 std::string* filename) {
75 bool has_system = false;
76 bool has_cache = false;
77 // image_location = /system/framework/boot.art
Igor Murashkin46774762014-10-22 11:37:02 -070078 // system_image_filename = /system/framework/<image_isa>/boot.art
Alex Lightcf4bf382014-07-24 11:29:14 -070079 std::string system_filename(GetSystemImageFilename(location.c_str(), isa));
80 if (OS::FileExists(system_filename.c_str())) {
81 has_system = true;
82 }
83
84 bool have_android_data = false;
85 bool dalvik_cache_exists = false;
Andreas Gampe3c13a792014-09-18 20:56:04 -070086 bool is_global_cache = false;
Alex Lightcf4bf382014-07-24 11:29:14 -070087 std::string dalvik_cache;
88 GetDalvikCache(GetInstructionSetString(isa), false, &dalvik_cache,
Andreas Gampe3c13a792014-09-18 20:56:04 -070089 &have_android_data, &dalvik_cache_exists, &is_global_cache);
Alex Lightcf4bf382014-07-24 11:29:14 -070090
91 std::string cache_filename;
92 if (have_android_data && dalvik_cache_exists) {
93 // Always set output location even if it does not exist,
94 // so that the caller knows where to create the image.
95 //
96 // image_location = /system/framework/boot.art
97 // *image_filename = /data/dalvik-cache/<image_isa>/boot.art
98 std::string error_msg;
99 if (GetDalvikCacheFilename(location.c_str(), dalvik_cache.c_str(),
100 &cache_filename, &error_msg)) {
101 has_cache = true;
102 }
103 }
104 if (has_system) {
105 *filename = system_filename;
106 return true;
107 } else if (has_cache) {
108 *filename = cache_filename;
109 return true;
110 } else {
111 return false;
112 }
113}
114
Alex Light53cb16b2014-06-12 11:26:29 -0700115bool PatchOat::Patch(const std::string& image_location, off_t delta,
116 File* output_image, InstructionSet isa,
Alex Lighteefbe392014-07-08 09:53:18 -0700117 TimingLogger* timings) {
Alex Light53cb16b2014-06-12 11:26:29 -0700118 CHECK(Runtime::Current() == nullptr);
119 CHECK(output_image != nullptr);
120 CHECK_GE(output_image->Fd(), 0);
121 CHECK(!image_location.empty()) << "image file must have a filename.";
122 CHECK_NE(isa, kNone);
123
Alex Lighteefbe392014-07-08 09:53:18 -0700124 TimingLogger::ScopedTiming t("Runtime Setup", timings);
Alex Light53cb16b2014-06-12 11:26:29 -0700125 const char *isa_name = GetInstructionSetString(isa);
Alex Lightcf4bf382014-07-24 11:29:14 -0700126 std::string image_filename;
127 if (!LocationToFilename(image_location, isa, &image_filename)) {
128 LOG(ERROR) << "Unable to find image at location " << image_location;
129 return false;
130 }
Alex Light53cb16b2014-06-12 11:26:29 -0700131 std::unique_ptr<File> input_image(OS::OpenFileForReading(image_filename.c_str()));
132 if (input_image.get() == nullptr) {
Alex Lightcf4bf382014-07-24 11:29:14 -0700133 LOG(ERROR) << "unable to open input image file at " << image_filename
134 << " for location " << image_location;
Alex Light53cb16b2014-06-12 11:26:29 -0700135 return false;
136 }
Igor Murashkin46774762014-10-22 11:37:02 -0700137
Alex Light53cb16b2014-06-12 11:26:29 -0700138 int64_t image_len = input_image->GetLength();
139 if (image_len < 0) {
140 LOG(ERROR) << "Error while getting image length";
141 return false;
142 }
143 ImageHeader image_header;
144 if (sizeof(image_header) != input_image->Read(reinterpret_cast<char*>(&image_header),
145 sizeof(image_header), 0)) {
146 LOG(ERROR) << "Unable to read image header from image file " << input_image->GetPath();
147 return false;
148 }
149
Igor Murashkin46774762014-10-22 11:37:02 -0700150 /*bool is_image_pic = */IsImagePic(image_header, input_image->GetPath());
151 // Nothing special to do right now since the image always needs to get patched.
152 // Perhaps in some far-off future we may have images with relative addresses that are true-PIC.
153
Alex Light53cb16b2014-06-12 11:26:29 -0700154 // Set up the runtime
Ian Rogerse63db272014-07-15 15:36:11 -0700155 RuntimeOptions options;
Alex Light53cb16b2014-06-12 11:26:29 -0700156 NoopCompilerCallbacks callbacks;
157 options.push_back(std::make_pair("compilercallbacks", &callbacks));
158 std::string img = "-Ximage:" + image_location;
159 options.push_back(std::make_pair(img.c_str(), nullptr));
160 options.push_back(std::make_pair("imageinstructionset", reinterpret_cast<const void*>(isa_name)));
161 if (!Runtime::Create(options, false)) {
162 LOG(ERROR) << "Unable to initialize runtime";
163 return false;
164 }
165 // Runtime::Create acquired the mutator_lock_ that is normally given away when we Runtime::Start,
166 // give it away now and then switch to a more manageable ScopedObjectAccess.
167 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
168 ScopedObjectAccess soa(Thread::Current());
169
170 t.NewTiming("Image and oat Patching setup");
171 // Create the map where we will write the image patches to.
Alex Lighteefbe392014-07-08 09:53:18 -0700172 std::string error_msg;
Alex Light53cb16b2014-06-12 11:26:29 -0700173 std::unique_ptr<MemMap> image(MemMap::MapFile(image_len, PROT_READ | PROT_WRITE, MAP_PRIVATE,
174 input_image->Fd(), 0,
175 input_image->GetPath().c_str(),
176 &error_msg));
177 if (image.get() == nullptr) {
178 LOG(ERROR) << "unable to map image file " << input_image->GetPath() << " : " << error_msg;
179 return false;
180 }
181 gc::space::ImageSpace* ispc = Runtime::Current()->GetHeap()->GetImageSpace();
182
Mathieu Chartier2d721012014-11-10 11:08:06 -0800183 PatchOat p(isa, image.release(), ispc->GetLiveBitmap(), ispc->GetMemMap(),
Alex Light53cb16b2014-06-12 11:26:29 -0700184 delta, timings);
185 t.NewTiming("Patching files");
186 if (!p.PatchImage()) {
Alex Lighta59dd802014-07-02 16:28:08 -0700187 LOG(ERROR) << "Failed to patch image file " << input_image->GetPath();
Alex Light53cb16b2014-06-12 11:26:29 -0700188 return false;
189 }
190
191 t.NewTiming("Writing files");
192 if (!p.WriteImage(output_image)) {
193 return false;
194 }
195 return true;
196}
197
Igor Murashkin46774762014-10-22 11:37:02 -0700198bool PatchOat::Patch(File* input_oat, const std::string& image_location, off_t delta,
Alex Light53cb16b2014-06-12 11:26:29 -0700199 File* output_oat, File* output_image, InstructionSet isa,
Igor Murashkin46774762014-10-22 11:37:02 -0700200 TimingLogger* timings,
201 bool output_oat_opened_from_fd,
202 bool new_oat_out) {
Alex Light53cb16b2014-06-12 11:26:29 -0700203 CHECK(Runtime::Current() == nullptr);
204 CHECK(output_image != nullptr);
205 CHECK_GE(output_image->Fd(), 0);
206 CHECK(input_oat != nullptr);
207 CHECK(output_oat != nullptr);
208 CHECK_GE(input_oat->Fd(), 0);
209 CHECK_GE(output_oat->Fd(), 0);
210 CHECK(!image_location.empty()) << "image file must have a filename.";
211
Alex Lighteefbe392014-07-08 09:53:18 -0700212 TimingLogger::ScopedTiming t("Runtime Setup", timings);
Alex Light53cb16b2014-06-12 11:26:29 -0700213
214 if (isa == kNone) {
215 Elf32_Ehdr elf_hdr;
216 if (sizeof(elf_hdr) != input_oat->Read(reinterpret_cast<char*>(&elf_hdr), sizeof(elf_hdr), 0)) {
217 LOG(ERROR) << "unable to read elf header";
218 return false;
219 }
Andreas Gampec5a3ea72015-01-13 16:41:53 -0800220 isa = ElfISAToInstructionSet(elf_hdr.e_machine, elf_hdr.e_flags);
Alex Light53cb16b2014-06-12 11:26:29 -0700221 }
222 const char* isa_name = GetInstructionSetString(isa);
Alex Lightcf4bf382014-07-24 11:29:14 -0700223 std::string image_filename;
224 if (!LocationToFilename(image_location, isa, &image_filename)) {
225 LOG(ERROR) << "Unable to find image at location " << image_location;
226 return false;
227 }
Alex Light53cb16b2014-06-12 11:26:29 -0700228 std::unique_ptr<File> input_image(OS::OpenFileForReading(image_filename.c_str()));
229 if (input_image.get() == nullptr) {
Alex Lightcf4bf382014-07-24 11:29:14 -0700230 LOG(ERROR) << "unable to open input image file at " << image_filename
231 << " for location " << image_location;
Alex Light53cb16b2014-06-12 11:26:29 -0700232 return false;
233 }
234 int64_t image_len = input_image->GetLength();
235 if (image_len < 0) {
236 LOG(ERROR) << "Error while getting image length";
237 return false;
238 }
239 ImageHeader image_header;
240 if (sizeof(image_header) != input_image->Read(reinterpret_cast<char*>(&image_header),
241 sizeof(image_header), 0)) {
242 LOG(ERROR) << "Unable to read image header from image file " << input_image->GetPath();
243 }
244
Igor Murashkin46774762014-10-22 11:37:02 -0700245 /*bool is_image_pic = */IsImagePic(image_header, input_image->GetPath());
246 // Nothing special to do right now since the image always needs to get patched.
247 // Perhaps in some far-off future we may have images with relative addresses that are true-PIC.
248
Alex Light53cb16b2014-06-12 11:26:29 -0700249 // Set up the runtime
Ian Rogerse63db272014-07-15 15:36:11 -0700250 RuntimeOptions options;
Alex Light53cb16b2014-06-12 11:26:29 -0700251 NoopCompilerCallbacks callbacks;
252 options.push_back(std::make_pair("compilercallbacks", &callbacks));
253 std::string img = "-Ximage:" + image_location;
254 options.push_back(std::make_pair(img.c_str(), nullptr));
255 options.push_back(std::make_pair("imageinstructionset", reinterpret_cast<const void*>(isa_name)));
256 if (!Runtime::Create(options, false)) {
257 LOG(ERROR) << "Unable to initialize runtime";
258 return false;
259 }
260 // Runtime::Create acquired the mutator_lock_ that is normally given away when we Runtime::Start,
261 // give it away now and then switch to a more manageable ScopedObjectAccess.
262 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
263 ScopedObjectAccess soa(Thread::Current());
264
265 t.NewTiming("Image and oat Patching setup");
266 // Create the map where we will write the image patches to.
Alex Lighteefbe392014-07-08 09:53:18 -0700267 std::string error_msg;
Alex Light53cb16b2014-06-12 11:26:29 -0700268 std::unique_ptr<MemMap> image(MemMap::MapFile(image_len, PROT_READ | PROT_WRITE, MAP_PRIVATE,
269 input_image->Fd(), 0,
270 input_image->GetPath().c_str(),
271 &error_msg));
272 if (image.get() == nullptr) {
273 LOG(ERROR) << "unable to map image file " << input_image->GetPath() << " : " << error_msg;
274 return false;
275 }
276 gc::space::ImageSpace* ispc = Runtime::Current()->GetHeap()->GetImageSpace();
277
Igor Murashkin46774762014-10-22 11:37:02 -0700278 std::unique_ptr<ElfFile> elf(ElfFile::Open(input_oat,
Alex Light53cb16b2014-06-12 11:26:29 -0700279 PROT_READ | PROT_WRITE, MAP_PRIVATE, &error_msg));
280 if (elf.get() == nullptr) {
281 LOG(ERROR) << "unable to open oat file " << input_oat->GetPath() << " : " << error_msg;
282 return false;
283 }
284
Igor Murashkin46774762014-10-22 11:37:02 -0700285 bool skip_patching_oat = false;
286 MaybePic is_oat_pic = IsOatPic(elf.get());
287 if (is_oat_pic >= ERROR_FIRST) {
288 // Error logged by IsOatPic
289 return false;
290 } else if (is_oat_pic == PIC) {
291 // Do not need to do ELF-file patching. Create a symlink and skip the ELF patching.
292 if (!ReplaceOatFileWithSymlink(input_oat->GetPath(),
293 output_oat->GetPath(),
294 output_oat_opened_from_fd,
295 new_oat_out)) {
296 // Errors already logged by above call.
297 return false;
298 }
299 // Don't patch the OAT, since we just symlinked it. Image still needs patching.
300 skip_patching_oat = true;
301 } else {
302 CHECK(is_oat_pic == NOT_PIC);
303 }
304
Mathieu Chartier2d721012014-11-10 11:08:06 -0800305 PatchOat p(isa, elf.release(), image.release(), ispc->GetLiveBitmap(), ispc->GetMemMap(),
Alex Light53cb16b2014-06-12 11:26:29 -0700306 delta, timings);
307 t.NewTiming("Patching files");
Igor Murashkin46774762014-10-22 11:37:02 -0700308 if (!skip_patching_oat && !p.PatchElf()) {
Alex Lighta59dd802014-07-02 16:28:08 -0700309 LOG(ERROR) << "Failed to patch oat file " << input_oat->GetPath();
Alex Light53cb16b2014-06-12 11:26:29 -0700310 return false;
311 }
312 if (!p.PatchImage()) {
Alex Lighta59dd802014-07-02 16:28:08 -0700313 LOG(ERROR) << "Failed to patch image file " << input_image->GetPath();
Alex Light53cb16b2014-06-12 11:26:29 -0700314 return false;
315 }
316
317 t.NewTiming("Writing files");
Igor Murashkin46774762014-10-22 11:37:02 -0700318 if (!skip_patching_oat && !p.WriteElf(output_oat)) {
319 LOG(ERROR) << "Failed to write oat file " << input_oat->GetPath();
Alex Light53cb16b2014-06-12 11:26:29 -0700320 return false;
321 }
322 if (!p.WriteImage(output_image)) {
Igor Murashkin46774762014-10-22 11:37:02 -0700323 LOG(ERROR) << "Failed to write image file " << input_image->GetPath();
Alex Light53cb16b2014-06-12 11:26:29 -0700324 return false;
325 }
326 return true;
327}
328
329bool PatchOat::WriteElf(File* out) {
Alex Lighteefbe392014-07-08 09:53:18 -0700330 TimingLogger::ScopedTiming t("Writing Elf File", timings_);
Alex Lighta59dd802014-07-02 16:28:08 -0700331
Alex Light53cb16b2014-06-12 11:26:29 -0700332 CHECK(oat_file_.get() != nullptr);
333 CHECK(out != nullptr);
334 size_t expect = oat_file_->Size();
335 if (out->WriteFully(reinterpret_cast<char*>(oat_file_->Begin()), expect) &&
336 out->SetLength(expect) == 0) {
337 return true;
338 } else {
339 LOG(ERROR) << "Writing to oat file " << out->GetPath() << " failed.";
340 return false;
341 }
342}
343
344bool PatchOat::WriteImage(File* out) {
Alex Lighteefbe392014-07-08 09:53:18 -0700345 TimingLogger::ScopedTiming t("Writing image File", timings_);
Alex Lighta59dd802014-07-02 16:28:08 -0700346 std::string error_msg;
347
Alex Lightcf4bf382014-07-24 11:29:14 -0700348 ScopedFlock img_flock;
349 img_flock.Init(out, &error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -0700350
Alex Light53cb16b2014-06-12 11:26:29 -0700351 CHECK(image_ != nullptr);
352 CHECK(out != nullptr);
353 size_t expect = image_->Size();
354 if (out->WriteFully(reinterpret_cast<char*>(image_->Begin()), expect) &&
355 out->SetLength(expect) == 0) {
356 return true;
357 } else {
358 LOG(ERROR) << "Writing to image file " << out->GetPath() << " failed.";
359 return false;
360 }
361}
362
Igor Murashkin46774762014-10-22 11:37:02 -0700363bool PatchOat::IsImagePic(const ImageHeader& image_header, const std::string& image_path) {
364 if (!image_header.CompilePic()) {
365 if (kIsDebugBuild) {
366 LOG(INFO) << "image at location " << image_path << " was *not* compiled pic";
367 }
368 return false;
369 }
370
371 if (kIsDebugBuild) {
372 LOG(INFO) << "image at location " << image_path << " was compiled PIC";
373 }
374
375 return true;
376}
377
378PatchOat::MaybePic PatchOat::IsOatPic(const ElfFile* oat_in) {
379 if (oat_in == nullptr) {
380 LOG(ERROR) << "No ELF input oat fie available";
381 return ERROR_OAT_FILE;
382 }
383
384 const std::string& file_path = oat_in->GetFile().GetPath();
385
386 const OatHeader* oat_header = GetOatHeader(oat_in);
387 if (oat_header == nullptr) {
388 LOG(ERROR) << "Failed to find oat header in oat file " << file_path;
389 return ERROR_OAT_FILE;
390 }
391
392 if (!oat_header->IsValid()) {
393 LOG(ERROR) << "Elf file " << file_path << " has an invalid oat header";
394 return ERROR_OAT_FILE;
395 }
396
397 bool is_pic = oat_header->IsPic();
398 if (kIsDebugBuild) {
399 LOG(INFO) << "Oat file at " << file_path << " is " << (is_pic ? "PIC" : "not pic");
400 }
401
402 return is_pic ? PIC : NOT_PIC;
403}
404
405bool PatchOat::ReplaceOatFileWithSymlink(const std::string& input_oat_filename,
406 const std::string& output_oat_filename,
407 bool output_oat_opened_from_fd,
408 bool new_oat_out) {
409 // Need a file when we are PIC, since we symlink over it. Refusing to symlink into FD.
410 if (output_oat_opened_from_fd) {
411 // TODO: installd uses --output-oat-fd. Should we change class linking logic for PIC?
412 LOG(ERROR) << "No output oat filename specified, needs filename for when we are PIC";
413 return false;
414 }
415
416 // Image was PIC. Create symlink where the oat is supposed to go.
417 if (!new_oat_out) {
418 LOG(ERROR) << "Oat file " << output_oat_filename << " already exists, refusing to overwrite";
419 return false;
420 }
421
422 // Delete the original file, since we won't need it.
423 TEMP_FAILURE_RETRY(unlink(output_oat_filename.c_str()));
424
425 // Create a symlink from the old oat to the new oat
426 if (symlink(input_oat_filename.c_str(), output_oat_filename.c_str()) < 0) {
427 int err = errno;
428 LOG(ERROR) << "Failed to create symlink at " << output_oat_filename
429 << " error(" << err << "): " << strerror(err);
430 return false;
431 }
432
433 if (kIsDebugBuild) {
434 LOG(INFO) << "Created symlink " << output_oat_filename << " -> " << input_oat_filename;
435 }
436
437 return true;
438}
439
Alex Light53cb16b2014-06-12 11:26:29 -0700440bool PatchOat::PatchImage() {
441 ImageHeader* image_header = reinterpret_cast<ImageHeader*>(image_->Begin());
442 CHECK_GT(image_->Size(), sizeof(ImageHeader));
443 // These are the roots from the original file.
444 mirror::Object* img_roots = image_header->GetImageRoots();
445 image_header->RelocateImage(delta_);
446
447 VisitObject(img_roots);
448 if (!image_header->IsValid()) {
449 LOG(ERROR) << "reloction renders image header invalid";
450 return false;
451 }
452
453 {
Alex Lighteefbe392014-07-08 09:53:18 -0700454 TimingLogger::ScopedTiming t("Walk Bitmap", timings_);
Alex Light53cb16b2014-06-12 11:26:29 -0700455 // Walk the bitmap.
456 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
457 bitmap_->Walk(PatchOat::BitmapCallback, this);
458 }
459 return true;
460}
461
462bool PatchOat::InHeap(mirror::Object* o) {
463 uintptr_t begin = reinterpret_cast<uintptr_t>(heap_->Begin());
464 uintptr_t end = reinterpret_cast<uintptr_t>(heap_->End());
465 uintptr_t obj = reinterpret_cast<uintptr_t>(o);
466 return o == nullptr || (begin <= obj && obj < end);
467}
468
469void PatchOat::PatchVisitor::operator() (mirror::Object* obj, MemberOffset off,
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700470 bool is_static_unused ATTRIBUTE_UNUSED) const {
Alex Light53cb16b2014-06-12 11:26:29 -0700471 mirror::Object* referent = obj->GetFieldObject<mirror::Object, kVerifyNone>(off);
472 DCHECK(patcher_->InHeap(referent)) << "Referent is not in the heap.";
473 mirror::Object* moved_object = patcher_->RelocatedAddressOf(referent);
474 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(off, moved_object);
475}
476
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700477void PatchOat::PatchVisitor::operator() (mirror::Class* cls ATTRIBUTE_UNUSED,
478 mirror::Reference* ref) const {
Alex Light53cb16b2014-06-12 11:26:29 -0700479 MemberOffset off = mirror::Reference::ReferentOffset();
480 mirror::Object* referent = ref->GetReferent();
481 DCHECK(patcher_->InHeap(referent)) << "Referent is not in the heap.";
482 mirror::Object* moved_object = patcher_->RelocatedAddressOf(referent);
483 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(off, moved_object);
484}
485
486mirror::Object* PatchOat::RelocatedCopyOf(mirror::Object* obj) {
487 if (obj == nullptr) {
488 return nullptr;
489 }
490 DCHECK_GT(reinterpret_cast<uintptr_t>(obj), reinterpret_cast<uintptr_t>(heap_->Begin()));
491 DCHECK_LT(reinterpret_cast<uintptr_t>(obj), reinterpret_cast<uintptr_t>(heap_->End()));
492 uintptr_t heap_off =
493 reinterpret_cast<uintptr_t>(obj) - reinterpret_cast<uintptr_t>(heap_->Begin());
494 DCHECK_LT(heap_off, image_->Size());
495 return reinterpret_cast<mirror::Object*>(image_->Begin() + heap_off);
496}
497
498mirror::Object* PatchOat::RelocatedAddressOf(mirror::Object* obj) {
499 if (obj == nullptr) {
500 return nullptr;
501 } else {
Ian Rogers13735952014-10-08 12:43:28 -0700502 return reinterpret_cast<mirror::Object*>(reinterpret_cast<uint8_t*>(obj) + delta_);
Alex Light53cb16b2014-06-12 11:26:29 -0700503 }
504}
505
Igor Murashkin46774762014-10-22 11:37:02 -0700506const OatHeader* PatchOat::GetOatHeader(const ElfFile* elf_file) {
507 if (elf_file->Is64Bit()) {
508 return GetOatHeader<ElfFileImpl64>(elf_file->GetImpl64());
509 } else {
510 return GetOatHeader<ElfFileImpl32>(elf_file->GetImpl32());
511 }
512}
513
514template <typename ElfFileImpl>
515const OatHeader* PatchOat::GetOatHeader(const ElfFileImpl* elf_file) {
516 auto rodata_sec = elf_file->FindSectionByName(".rodata");
517 if (rodata_sec == nullptr) {
518 return nullptr;
519 }
520
521 OatHeader* oat_header = reinterpret_cast<OatHeader*>(elf_file->Begin() + rodata_sec->sh_offset);
522 return oat_header;
523}
524
Alex Light53cb16b2014-06-12 11:26:29 -0700525// Called by BitmapCallback
526void PatchOat::VisitObject(mirror::Object* object) {
527 mirror::Object* copy = RelocatedCopyOf(object);
528 CHECK(copy != nullptr);
529 if (kUseBakerOrBrooksReadBarrier) {
530 object->AssertReadBarrierPointer();
531 if (kUseBrooksReadBarrier) {
532 mirror::Object* moved_to = RelocatedAddressOf(object);
533 copy->SetReadBarrierPointer(moved_to);
534 DCHECK_EQ(copy->GetReadBarrierPointer(), moved_to);
535 }
536 }
537 PatchOat::PatchVisitor visitor(this, copy);
538 object->VisitReferences<true, kVerifyNone>(visitor, visitor);
539 if (object->IsArtMethod<kVerifyNone>()) {
Mathieu Chartier2d721012014-11-10 11:08:06 -0800540 FixupMethod(down_cast<mirror::ArtMethod*>(object), down_cast<mirror::ArtMethod*>(copy));
Alex Light53cb16b2014-06-12 11:26:29 -0700541 }
542}
543
544void PatchOat::FixupMethod(mirror::ArtMethod* object, mirror::ArtMethod* copy) {
Mathieu Chartier2d721012014-11-10 11:08:06 -0800545 const size_t pointer_size = InstructionSetPointerSize(isa_);
Alex Light53cb16b2014-06-12 11:26:29 -0700546 // Just update the entry points if it looks like we should.
Alex Lighteefbe392014-07-08 09:53:18 -0700547 // TODO: sanity check all the pointers' values
Alex Light53cb16b2014-06-12 11:26:29 -0700548 uintptr_t quick= reinterpret_cast<uintptr_t>(
Mathieu Chartier2d721012014-11-10 11:08:06 -0800549 object->GetEntryPointFromQuickCompiledCodePtrSize<kVerifyNone>(pointer_size));
Alex Light53cb16b2014-06-12 11:26:29 -0700550 if (quick != 0) {
Mathieu Chartier2d721012014-11-10 11:08:06 -0800551 copy->SetEntryPointFromQuickCompiledCodePtrSize(reinterpret_cast<void*>(quick + delta_),
552 pointer_size);
Alex Light53cb16b2014-06-12 11:26:29 -0700553 }
554 uintptr_t interpreter = reinterpret_cast<uintptr_t>(
Mathieu Chartier2d721012014-11-10 11:08:06 -0800555 object->GetEntryPointFromInterpreterPtrSize<kVerifyNone>(pointer_size));
Alex Light53cb16b2014-06-12 11:26:29 -0700556 if (interpreter != 0) {
Mathieu Chartier2d721012014-11-10 11:08:06 -0800557 copy->SetEntryPointFromInterpreterPtrSize(
558 reinterpret_cast<mirror::EntryPointFromInterpreter*>(interpreter + delta_), pointer_size);
Alex Light53cb16b2014-06-12 11:26:29 -0700559 }
560
Mathieu Chartier2d721012014-11-10 11:08:06 -0800561 uintptr_t native_method = reinterpret_cast<uintptr_t>(
562 object->GetEntryPointFromJniPtrSize(pointer_size));
Alex Light53cb16b2014-06-12 11:26:29 -0700563 if (native_method != 0) {
Mathieu Chartier2d721012014-11-10 11:08:06 -0800564 copy->SetEntryPointFromJniPtrSize(reinterpret_cast<void*>(native_method + delta_),
565 pointer_size);
Alex Light53cb16b2014-06-12 11:26:29 -0700566 }
Alex Light53cb16b2014-06-12 11:26:29 -0700567}
568
Igor Murashkin46774762014-10-22 11:37:02 -0700569bool PatchOat::Patch(File* input_oat, off_t delta, File* output_oat, TimingLogger* timings,
570 bool output_oat_opened_from_fd, bool new_oat_out) {
Alex Light53cb16b2014-06-12 11:26:29 -0700571 CHECK(input_oat != nullptr);
572 CHECK(output_oat != nullptr);
573 CHECK_GE(input_oat->Fd(), 0);
574 CHECK_GE(output_oat->Fd(), 0);
Alex Lighteefbe392014-07-08 09:53:18 -0700575 TimingLogger::ScopedTiming t("Setup Oat File Patching", timings);
Alex Light53cb16b2014-06-12 11:26:29 -0700576
577 std::string error_msg;
Igor Murashkin46774762014-10-22 11:37:02 -0700578 std::unique_ptr<ElfFile> elf(ElfFile::Open(input_oat,
Alex Light53cb16b2014-06-12 11:26:29 -0700579 PROT_READ | PROT_WRITE, MAP_PRIVATE, &error_msg));
580 if (elf.get() == nullptr) {
581 LOG(ERROR) << "unable to open oat file " << input_oat->GetPath() << " : " << error_msg;
582 return false;
583 }
584
Igor Murashkin46774762014-10-22 11:37:02 -0700585 MaybePic is_oat_pic = IsOatPic(elf.get());
586 if (is_oat_pic >= ERROR_FIRST) {
587 // Error logged by IsOatPic
588 return false;
589 } else if (is_oat_pic == PIC) {
590 // Do not need to do ELF-file patching. Create a symlink and skip the rest.
591 // Any errors will be logged by the function call.
592 return ReplaceOatFileWithSymlink(input_oat->GetPath(),
593 output_oat->GetPath(),
594 output_oat_opened_from_fd,
595 new_oat_out);
596 } else {
597 CHECK(is_oat_pic == NOT_PIC);
598 }
599
Alex Light53cb16b2014-06-12 11:26:29 -0700600 PatchOat p(elf.release(), delta, timings);
601 t.NewTiming("Patch Oat file");
602 if (!p.PatchElf()) {
603 return false;
604 }
605
606 t.NewTiming("Writing oat file");
607 if (!p.WriteElf(output_oat)) {
608 return false;
609 }
610 return true;
611}
612
Tong Shen62d1ca32014-09-03 17:24:56 -0700613template <typename ElfFileImpl, typename ptr_t>
614bool PatchOat::CheckOatFile(ElfFileImpl* oat_file) {
615 auto patches_sec = oat_file->FindSectionByName(".oat_patches");
616 if (patches_sec->sh_type != SHT_OAT_PATCH) {
Alex Light53cb16b2014-06-12 11:26:29 -0700617 return false;
618 }
Tong Shen62d1ca32014-09-03 17:24:56 -0700619 ptr_t* patches = reinterpret_cast<ptr_t*>(oat_file->Begin() + patches_sec->sh_offset);
620 ptr_t* patches_end = patches + (patches_sec->sh_size / sizeof(ptr_t));
621 auto oat_data_sec = oat_file->FindSectionByName(".rodata");
622 auto oat_text_sec = oat_file->FindSectionByName(".text");
Alex Light53cb16b2014-06-12 11:26:29 -0700623 if (oat_data_sec == nullptr) {
624 return false;
625 }
626 if (oat_text_sec == nullptr) {
627 return false;
628 }
629 if (oat_text_sec->sh_offset <= oat_data_sec->sh_offset) {
630 return false;
631 }
632
633 for (; patches < patches_end; patches++) {
634 if (oat_text_sec->sh_size <= *patches) {
635 return false;
636 }
637 }
638
639 return true;
640}
641
Tong Shen62d1ca32014-09-03 17:24:56 -0700642template <typename ElfFileImpl>
643bool PatchOat::PatchOatHeader(ElfFileImpl* oat_file) {
644 auto rodata_sec = oat_file->FindSectionByName(".rodata");
Alex Lighta59dd802014-07-02 16:28:08 -0700645 if (rodata_sec == nullptr) {
646 return false;
647 }
Tong Shen62d1ca32014-09-03 17:24:56 -0700648 OatHeader* oat_header = reinterpret_cast<OatHeader*>(oat_file->Begin() + rodata_sec->sh_offset);
Alex Lighta59dd802014-07-02 16:28:08 -0700649 if (!oat_header->IsValid()) {
Tong Shen62d1ca32014-09-03 17:24:56 -0700650 LOG(ERROR) << "Elf file " << oat_file->GetFile().GetPath() << " has an invalid oat header";
Alex Lighta59dd802014-07-02 16:28:08 -0700651 return false;
652 }
653 oat_header->RelocateOat(delta_);
654 return true;
655}
656
Alex Light53cb16b2014-06-12 11:26:29 -0700657bool PatchOat::PatchElf() {
Ian Rogersd4c4d952014-10-16 20:31:53 -0700658 if (oat_file_->Is64Bit())
Tong Shen62d1ca32014-09-03 17:24:56 -0700659 return PatchElf<ElfFileImpl64>(oat_file_->GetImpl64());
660 else
661 return PatchElf<ElfFileImpl32>(oat_file_->GetImpl32());
662}
663
664template <typename ElfFileImpl>
665bool PatchOat::PatchElf(ElfFileImpl* oat_file) {
Alex Lighta59dd802014-07-02 16:28:08 -0700666 TimingLogger::ScopedTiming t("Fixup Elf Text Section", timings_);
Tong Shen62d1ca32014-09-03 17:24:56 -0700667 if (!PatchTextSection<ElfFileImpl>(oat_file)) {
Alex Lighta59dd802014-07-02 16:28:08 -0700668 return false;
669 }
670
Tong Shen62d1ca32014-09-03 17:24:56 -0700671 if (!PatchOatHeader<ElfFileImpl>(oat_file)) {
Alex Lighta59dd802014-07-02 16:28:08 -0700672 return false;
673 }
674
675 bool need_fixup = false;
Ian Rogersd4c4d952014-10-16 20:31:53 -0700676 for (unsigned int i = 0; i < oat_file->GetProgramHeaderNum(); ++i) {
Tong Shen62d1ca32014-09-03 17:24:56 -0700677 auto hdr = oat_file->GetProgramHeader(i);
Ian Rogersd4c4d952014-10-16 20:31:53 -0700678 if ((hdr->p_vaddr != 0 && hdr->p_vaddr != hdr->p_offset) ||
679 (hdr->p_paddr != 0 && hdr->p_paddr != hdr->p_offset)) {
Alex Lighta59dd802014-07-02 16:28:08 -0700680 need_fixup = true;
Ian Rogersd4c4d952014-10-16 20:31:53 -0700681 break;
Alex Light53cb16b2014-06-12 11:26:29 -0700682 }
683 }
Alex Lighta59dd802014-07-02 16:28:08 -0700684 if (!need_fixup) {
685 // This was never passed through ElfFixup so all headers/symbols just have their offset as
686 // their addr. Therefore we do not need to update these parts.
687 return true;
688 }
Tong Shen62d1ca32014-09-03 17:24:56 -0700689
690 t.NewTiming("Fixup Elf Headers");
691 // Fixup Phdr's
692 oat_file->FixupProgramHeaders(delta_);
693
Alex Lighta59dd802014-07-02 16:28:08 -0700694 t.NewTiming("Fixup Section Headers");
Tong Shen62d1ca32014-09-03 17:24:56 -0700695 // Fixup Shdr's
696 oat_file->FixupSectionHeaders(delta_);
Alex Light53cb16b2014-06-12 11:26:29 -0700697
Alex Lighta59dd802014-07-02 16:28:08 -0700698 t.NewTiming("Fixup Dynamics");
Tong Shen62d1ca32014-09-03 17:24:56 -0700699 oat_file->FixupDynamic(delta_);
Alex Light53cb16b2014-06-12 11:26:29 -0700700
701 t.NewTiming("Fixup Elf Symbols");
702 // Fixup dynsym
Tong Shen62d1ca32014-09-03 17:24:56 -0700703 if (!oat_file->FixupSymbols(delta_, true)) {
Alex Light53cb16b2014-06-12 11:26:29 -0700704 return false;
705 }
Alex Light53cb16b2014-06-12 11:26:29 -0700706 // Fixup symtab
Tong Shen62d1ca32014-09-03 17:24:56 -0700707 if (!oat_file->FixupSymbols(delta_, false)) {
708 return false;
Alex Light53cb16b2014-06-12 11:26:29 -0700709 }
710
Yevgeny Roubane3ea8382014-08-08 16:29:38 +0700711 t.NewTiming("Fixup Debug Sections");
Tong Shen62d1ca32014-09-03 17:24:56 -0700712 if (!oat_file->FixupDebugSections(delta_)) {
Yevgeny Roubane3ea8382014-08-08 16:29:38 +0700713 return false;
714 }
715
Alex Light53cb16b2014-06-12 11:26:29 -0700716 return true;
717}
718
Tong Shen62d1ca32014-09-03 17:24:56 -0700719template <typename ElfFileImpl>
720bool PatchOat::PatchTextSection(ElfFileImpl* oat_file) {
721 auto patches_sec = oat_file->FindSectionByName(".oat_patches");
Alex Light53cb16b2014-06-12 11:26:29 -0700722 if (patches_sec == nullptr) {
Alex Lighta59dd802014-07-02 16:28:08 -0700723 LOG(ERROR) << ".oat_patches section not found. Aborting patch";
Alex Light53cb16b2014-06-12 11:26:29 -0700724 return false;
725 }
Alex Light4b0d2d92014-08-06 13:37:23 -0700726 if (patches_sec->sh_type != SHT_OAT_PATCH) {
727 LOG(ERROR) << "Unexpected type of .oat_patches";
728 return false;
729 }
730
731 switch (patches_sec->sh_entsize) {
732 case sizeof(uint32_t):
Tong Shen62d1ca32014-09-03 17:24:56 -0700733 return PatchTextSection<ElfFileImpl, uint32_t>(oat_file);
Alex Light4b0d2d92014-08-06 13:37:23 -0700734 case sizeof(uint64_t):
Tong Shen62d1ca32014-09-03 17:24:56 -0700735 return PatchTextSection<ElfFileImpl, uint64_t>(oat_file);
Alex Light4b0d2d92014-08-06 13:37:23 -0700736 default:
737 LOG(ERROR) << ".oat_patches Entsize of " << patches_sec->sh_entsize << "bits "
738 << "is not valid";
739 return false;
740 }
741}
742
Tong Shen62d1ca32014-09-03 17:24:56 -0700743template <typename ElfFileImpl, typename patch_loc_t>
744bool PatchOat::PatchTextSection(ElfFileImpl* oat_file) {
745 bool oat_file_valid = CheckOatFile<ElfFileImpl, patch_loc_t>(oat_file);
746 CHECK(oat_file_valid) << "Oat file invalid";
747 auto patches_sec = oat_file->FindSectionByName(".oat_patches");
748 patch_loc_t* patches = reinterpret_cast<patch_loc_t*>(oat_file->Begin() + patches_sec->sh_offset);
749 patch_loc_t* patches_end = patches + (patches_sec->sh_size / sizeof(patch_loc_t));
750 auto oat_text_sec = oat_file->FindSectionByName(".text");
Alex Light53cb16b2014-06-12 11:26:29 -0700751 CHECK(oat_text_sec != nullptr);
Ian Rogers13735952014-10-08 12:43:28 -0700752 uint8_t* to_patch = oat_file->Begin() + oat_text_sec->sh_offset;
Alex Light53cb16b2014-06-12 11:26:29 -0700753 uintptr_t to_patch_end = reinterpret_cast<uintptr_t>(to_patch) + oat_text_sec->sh_size;
754
755 for (; patches < patches_end; patches++) {
756 CHECK_LT(*patches, oat_text_sec->sh_size) << "Bad Patch";
757 uint32_t* patch_loc = reinterpret_cast<uint32_t*>(to_patch + *patches);
758 CHECK_LT(reinterpret_cast<uintptr_t>(patch_loc), to_patch_end);
759 *patch_loc += delta_;
760 }
Alex Light53cb16b2014-06-12 11:26:29 -0700761 return true;
762}
763
764static int orig_argc;
765static char** orig_argv;
766
767static std::string CommandLine() {
768 std::vector<std::string> command;
769 for (int i = 0; i < orig_argc; ++i) {
770 command.push_back(orig_argv[i]);
771 }
772 return Join(command, ' ');
773}
774
775static void UsageErrorV(const char* fmt, va_list ap) {
776 std::string error;
777 StringAppendV(&error, fmt, ap);
778 LOG(ERROR) << error;
779}
780
781static void UsageError(const char* fmt, ...) {
782 va_list ap;
783 va_start(ap, fmt);
784 UsageErrorV(fmt, ap);
785 va_end(ap);
786}
787
Ian Rogers7223d442014-10-10 20:05:39 -0700788[[noreturn]] static void Usage(const char *fmt, ...) {
Alex Light53cb16b2014-06-12 11:26:29 -0700789 va_list ap;
790 va_start(ap, fmt);
791 UsageErrorV(fmt, ap);
792 va_end(ap);
793
794 UsageError("Command: %s", CommandLine().c_str());
795 UsageError("Usage: patchoat [options]...");
796 UsageError("");
797 UsageError(" --instruction-set=<isa>: Specifies the instruction set the patched code is");
798 UsageError(" compiled for. Required if you use --input-oat-location");
799 UsageError("");
800 UsageError(" --input-oat-file=<file.oat>: Specifies the exact filename of the oat file to be");
801 UsageError(" patched.");
802 UsageError("");
803 UsageError(" --input-oat-fd=<file-descriptor>: Specifies the file-descriptor of the oat file");
804 UsageError(" to be patched.");
805 UsageError("");
806 UsageError(" --input-oat-location=<file.oat>: Specifies the 'location' to read the patched");
807 UsageError(" oat file from. If used one must also supply the --instruction-set");
808 UsageError("");
809 UsageError(" --input-image-location=<file.art>: Specifies the 'location' of the image file to");
810 UsageError(" be patched. If --instruction-set is not given it will use the instruction set");
811 UsageError(" extracted from the --input-oat-file.");
812 UsageError("");
813 UsageError(" --output-oat-file=<file.oat>: Specifies the exact file to write the patched oat");
814 UsageError(" file to.");
815 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700816 UsageError(" --output-oat-fd=<file-descriptor>: Specifies the file-descriptor to write the");
817 UsageError(" the patched oat file to.");
818 UsageError("");
819 UsageError(" --output-image-file=<file.art>: Specifies the exact file to write the patched");
820 UsageError(" image file to.");
821 UsageError("");
822 UsageError(" --output-image-fd=<file-descriptor>: Specifies the file-descriptor to write the");
823 UsageError(" the patched image file to.");
824 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700825 UsageError(" --orig-base-offset=<original-base-offset>: Specify the base offset the input file");
826 UsageError(" was compiled with. This is needed if one is specifying a --base-offset");
827 UsageError("");
828 UsageError(" --base-offset=<new-base-offset>: Specify the base offset we will repatch the");
829 UsageError(" given files to use. This requires that --orig-base-offset is also given.");
830 UsageError("");
831 UsageError(" --base-offset-delta=<delta>: Specify the amount to change the old base-offset by.");
832 UsageError(" This value may be negative.");
833 UsageError("");
834 UsageError(" --patched-image-file=<file.art>: Use the same patch delta as was used to patch");
835 UsageError(" the given image file.");
836 UsageError("");
837 UsageError(" --patched-image-location=<file.art>: Use the same patch delta as was used to");
838 UsageError(" patch the given image location. If used one must also specify the");
Alex Lighta59dd802014-07-02 16:28:08 -0700839 UsageError(" --instruction-set flag. It will search for this image in the same way that");
840 UsageError(" is done when loading one.");
Alex Light53cb16b2014-06-12 11:26:29 -0700841 UsageError("");
Alex Lightcf4bf382014-07-24 11:29:14 -0700842 UsageError(" --lock-output: Obtain a flock on output oat file before starting.");
843 UsageError("");
844 UsageError(" --no-lock-output: Do not attempt to obtain a flock on output oat file.");
845 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700846 UsageError(" --dump-timings: dump out patch timing information");
847 UsageError("");
848 UsageError(" --no-dump-timings: do not dump out patch timing information");
849 UsageError("");
850
851 exit(EXIT_FAILURE);
852}
853
Alex Lighteefbe392014-07-08 09:53:18 -0700854static bool ReadBaseDelta(const char* name, off_t* delta, std::string* error_msg) {
Alex Light53cb16b2014-06-12 11:26:29 -0700855 CHECK(name != nullptr);
856 CHECK(delta != nullptr);
857 std::unique_ptr<File> file;
858 if (OS::FileExists(name)) {
859 file.reset(OS::OpenFileForReading(name));
860 if (file.get() == nullptr) {
Alex Lighteefbe392014-07-08 09:53:18 -0700861 *error_msg = "Failed to open file %s for reading";
Alex Light53cb16b2014-06-12 11:26:29 -0700862 return false;
863 }
864 } else {
Alex Lighteefbe392014-07-08 09:53:18 -0700865 *error_msg = "File %s does not exist";
Alex Light53cb16b2014-06-12 11:26:29 -0700866 return false;
867 }
868 CHECK(file.get() != nullptr);
869 ImageHeader hdr;
870 if (sizeof(hdr) != file->Read(reinterpret_cast<char*>(&hdr), sizeof(hdr), 0)) {
Alex Lighteefbe392014-07-08 09:53:18 -0700871 *error_msg = "Failed to read file %s";
Alex Light53cb16b2014-06-12 11:26:29 -0700872 return false;
873 }
874 if (!hdr.IsValid()) {
Alex Lighteefbe392014-07-08 09:53:18 -0700875 *error_msg = "%s does not contain a valid image header.";
Alex Light53cb16b2014-06-12 11:26:29 -0700876 return false;
877 }
878 *delta = hdr.GetPatchDelta();
879 return true;
880}
881
882static File* CreateOrOpen(const char* name, bool* created) {
883 if (OS::FileExists(name)) {
884 *created = false;
885 return OS::OpenFileReadWrite(name);
886 } else {
887 *created = true;
Alex Lightcf4bf382014-07-24 11:29:14 -0700888 std::unique_ptr<File> f(OS::CreateEmptyFile(name));
889 if (f.get() != nullptr) {
890 if (fchmod(f->Fd(), 0644) != 0) {
891 PLOG(ERROR) << "Unable to make " << name << " world readable";
Brian Carlstrom8c52a3f2014-09-30 16:18:01 -0700892 TEMP_FAILURE_RETRY(unlink(name));
Alex Lightcf4bf382014-07-24 11:29:14 -0700893 return nullptr;
894 }
895 }
896 return f.release();
Alex Light53cb16b2014-06-12 11:26:29 -0700897 }
898}
899
Andreas Gampe4303ba92014-11-06 01:00:46 -0800900// Either try to close the file (close=true), or erase it.
901static bool FinishFile(File* file, bool close) {
902 if (close) {
903 if (file->FlushCloseOrErase() != 0) {
904 PLOG(ERROR) << "Failed to flush and close file.";
905 return false;
906 }
907 return true;
908 } else {
909 file->Erase();
910 return false;
911 }
912}
913
Alex Lighteefbe392014-07-08 09:53:18 -0700914static int patchoat(int argc, char **argv) {
Alex Light53cb16b2014-06-12 11:26:29 -0700915 InitLogging(argv);
Mathieu Chartier6e88ef62014-10-14 15:01:24 -0700916 MemMap::Init();
Alex Light53cb16b2014-06-12 11:26:29 -0700917 const bool debug = kIsDebugBuild;
918 orig_argc = argc;
919 orig_argv = argv;
920 TimingLogger timings("patcher", false, false);
921
922 InitLogging(argv);
923
924 // Skip over the command name.
925 argv++;
926 argc--;
927
928 if (argc == 0) {
929 Usage("No arguments specified");
930 }
931
932 timings.StartTiming("Patchoat");
933
934 // cmd line args
935 bool isa_set = false;
936 InstructionSet isa = kNone;
937 std::string input_oat_filename;
938 std::string input_oat_location;
939 int input_oat_fd = -1;
940 bool have_input_oat = false;
941 std::string input_image_location;
942 std::string output_oat_filename;
Alex Light53cb16b2014-06-12 11:26:29 -0700943 int output_oat_fd = -1;
944 bool have_output_oat = false;
945 std::string output_image_filename;
Alex Light53cb16b2014-06-12 11:26:29 -0700946 int output_image_fd = -1;
947 bool have_output_image = false;
948 uintptr_t base_offset = 0;
949 bool base_offset_set = false;
950 uintptr_t orig_base_offset = 0;
951 bool orig_base_offset_set = false;
952 off_t base_delta = 0;
953 bool base_delta_set = false;
954 std::string patched_image_filename;
955 std::string patched_image_location;
956 bool dump_timings = kIsDebugBuild;
Alex Lightcf4bf382014-07-24 11:29:14 -0700957 bool lock_output = true;
Alex Light53cb16b2014-06-12 11:26:29 -0700958
Ian Rogersd4c4d952014-10-16 20:31:53 -0700959 for (int i = 0; i < argc; ++i) {
Alex Light53cb16b2014-06-12 11:26:29 -0700960 const StringPiece option(argv[i]);
961 const bool log_options = false;
962 if (log_options) {
963 LOG(INFO) << "patchoat: option[" << i << "]=" << argv[i];
964 }
Alex Light53cb16b2014-06-12 11:26:29 -0700965 if (option.starts_with("--instruction-set=")) {
966 isa_set = true;
967 const char* isa_str = option.substr(strlen("--instruction-set=")).data();
Andreas Gampe20c89302014-08-19 17:28:06 -0700968 isa = GetInstructionSetFromString(isa_str);
969 if (isa == kNone) {
970 Usage("Unknown or invalid instruction set %s", isa_str);
Alex Light53cb16b2014-06-12 11:26:29 -0700971 }
972 } else if (option.starts_with("--input-oat-location=")) {
973 if (have_input_oat) {
974 Usage("Only one of --input-oat-file, --input-oat-location and --input-oat-fd may be used.");
975 }
976 have_input_oat = true;
977 input_oat_location = option.substr(strlen("--input-oat-location=")).data();
978 } else if (option.starts_with("--input-oat-file=")) {
979 if (have_input_oat) {
980 Usage("Only one of --input-oat-file, --input-oat-location and --input-oat-fd may be used.");
981 }
982 have_input_oat = true;
983 input_oat_filename = option.substr(strlen("--input-oat-file=")).data();
984 } else if (option.starts_with("--input-oat-fd=")) {
985 if (have_input_oat) {
986 Usage("Only one of --input-oat-file, --input-oat-location and --input-oat-fd may be used.");
987 }
988 have_input_oat = true;
989 const char* oat_fd_str = option.substr(strlen("--input-oat-fd=")).data();
990 if (!ParseInt(oat_fd_str, &input_oat_fd)) {
991 Usage("Failed to parse --input-oat-fd argument '%s' as an integer", oat_fd_str);
992 }
993 if (input_oat_fd < 0) {
994 Usage("--input-oat-fd pass a negative value %d", input_oat_fd);
995 }
996 } else if (option.starts_with("--input-image-location=")) {
997 input_image_location = option.substr(strlen("--input-image-location=")).data();
Alex Light53cb16b2014-06-12 11:26:29 -0700998 } else if (option.starts_with("--output-oat-file=")) {
999 if (have_output_oat) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001000 Usage("Only one of --output-oat-file, and --output-oat-fd may be used.");
Alex Light53cb16b2014-06-12 11:26:29 -07001001 }
1002 have_output_oat = true;
1003 output_oat_filename = option.substr(strlen("--output-oat-file=")).data();
1004 } else if (option.starts_with("--output-oat-fd=")) {
1005 if (have_output_oat) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001006 Usage("Only one of --output-oat-file, --output-oat-fd may be used.");
Alex Light53cb16b2014-06-12 11:26:29 -07001007 }
1008 have_output_oat = true;
1009 const char* oat_fd_str = option.substr(strlen("--output-oat-fd=")).data();
1010 if (!ParseInt(oat_fd_str, &output_oat_fd)) {
1011 Usage("Failed to parse --output-oat-fd argument '%s' as an integer", oat_fd_str);
1012 }
1013 if (output_oat_fd < 0) {
1014 Usage("--output-oat-fd pass a negative value %d", output_oat_fd);
1015 }
Alex Light53cb16b2014-06-12 11:26:29 -07001016 } else if (option.starts_with("--output-image-file=")) {
1017 if (have_output_image) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001018 Usage("Only one of --output-image-file, and --output-image-fd may be used.");
Alex Light53cb16b2014-06-12 11:26:29 -07001019 }
1020 have_output_image = true;
1021 output_image_filename = option.substr(strlen("--output-image-file=")).data();
1022 } else if (option.starts_with("--output-image-fd=")) {
1023 if (have_output_image) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001024 Usage("Only one of --output-image-file, and --output-image-fd may be used.");
Alex Light53cb16b2014-06-12 11:26:29 -07001025 }
1026 have_output_image = true;
1027 const char* image_fd_str = option.substr(strlen("--output-image-fd=")).data();
1028 if (!ParseInt(image_fd_str, &output_image_fd)) {
1029 Usage("Failed to parse --output-image-fd argument '%s' as an integer", image_fd_str);
1030 }
1031 if (output_image_fd < 0) {
1032 Usage("--output-image-fd pass a negative value %d", output_image_fd);
1033 }
1034 } else if (option.starts_with("--orig-base-offset=")) {
1035 const char* orig_base_offset_str = option.substr(strlen("--orig-base-offset=")).data();
1036 orig_base_offset_set = true;
1037 if (!ParseUint(orig_base_offset_str, &orig_base_offset)) {
1038 Usage("Failed to parse --orig-base-offset argument '%s' as an uintptr_t",
1039 orig_base_offset_str);
1040 }
1041 } else if (option.starts_with("--base-offset=")) {
1042 const char* base_offset_str = option.substr(strlen("--base-offset=")).data();
1043 base_offset_set = true;
1044 if (!ParseUint(base_offset_str, &base_offset)) {
1045 Usage("Failed to parse --base-offset argument '%s' as an uintptr_t", base_offset_str);
1046 }
1047 } else if (option.starts_with("--base-offset-delta=")) {
1048 const char* base_delta_str = option.substr(strlen("--base-offset-delta=")).data();
1049 base_delta_set = true;
1050 if (!ParseInt(base_delta_str, &base_delta)) {
1051 Usage("Failed to parse --base-offset-delta argument '%s' as an off_t", base_delta_str);
1052 }
1053 } else if (option.starts_with("--patched-image-location=")) {
1054 patched_image_location = option.substr(strlen("--patched-image-location=")).data();
1055 } else if (option.starts_with("--patched-image-file=")) {
1056 patched_image_filename = option.substr(strlen("--patched-image-file=")).data();
Alex Lightcf4bf382014-07-24 11:29:14 -07001057 } else if (option == "--lock-output") {
1058 lock_output = true;
1059 } else if (option == "--no-lock-output") {
1060 lock_output = false;
Alex Light53cb16b2014-06-12 11:26:29 -07001061 } else if (option == "--dump-timings") {
1062 dump_timings = true;
1063 } else if (option == "--no-dump-timings") {
1064 dump_timings = false;
1065 } else {
1066 Usage("Unknown argument %s", option.data());
1067 }
1068 }
1069
1070 {
1071 // Only 1 of these may be set.
1072 uint32_t cnt = 0;
1073 cnt += (base_delta_set) ? 1 : 0;
1074 cnt += (base_offset_set && orig_base_offset_set) ? 1 : 0;
1075 cnt += (!patched_image_filename.empty()) ? 1 : 0;
1076 cnt += (!patched_image_location.empty()) ? 1 : 0;
1077 if (cnt > 1) {
1078 Usage("Only one of --base-offset/--orig-base-offset, --base-offset-delta, "
1079 "--patched-image-filename or --patched-image-location may be used.");
1080 } else if (cnt == 0) {
1081 Usage("Must specify --base-offset-delta, --base-offset and --orig-base-offset, "
1082 "--patched-image-location or --patched-image-file");
1083 }
1084 }
1085
1086 if (have_input_oat != have_output_oat) {
1087 Usage("Either both input and output oat must be supplied or niether must be.");
1088 }
1089
1090 if ((!input_image_location.empty()) != have_output_image) {
1091 Usage("Either both input and output image must be supplied or niether must be.");
1092 }
1093
1094 // We know we have both the input and output so rename for clarity.
1095 bool have_image_files = have_output_image;
1096 bool have_oat_files = have_output_oat;
1097
1098 if (!have_oat_files && !have_image_files) {
1099 Usage("Must be patching either an oat or an image file or both.");
1100 }
1101
1102 if (!have_oat_files && !isa_set) {
1103 Usage("Must include ISA if patching an image file without an oat file.");
1104 }
1105
1106 if (!input_oat_location.empty()) {
1107 if (!isa_set) {
1108 Usage("specifying a location requires specifying an instruction set");
1109 }
Alex Lightcf4bf382014-07-24 11:29:14 -07001110 if (!LocationToFilename(input_oat_location, isa, &input_oat_filename)) {
1111 Usage("Unable to find filename for input oat location %s", input_oat_location.c_str());
1112 }
Alex Light53cb16b2014-06-12 11:26:29 -07001113 if (debug) {
1114 LOG(INFO) << "Using input-oat-file " << input_oat_filename;
1115 }
1116 }
Alex Light53cb16b2014-06-12 11:26:29 -07001117 if (!patched_image_location.empty()) {
1118 if (!isa_set) {
1119 Usage("specifying a location requires specifying an instruction set");
1120 }
Alex Lighta59dd802014-07-02 16:28:08 -07001121 std::string system_filename;
1122 bool has_system = false;
1123 std::string cache_filename;
1124 bool has_cache = false;
1125 bool has_android_data_unused = false;
Andreas Gampe3c13a792014-09-18 20:56:04 -07001126 bool is_global_cache = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001127 if (!gc::space::ImageSpace::FindImageFilename(patched_image_location.c_str(), isa,
1128 &system_filename, &has_system, &cache_filename,
Andreas Gampe3c13a792014-09-18 20:56:04 -07001129 &has_android_data_unused, &has_cache,
1130 &is_global_cache)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001131 Usage("Unable to determine image file for location %s", patched_image_location.c_str());
1132 }
1133 if (has_cache) {
1134 patched_image_filename = cache_filename;
1135 } else if (has_system) {
1136 LOG(WARNING) << "Only image file found was in /system for image location "
1137 << patched_image_location;
1138 patched_image_filename = system_filename;
1139 } else {
1140 Usage("Unable to determine image file for location %s", patched_image_location.c_str());
1141 }
Alex Light53cb16b2014-06-12 11:26:29 -07001142 if (debug) {
1143 LOG(INFO) << "Using patched-image-file " << patched_image_filename;
1144 }
1145 }
1146
1147 if (!base_delta_set) {
1148 if (orig_base_offset_set && base_offset_set) {
1149 base_delta_set = true;
1150 base_delta = base_offset - orig_base_offset;
1151 } else if (!patched_image_filename.empty()) {
1152 base_delta_set = true;
1153 std::string error_msg;
Alex Lighteefbe392014-07-08 09:53:18 -07001154 if (!ReadBaseDelta(patched_image_filename.c_str(), &base_delta, &error_msg)) {
Alex Light53cb16b2014-06-12 11:26:29 -07001155 Usage(error_msg.c_str(), patched_image_filename.c_str());
1156 }
1157 } else {
1158 if (base_offset_set) {
1159 Usage("Unable to determine original base offset.");
1160 } else {
1161 Usage("Must supply a desired new offset or delta.");
1162 }
1163 }
1164 }
1165
1166 if (!IsAligned<kPageSize>(base_delta)) {
1167 Usage("Base offset/delta must be alligned to a pagesize (0x%08x) boundary.", kPageSize);
1168 }
1169
1170 // Do we need to cleanup output files if we fail?
1171 bool new_image_out = false;
1172 bool new_oat_out = false;
1173
1174 std::unique_ptr<File> input_oat;
1175 std::unique_ptr<File> output_oat;
1176 std::unique_ptr<File> output_image;
1177
1178 if (have_image_files) {
1179 CHECK(!input_image_location.empty());
1180
1181 if (output_image_fd != -1) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001182 if (output_image_filename.empty()) {
1183 output_image_filename = "output-image-file";
1184 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001185 output_image.reset(new File(output_image_fd, output_image_filename, true));
Alex Light53cb16b2014-06-12 11:26:29 -07001186 } else {
1187 CHECK(!output_image_filename.empty());
1188 output_image.reset(CreateOrOpen(output_image_filename.c_str(), &new_image_out));
1189 }
1190 } else {
1191 CHECK(output_image_filename.empty() && output_image_fd == -1 && input_image_location.empty());
1192 }
1193
1194 if (have_oat_files) {
1195 if (input_oat_fd != -1) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001196 if (input_oat_filename.empty()) {
1197 input_oat_filename = "input-oat-file";
1198 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001199 input_oat.reset(new File(input_oat_fd, input_oat_filename, false));
Igor Murashkin46774762014-10-22 11:37:02 -07001200 if (input_oat == nullptr) {
1201 // Unlikely, but ensure exhaustive logging in non-0 exit code case
1202 LOG(ERROR) << "Failed to open input oat file by its FD" << input_oat_fd;
1203 }
Alex Light53cb16b2014-06-12 11:26:29 -07001204 } else {
1205 CHECK(!input_oat_filename.empty());
1206 input_oat.reset(OS::OpenFileForReading(input_oat_filename.c_str()));
Igor Murashkin46774762014-10-22 11:37:02 -07001207 if (input_oat == nullptr) {
1208 int err = errno;
1209 LOG(ERROR) << "Failed to open input oat file " << input_oat_filename
1210 << ": " << strerror(err) << "(" << err << ")";
Andreas Gampe1c83cbc2014-07-22 18:52:29 -07001211 }
Alex Light53cb16b2014-06-12 11:26:29 -07001212 }
1213
1214 if (output_oat_fd != -1) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001215 if (output_oat_filename.empty()) {
1216 output_oat_filename = "output-oat-file";
Alex Lighta59dd802014-07-02 16:28:08 -07001217 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001218 output_oat.reset(new File(output_oat_fd, output_oat_filename, true));
Igor Murashkin46774762014-10-22 11:37:02 -07001219 if (output_oat == nullptr) {
1220 // Unlikely, but ensure exhaustive logging in non-0 exit code case
1221 LOG(ERROR) << "Failed to open output oat file by its FD" << output_oat_fd;
1222 }
Alex Light53cb16b2014-06-12 11:26:29 -07001223 } else {
1224 CHECK(!output_oat_filename.empty());
1225 output_oat.reset(CreateOrOpen(output_oat_filename.c_str(), &new_oat_out));
Igor Murashkin46774762014-10-22 11:37:02 -07001226 if (output_oat == nullptr) {
1227 int err = errno;
1228 LOG(ERROR) << "Failed to open output oat file " << output_oat_filename
1229 << ": " << strerror(err) << "(" << err << ")";
1230 }
Alex Light53cb16b2014-06-12 11:26:29 -07001231 }
1232 }
1233
Igor Murashkin46774762014-10-22 11:37:02 -07001234 // TODO: get rid of this.
Alex Light53cb16b2014-06-12 11:26:29 -07001235 auto cleanup = [&output_image_filename, &output_oat_filename,
1236 &new_oat_out, &new_image_out, &timings, &dump_timings](bool success) {
1237 timings.EndTiming();
1238 if (!success) {
1239 if (new_oat_out) {
1240 CHECK(!output_oat_filename.empty());
Brian Carlstrom8c52a3f2014-09-30 16:18:01 -07001241 TEMP_FAILURE_RETRY(unlink(output_oat_filename.c_str()));
Alex Light53cb16b2014-06-12 11:26:29 -07001242 }
1243 if (new_image_out) {
1244 CHECK(!output_image_filename.empty());
Brian Carlstrom8c52a3f2014-09-30 16:18:01 -07001245 TEMP_FAILURE_RETRY(unlink(output_image_filename.c_str()));
Alex Light53cb16b2014-06-12 11:26:29 -07001246 }
1247 }
1248 if (dump_timings) {
1249 LOG(INFO) << Dumpable<TimingLogger>(timings);
1250 }
Igor Murashkin46774762014-10-22 11:37:02 -07001251
1252 if (kIsDebugBuild) {
1253 LOG(INFO) << "Cleaning up.. success? " << success;
1254 }
Alex Light53cb16b2014-06-12 11:26:29 -07001255 };
1256
Igor Murashkin46774762014-10-22 11:37:02 -07001257 if (have_oat_files && (input_oat.get() == nullptr || output_oat.get() == nullptr)) {
1258 LOG(ERROR) << "Failed to open input/output oat files";
1259 cleanup(false);
1260 return EXIT_FAILURE;
1261 } else if (have_image_files && output_image.get() == nullptr) {
1262 LOG(ERROR) << "Failed to open output image file";
Alex Lightcf4bf382014-07-24 11:29:14 -07001263 cleanup(false);
1264 return EXIT_FAILURE;
1265 }
1266
Igor Murashkin46774762014-10-22 11:37:02 -07001267 if (debug) {
1268 LOG(INFO) << "moving offset by " << base_delta
1269 << " (0x" << std::hex << base_delta << ") bytes or "
1270 << std::dec << (base_delta/kPageSize) << " pages.";
1271 }
1272
1273 // TODO: is it going to be promatic to unlink a file that was flock-ed?
Alex Lightcf4bf382014-07-24 11:29:14 -07001274 ScopedFlock output_oat_lock;
1275 if (lock_output) {
1276 std::string error_msg;
1277 if (have_oat_files && !output_oat_lock.Init(output_oat.get(), &error_msg)) {
1278 LOG(ERROR) << "Unable to lock output oat " << output_image->GetPath() << ": " << error_msg;
1279 cleanup(false);
1280 return EXIT_FAILURE;
1281 }
1282 }
1283
Alex Light53cb16b2014-06-12 11:26:29 -07001284 bool ret;
1285 if (have_image_files && have_oat_files) {
1286 TimingLogger::ScopedTiming pt("patch image and oat", &timings);
1287 ret = PatchOat::Patch(input_oat.get(), input_image_location, base_delta,
Igor Murashkin46774762014-10-22 11:37:02 -07001288 output_oat.get(), output_image.get(), isa, &timings,
1289 output_oat_fd >= 0, // was it opened from FD?
1290 new_oat_out);
Andreas Gampe4303ba92014-11-06 01:00:46 -08001291 // The order here doesn't matter. If the first one is successfully saved and the second one
1292 // erased, ImageSpace will still detect a problem and not use the files.
1293 ret = ret && FinishFile(output_image.get(), ret);
1294 ret = ret && FinishFile(output_oat.get(), ret);
Alex Light53cb16b2014-06-12 11:26:29 -07001295 } else if (have_oat_files) {
1296 TimingLogger::ScopedTiming pt("patch oat", &timings);
Igor Murashkin46774762014-10-22 11:37:02 -07001297 ret = PatchOat::Patch(input_oat.get(), base_delta, output_oat.get(), &timings,
1298 output_oat_fd >= 0, // was it opened from FD?
1299 new_oat_out);
Andreas Gampe4303ba92014-11-06 01:00:46 -08001300 ret = ret && FinishFile(output_oat.get(), ret);
Igor Murashkin46774762014-10-22 11:37:02 -07001301 } else if (have_image_files) {
Alex Light53cb16b2014-06-12 11:26:29 -07001302 TimingLogger::ScopedTiming pt("patch image", &timings);
Alex Lighteefbe392014-07-08 09:53:18 -07001303 ret = PatchOat::Patch(input_image_location, base_delta, output_image.get(), isa, &timings);
Andreas Gampe4303ba92014-11-06 01:00:46 -08001304 ret = ret && FinishFile(output_image.get(), ret);
Igor Murashkin46774762014-10-22 11:37:02 -07001305 } else {
1306 CHECK(false);
1307 ret = true;
1308 }
1309
1310 if (kIsDebugBuild) {
1311 LOG(INFO) << "Exiting with return ... " << ret;
Alex Light53cb16b2014-06-12 11:26:29 -07001312 }
1313 cleanup(ret);
Alex Light53cb16b2014-06-12 11:26:29 -07001314 return (ret) ? EXIT_SUCCESS : EXIT_FAILURE;
1315}
1316
1317} // namespace art
1318
1319int main(int argc, char **argv) {
1320 return art::patchoat(argc, argv);
1321}