blob: 6c86c7b7a5d0f6b9f737ab449890358389130de0 [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;
Andreas Gampe57b34292015-01-14 15:45:59 -080065 } else if ((e_flags & EF_MIPS_ARCH) == EF_MIPS_ARCH_64R6) {
66 return kMips64;
Andreas Gampec5a3ea72015-01-13 16:41:53 -080067 } else {
68 return kNone;
69 }
Alex Light53cb16b2014-06-12 11:26:29 -070070 default:
71 return kNone;
72 }
73}
74
Alex Lightcf4bf382014-07-24 11:29:14 -070075static bool LocationToFilename(const std::string& location, InstructionSet isa,
76 std::string* filename) {
77 bool has_system = false;
78 bool has_cache = false;
79 // image_location = /system/framework/boot.art
Igor Murashkin46774762014-10-22 11:37:02 -070080 // system_image_filename = /system/framework/<image_isa>/boot.art
Alex Lightcf4bf382014-07-24 11:29:14 -070081 std::string system_filename(GetSystemImageFilename(location.c_str(), isa));
82 if (OS::FileExists(system_filename.c_str())) {
83 has_system = true;
84 }
85
86 bool have_android_data = false;
87 bool dalvik_cache_exists = false;
Andreas Gampe3c13a792014-09-18 20:56:04 -070088 bool is_global_cache = false;
Alex Lightcf4bf382014-07-24 11:29:14 -070089 std::string dalvik_cache;
90 GetDalvikCache(GetInstructionSetString(isa), false, &dalvik_cache,
Andreas Gampe3c13a792014-09-18 20:56:04 -070091 &have_android_data, &dalvik_cache_exists, &is_global_cache);
Alex Lightcf4bf382014-07-24 11:29:14 -070092
93 std::string cache_filename;
94 if (have_android_data && dalvik_cache_exists) {
95 // Always set output location even if it does not exist,
96 // so that the caller knows where to create the image.
97 //
98 // image_location = /system/framework/boot.art
99 // *image_filename = /data/dalvik-cache/<image_isa>/boot.art
100 std::string error_msg;
101 if (GetDalvikCacheFilename(location.c_str(), dalvik_cache.c_str(),
102 &cache_filename, &error_msg)) {
103 has_cache = true;
104 }
105 }
106 if (has_system) {
107 *filename = system_filename;
108 return true;
109 } else if (has_cache) {
110 *filename = cache_filename;
111 return true;
112 } else {
113 return false;
114 }
115}
116
Alex Light53cb16b2014-06-12 11:26:29 -0700117bool PatchOat::Patch(const std::string& image_location, off_t delta,
118 File* output_image, InstructionSet isa,
Alex Lighteefbe392014-07-08 09:53:18 -0700119 TimingLogger* timings) {
Alex Light53cb16b2014-06-12 11:26:29 -0700120 CHECK(Runtime::Current() == nullptr);
121 CHECK(output_image != nullptr);
122 CHECK_GE(output_image->Fd(), 0);
123 CHECK(!image_location.empty()) << "image file must have a filename.";
124 CHECK_NE(isa, kNone);
125
Alex Lighteefbe392014-07-08 09:53:18 -0700126 TimingLogger::ScopedTiming t("Runtime Setup", timings);
Alex Light53cb16b2014-06-12 11:26:29 -0700127 const char *isa_name = GetInstructionSetString(isa);
Alex Lightcf4bf382014-07-24 11:29:14 -0700128 std::string image_filename;
129 if (!LocationToFilename(image_location, isa, &image_filename)) {
130 LOG(ERROR) << "Unable to find image at location " << image_location;
131 return false;
132 }
Alex Light53cb16b2014-06-12 11:26:29 -0700133 std::unique_ptr<File> input_image(OS::OpenFileForReading(image_filename.c_str()));
134 if (input_image.get() == nullptr) {
Alex Lightcf4bf382014-07-24 11:29:14 -0700135 LOG(ERROR) << "unable to open input image file at " << image_filename
136 << " for location " << image_location;
Alex Light53cb16b2014-06-12 11:26:29 -0700137 return false;
138 }
Igor Murashkin46774762014-10-22 11:37:02 -0700139
Alex Light53cb16b2014-06-12 11:26:29 -0700140 int64_t image_len = input_image->GetLength();
141 if (image_len < 0) {
142 LOG(ERROR) << "Error while getting image length";
143 return false;
144 }
145 ImageHeader image_header;
146 if (sizeof(image_header) != input_image->Read(reinterpret_cast<char*>(&image_header),
147 sizeof(image_header), 0)) {
148 LOG(ERROR) << "Unable to read image header from image file " << input_image->GetPath();
149 return false;
150 }
151
Igor Murashkin46774762014-10-22 11:37:02 -0700152 /*bool is_image_pic = */IsImagePic(image_header, input_image->GetPath());
153 // Nothing special to do right now since the image always needs to get patched.
154 // Perhaps in some far-off future we may have images with relative addresses that are true-PIC.
155
Alex Light53cb16b2014-06-12 11:26:29 -0700156 // Set up the runtime
Ian Rogerse63db272014-07-15 15:36:11 -0700157 RuntimeOptions options;
Alex Light53cb16b2014-06-12 11:26:29 -0700158 NoopCompilerCallbacks callbacks;
159 options.push_back(std::make_pair("compilercallbacks", &callbacks));
160 std::string img = "-Ximage:" + image_location;
161 options.push_back(std::make_pair(img.c_str(), nullptr));
162 options.push_back(std::make_pair("imageinstructionset", reinterpret_cast<const void*>(isa_name)));
163 if (!Runtime::Create(options, false)) {
164 LOG(ERROR) << "Unable to initialize runtime";
165 return false;
166 }
167 // Runtime::Create acquired the mutator_lock_ that is normally given away when we Runtime::Start,
168 // give it away now and then switch to a more manageable ScopedObjectAccess.
169 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
170 ScopedObjectAccess soa(Thread::Current());
171
172 t.NewTiming("Image and oat Patching setup");
173 // Create the map where we will write the image patches to.
Alex Lighteefbe392014-07-08 09:53:18 -0700174 std::string error_msg;
Alex Light53cb16b2014-06-12 11:26:29 -0700175 std::unique_ptr<MemMap> image(MemMap::MapFile(image_len, PROT_READ | PROT_WRITE, MAP_PRIVATE,
176 input_image->Fd(), 0,
177 input_image->GetPath().c_str(),
178 &error_msg));
179 if (image.get() == nullptr) {
180 LOG(ERROR) << "unable to map image file " << input_image->GetPath() << " : " << error_msg;
181 return false;
182 }
183 gc::space::ImageSpace* ispc = Runtime::Current()->GetHeap()->GetImageSpace();
184
Mathieu Chartier2d721012014-11-10 11:08:06 -0800185 PatchOat p(isa, image.release(), ispc->GetLiveBitmap(), ispc->GetMemMap(),
Alex Light53cb16b2014-06-12 11:26:29 -0700186 delta, timings);
187 t.NewTiming("Patching files");
188 if (!p.PatchImage()) {
Alex Lighta59dd802014-07-02 16:28:08 -0700189 LOG(ERROR) << "Failed to patch image file " << input_image->GetPath();
Alex Light53cb16b2014-06-12 11:26:29 -0700190 return false;
191 }
192
193 t.NewTiming("Writing files");
194 if (!p.WriteImage(output_image)) {
195 return false;
196 }
197 return true;
198}
199
Igor Murashkin46774762014-10-22 11:37:02 -0700200bool PatchOat::Patch(File* input_oat, const std::string& image_location, off_t delta,
Alex Light53cb16b2014-06-12 11:26:29 -0700201 File* output_oat, File* output_image, InstructionSet isa,
Igor Murashkin46774762014-10-22 11:37:02 -0700202 TimingLogger* timings,
203 bool output_oat_opened_from_fd,
204 bool new_oat_out) {
Alex Light53cb16b2014-06-12 11:26:29 -0700205 CHECK(Runtime::Current() == nullptr);
206 CHECK(output_image != nullptr);
207 CHECK_GE(output_image->Fd(), 0);
208 CHECK(input_oat != nullptr);
209 CHECK(output_oat != nullptr);
210 CHECK_GE(input_oat->Fd(), 0);
211 CHECK_GE(output_oat->Fd(), 0);
212 CHECK(!image_location.empty()) << "image file must have a filename.";
213
Alex Lighteefbe392014-07-08 09:53:18 -0700214 TimingLogger::ScopedTiming t("Runtime Setup", timings);
Alex Light53cb16b2014-06-12 11:26:29 -0700215
216 if (isa == kNone) {
217 Elf32_Ehdr elf_hdr;
218 if (sizeof(elf_hdr) != input_oat->Read(reinterpret_cast<char*>(&elf_hdr), sizeof(elf_hdr), 0)) {
219 LOG(ERROR) << "unable to read elf header";
220 return false;
221 }
Andreas Gampec5a3ea72015-01-13 16:41:53 -0800222 isa = ElfISAToInstructionSet(elf_hdr.e_machine, elf_hdr.e_flags);
Alex Light53cb16b2014-06-12 11:26:29 -0700223 }
224 const char* isa_name = GetInstructionSetString(isa);
Alex Lightcf4bf382014-07-24 11:29:14 -0700225 std::string image_filename;
226 if (!LocationToFilename(image_location, isa, &image_filename)) {
227 LOG(ERROR) << "Unable to find image at location " << image_location;
228 return false;
229 }
Alex Light53cb16b2014-06-12 11:26:29 -0700230 std::unique_ptr<File> input_image(OS::OpenFileForReading(image_filename.c_str()));
231 if (input_image.get() == nullptr) {
Alex Lightcf4bf382014-07-24 11:29:14 -0700232 LOG(ERROR) << "unable to open input image file at " << image_filename
233 << " for location " << image_location;
Alex Light53cb16b2014-06-12 11:26:29 -0700234 return false;
235 }
236 int64_t image_len = input_image->GetLength();
237 if (image_len < 0) {
238 LOG(ERROR) << "Error while getting image length";
239 return false;
240 }
241 ImageHeader image_header;
242 if (sizeof(image_header) != input_image->Read(reinterpret_cast<char*>(&image_header),
243 sizeof(image_header), 0)) {
244 LOG(ERROR) << "Unable to read image header from image file " << input_image->GetPath();
245 }
246
Igor Murashkin46774762014-10-22 11:37:02 -0700247 /*bool is_image_pic = */IsImagePic(image_header, input_image->GetPath());
248 // Nothing special to do right now since the image always needs to get patched.
249 // Perhaps in some far-off future we may have images with relative addresses that are true-PIC.
250
Alex Light53cb16b2014-06-12 11:26:29 -0700251 // Set up the runtime
Ian Rogerse63db272014-07-15 15:36:11 -0700252 RuntimeOptions options;
Alex Light53cb16b2014-06-12 11:26:29 -0700253 NoopCompilerCallbacks callbacks;
254 options.push_back(std::make_pair("compilercallbacks", &callbacks));
255 std::string img = "-Ximage:" + image_location;
256 options.push_back(std::make_pair(img.c_str(), nullptr));
257 options.push_back(std::make_pair("imageinstructionset", reinterpret_cast<const void*>(isa_name)));
258 if (!Runtime::Create(options, false)) {
259 LOG(ERROR) << "Unable to initialize runtime";
260 return false;
261 }
262 // Runtime::Create acquired the mutator_lock_ that is normally given away when we Runtime::Start,
263 // give it away now and then switch to a more manageable ScopedObjectAccess.
264 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
265 ScopedObjectAccess soa(Thread::Current());
266
267 t.NewTiming("Image and oat Patching setup");
268 // Create the map where we will write the image patches to.
Alex Lighteefbe392014-07-08 09:53:18 -0700269 std::string error_msg;
Alex Light53cb16b2014-06-12 11:26:29 -0700270 std::unique_ptr<MemMap> image(MemMap::MapFile(image_len, PROT_READ | PROT_WRITE, MAP_PRIVATE,
271 input_image->Fd(), 0,
272 input_image->GetPath().c_str(),
273 &error_msg));
274 if (image.get() == nullptr) {
275 LOG(ERROR) << "unable to map image file " << input_image->GetPath() << " : " << error_msg;
276 return false;
277 }
278 gc::space::ImageSpace* ispc = Runtime::Current()->GetHeap()->GetImageSpace();
279
Igor Murashkin46774762014-10-22 11:37:02 -0700280 std::unique_ptr<ElfFile> elf(ElfFile::Open(input_oat,
Alex Light53cb16b2014-06-12 11:26:29 -0700281 PROT_READ | PROT_WRITE, MAP_PRIVATE, &error_msg));
282 if (elf.get() == nullptr) {
283 LOG(ERROR) << "unable to open oat file " << input_oat->GetPath() << " : " << error_msg;
284 return false;
285 }
286
Igor Murashkin46774762014-10-22 11:37:02 -0700287 bool skip_patching_oat = false;
288 MaybePic is_oat_pic = IsOatPic(elf.get());
289 if (is_oat_pic >= ERROR_FIRST) {
290 // Error logged by IsOatPic
291 return false;
292 } else if (is_oat_pic == PIC) {
293 // Do not need to do ELF-file patching. Create a symlink and skip the ELF patching.
294 if (!ReplaceOatFileWithSymlink(input_oat->GetPath(),
295 output_oat->GetPath(),
296 output_oat_opened_from_fd,
297 new_oat_out)) {
298 // Errors already logged by above call.
299 return false;
300 }
301 // Don't patch the OAT, since we just symlinked it. Image still needs patching.
302 skip_patching_oat = true;
303 } else {
304 CHECK(is_oat_pic == NOT_PIC);
305 }
306
Mathieu Chartier2d721012014-11-10 11:08:06 -0800307 PatchOat p(isa, elf.release(), image.release(), ispc->GetLiveBitmap(), ispc->GetMemMap(),
Alex Light53cb16b2014-06-12 11:26:29 -0700308 delta, timings);
309 t.NewTiming("Patching files");
Igor Murashkin46774762014-10-22 11:37:02 -0700310 if (!skip_patching_oat && !p.PatchElf()) {
Alex Lighta59dd802014-07-02 16:28:08 -0700311 LOG(ERROR) << "Failed to patch oat file " << input_oat->GetPath();
Alex Light53cb16b2014-06-12 11:26:29 -0700312 return false;
313 }
314 if (!p.PatchImage()) {
Alex Lighta59dd802014-07-02 16:28:08 -0700315 LOG(ERROR) << "Failed to patch image file " << input_image->GetPath();
Alex Light53cb16b2014-06-12 11:26:29 -0700316 return false;
317 }
318
319 t.NewTiming("Writing files");
Igor Murashkin46774762014-10-22 11:37:02 -0700320 if (!skip_patching_oat && !p.WriteElf(output_oat)) {
321 LOG(ERROR) << "Failed to write oat file " << input_oat->GetPath();
Alex Light53cb16b2014-06-12 11:26:29 -0700322 return false;
323 }
324 if (!p.WriteImage(output_image)) {
Igor Murashkin46774762014-10-22 11:37:02 -0700325 LOG(ERROR) << "Failed to write image file " << input_image->GetPath();
Alex Light53cb16b2014-06-12 11:26:29 -0700326 return false;
327 }
328 return true;
329}
330
331bool PatchOat::WriteElf(File* out) {
Alex Lighteefbe392014-07-08 09:53:18 -0700332 TimingLogger::ScopedTiming t("Writing Elf File", timings_);
Alex Lighta59dd802014-07-02 16:28:08 -0700333
Alex Light53cb16b2014-06-12 11:26:29 -0700334 CHECK(oat_file_.get() != nullptr);
335 CHECK(out != nullptr);
336 size_t expect = oat_file_->Size();
337 if (out->WriteFully(reinterpret_cast<char*>(oat_file_->Begin()), expect) &&
338 out->SetLength(expect) == 0) {
339 return true;
340 } else {
341 LOG(ERROR) << "Writing to oat file " << out->GetPath() << " failed.";
342 return false;
343 }
344}
345
346bool PatchOat::WriteImage(File* out) {
Alex Lighteefbe392014-07-08 09:53:18 -0700347 TimingLogger::ScopedTiming t("Writing image File", timings_);
Alex Lighta59dd802014-07-02 16:28:08 -0700348 std::string error_msg;
349
Alex Lightcf4bf382014-07-24 11:29:14 -0700350 ScopedFlock img_flock;
351 img_flock.Init(out, &error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -0700352
Alex Light53cb16b2014-06-12 11:26:29 -0700353 CHECK(image_ != nullptr);
354 CHECK(out != nullptr);
355 size_t expect = image_->Size();
356 if (out->WriteFully(reinterpret_cast<char*>(image_->Begin()), expect) &&
357 out->SetLength(expect) == 0) {
358 return true;
359 } else {
360 LOG(ERROR) << "Writing to image file " << out->GetPath() << " failed.";
361 return false;
362 }
363}
364
Igor Murashkin46774762014-10-22 11:37:02 -0700365bool PatchOat::IsImagePic(const ImageHeader& image_header, const std::string& image_path) {
366 if (!image_header.CompilePic()) {
367 if (kIsDebugBuild) {
368 LOG(INFO) << "image at location " << image_path << " was *not* compiled pic";
369 }
370 return false;
371 }
372
373 if (kIsDebugBuild) {
374 LOG(INFO) << "image at location " << image_path << " was compiled PIC";
375 }
376
377 return true;
378}
379
380PatchOat::MaybePic PatchOat::IsOatPic(const ElfFile* oat_in) {
381 if (oat_in == nullptr) {
382 LOG(ERROR) << "No ELF input oat fie available";
383 return ERROR_OAT_FILE;
384 }
385
386 const std::string& file_path = oat_in->GetFile().GetPath();
387
388 const OatHeader* oat_header = GetOatHeader(oat_in);
389 if (oat_header == nullptr) {
390 LOG(ERROR) << "Failed to find oat header in oat file " << file_path;
391 return ERROR_OAT_FILE;
392 }
393
394 if (!oat_header->IsValid()) {
395 LOG(ERROR) << "Elf file " << file_path << " has an invalid oat header";
396 return ERROR_OAT_FILE;
397 }
398
399 bool is_pic = oat_header->IsPic();
400 if (kIsDebugBuild) {
401 LOG(INFO) << "Oat file at " << file_path << " is " << (is_pic ? "PIC" : "not pic");
402 }
403
404 return is_pic ? PIC : NOT_PIC;
405}
406
407bool PatchOat::ReplaceOatFileWithSymlink(const std::string& input_oat_filename,
408 const std::string& output_oat_filename,
409 bool output_oat_opened_from_fd,
410 bool new_oat_out) {
411 // Need a file when we are PIC, since we symlink over it. Refusing to symlink into FD.
412 if (output_oat_opened_from_fd) {
413 // TODO: installd uses --output-oat-fd. Should we change class linking logic for PIC?
414 LOG(ERROR) << "No output oat filename specified, needs filename for when we are PIC";
415 return false;
416 }
417
418 // Image was PIC. Create symlink where the oat is supposed to go.
419 if (!new_oat_out) {
420 LOG(ERROR) << "Oat file " << output_oat_filename << " already exists, refusing to overwrite";
421 return false;
422 }
423
424 // Delete the original file, since we won't need it.
425 TEMP_FAILURE_RETRY(unlink(output_oat_filename.c_str()));
426
427 // Create a symlink from the old oat to the new oat
428 if (symlink(input_oat_filename.c_str(), output_oat_filename.c_str()) < 0) {
429 int err = errno;
430 LOG(ERROR) << "Failed to create symlink at " << output_oat_filename
431 << " error(" << err << "): " << strerror(err);
432 return false;
433 }
434
435 if (kIsDebugBuild) {
436 LOG(INFO) << "Created symlink " << output_oat_filename << " -> " << input_oat_filename;
437 }
438
439 return true;
440}
441
Alex Light53cb16b2014-06-12 11:26:29 -0700442bool PatchOat::PatchImage() {
443 ImageHeader* image_header = reinterpret_cast<ImageHeader*>(image_->Begin());
444 CHECK_GT(image_->Size(), sizeof(ImageHeader));
445 // These are the roots from the original file.
446 mirror::Object* img_roots = image_header->GetImageRoots();
447 image_header->RelocateImage(delta_);
448
449 VisitObject(img_roots);
450 if (!image_header->IsValid()) {
451 LOG(ERROR) << "reloction renders image header invalid";
452 return false;
453 }
454
455 {
Alex Lighteefbe392014-07-08 09:53:18 -0700456 TimingLogger::ScopedTiming t("Walk Bitmap", timings_);
Alex Light53cb16b2014-06-12 11:26:29 -0700457 // Walk the bitmap.
458 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
459 bitmap_->Walk(PatchOat::BitmapCallback, this);
460 }
461 return true;
462}
463
464bool PatchOat::InHeap(mirror::Object* o) {
465 uintptr_t begin = reinterpret_cast<uintptr_t>(heap_->Begin());
466 uintptr_t end = reinterpret_cast<uintptr_t>(heap_->End());
467 uintptr_t obj = reinterpret_cast<uintptr_t>(o);
468 return o == nullptr || (begin <= obj && obj < end);
469}
470
471void PatchOat::PatchVisitor::operator() (mirror::Object* obj, MemberOffset off,
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700472 bool is_static_unused ATTRIBUTE_UNUSED) const {
Alex Light53cb16b2014-06-12 11:26:29 -0700473 mirror::Object* referent = obj->GetFieldObject<mirror::Object, kVerifyNone>(off);
474 DCHECK(patcher_->InHeap(referent)) << "Referent is not in the heap.";
475 mirror::Object* moved_object = patcher_->RelocatedAddressOf(referent);
476 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(off, moved_object);
477}
478
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700479void PatchOat::PatchVisitor::operator() (mirror::Class* cls ATTRIBUTE_UNUSED,
480 mirror::Reference* ref) const {
Alex Light53cb16b2014-06-12 11:26:29 -0700481 MemberOffset off = mirror::Reference::ReferentOffset();
482 mirror::Object* referent = ref->GetReferent();
483 DCHECK(patcher_->InHeap(referent)) << "Referent is not in the heap.";
484 mirror::Object* moved_object = patcher_->RelocatedAddressOf(referent);
485 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(off, moved_object);
486}
487
488mirror::Object* PatchOat::RelocatedCopyOf(mirror::Object* obj) {
489 if (obj == nullptr) {
490 return nullptr;
491 }
492 DCHECK_GT(reinterpret_cast<uintptr_t>(obj), reinterpret_cast<uintptr_t>(heap_->Begin()));
493 DCHECK_LT(reinterpret_cast<uintptr_t>(obj), reinterpret_cast<uintptr_t>(heap_->End()));
494 uintptr_t heap_off =
495 reinterpret_cast<uintptr_t>(obj) - reinterpret_cast<uintptr_t>(heap_->Begin());
496 DCHECK_LT(heap_off, image_->Size());
497 return reinterpret_cast<mirror::Object*>(image_->Begin() + heap_off);
498}
499
500mirror::Object* PatchOat::RelocatedAddressOf(mirror::Object* obj) {
501 if (obj == nullptr) {
502 return nullptr;
503 } else {
Ian Rogers13735952014-10-08 12:43:28 -0700504 return reinterpret_cast<mirror::Object*>(reinterpret_cast<uint8_t*>(obj) + delta_);
Alex Light53cb16b2014-06-12 11:26:29 -0700505 }
506}
507
Igor Murashkin46774762014-10-22 11:37:02 -0700508const OatHeader* PatchOat::GetOatHeader(const ElfFile* elf_file) {
509 if (elf_file->Is64Bit()) {
510 return GetOatHeader<ElfFileImpl64>(elf_file->GetImpl64());
511 } else {
512 return GetOatHeader<ElfFileImpl32>(elf_file->GetImpl32());
513 }
514}
515
516template <typename ElfFileImpl>
517const OatHeader* PatchOat::GetOatHeader(const ElfFileImpl* elf_file) {
518 auto rodata_sec = elf_file->FindSectionByName(".rodata");
519 if (rodata_sec == nullptr) {
520 return nullptr;
521 }
522
523 OatHeader* oat_header = reinterpret_cast<OatHeader*>(elf_file->Begin() + rodata_sec->sh_offset);
524 return oat_header;
525}
526
Alex Light53cb16b2014-06-12 11:26:29 -0700527// Called by BitmapCallback
528void PatchOat::VisitObject(mirror::Object* object) {
529 mirror::Object* copy = RelocatedCopyOf(object);
530 CHECK(copy != nullptr);
531 if (kUseBakerOrBrooksReadBarrier) {
532 object->AssertReadBarrierPointer();
533 if (kUseBrooksReadBarrier) {
534 mirror::Object* moved_to = RelocatedAddressOf(object);
535 copy->SetReadBarrierPointer(moved_to);
536 DCHECK_EQ(copy->GetReadBarrierPointer(), moved_to);
537 }
538 }
539 PatchOat::PatchVisitor visitor(this, copy);
540 object->VisitReferences<true, kVerifyNone>(visitor, visitor);
541 if (object->IsArtMethod<kVerifyNone>()) {
Mathieu Chartier2d721012014-11-10 11:08:06 -0800542 FixupMethod(down_cast<mirror::ArtMethod*>(object), down_cast<mirror::ArtMethod*>(copy));
Alex Light53cb16b2014-06-12 11:26:29 -0700543 }
544}
545
546void PatchOat::FixupMethod(mirror::ArtMethod* object, mirror::ArtMethod* copy) {
Mathieu Chartier2d721012014-11-10 11:08:06 -0800547 const size_t pointer_size = InstructionSetPointerSize(isa_);
Alex Light53cb16b2014-06-12 11:26:29 -0700548 // Just update the entry points if it looks like we should.
Alex Lighteefbe392014-07-08 09:53:18 -0700549 // TODO: sanity check all the pointers' values
Alex Light53cb16b2014-06-12 11:26:29 -0700550 uintptr_t quick= reinterpret_cast<uintptr_t>(
Mathieu Chartier2d721012014-11-10 11:08:06 -0800551 object->GetEntryPointFromQuickCompiledCodePtrSize<kVerifyNone>(pointer_size));
Alex Light53cb16b2014-06-12 11:26:29 -0700552 if (quick != 0) {
Mathieu Chartier2d721012014-11-10 11:08:06 -0800553 copy->SetEntryPointFromQuickCompiledCodePtrSize(reinterpret_cast<void*>(quick + delta_),
554 pointer_size);
Alex Light53cb16b2014-06-12 11:26:29 -0700555 }
556 uintptr_t interpreter = reinterpret_cast<uintptr_t>(
Mathieu Chartier2d721012014-11-10 11:08:06 -0800557 object->GetEntryPointFromInterpreterPtrSize<kVerifyNone>(pointer_size));
Alex Light53cb16b2014-06-12 11:26:29 -0700558 if (interpreter != 0) {
Mathieu Chartier2d721012014-11-10 11:08:06 -0800559 copy->SetEntryPointFromInterpreterPtrSize(
560 reinterpret_cast<mirror::EntryPointFromInterpreter*>(interpreter + delta_), pointer_size);
Alex Light53cb16b2014-06-12 11:26:29 -0700561 }
562
Mathieu Chartier2d721012014-11-10 11:08:06 -0800563 uintptr_t native_method = reinterpret_cast<uintptr_t>(
564 object->GetEntryPointFromJniPtrSize(pointer_size));
Alex Light53cb16b2014-06-12 11:26:29 -0700565 if (native_method != 0) {
Mathieu Chartier2d721012014-11-10 11:08:06 -0800566 copy->SetEntryPointFromJniPtrSize(reinterpret_cast<void*>(native_method + delta_),
567 pointer_size);
Alex Light53cb16b2014-06-12 11:26:29 -0700568 }
Alex Light53cb16b2014-06-12 11:26:29 -0700569}
570
Igor Murashkin46774762014-10-22 11:37:02 -0700571bool PatchOat::Patch(File* input_oat, off_t delta, File* output_oat, TimingLogger* timings,
572 bool output_oat_opened_from_fd, bool new_oat_out) {
Alex Light53cb16b2014-06-12 11:26:29 -0700573 CHECK(input_oat != nullptr);
574 CHECK(output_oat != nullptr);
575 CHECK_GE(input_oat->Fd(), 0);
576 CHECK_GE(output_oat->Fd(), 0);
Alex Lighteefbe392014-07-08 09:53:18 -0700577 TimingLogger::ScopedTiming t("Setup Oat File Patching", timings);
Alex Light53cb16b2014-06-12 11:26:29 -0700578
579 std::string error_msg;
Igor Murashkin46774762014-10-22 11:37:02 -0700580 std::unique_ptr<ElfFile> elf(ElfFile::Open(input_oat,
Alex Light53cb16b2014-06-12 11:26:29 -0700581 PROT_READ | PROT_WRITE, MAP_PRIVATE, &error_msg));
582 if (elf.get() == nullptr) {
583 LOG(ERROR) << "unable to open oat file " << input_oat->GetPath() << " : " << error_msg;
584 return false;
585 }
586
Igor Murashkin46774762014-10-22 11:37:02 -0700587 MaybePic is_oat_pic = IsOatPic(elf.get());
588 if (is_oat_pic >= ERROR_FIRST) {
589 // Error logged by IsOatPic
590 return false;
591 } else if (is_oat_pic == PIC) {
592 // Do not need to do ELF-file patching. Create a symlink and skip the rest.
593 // Any errors will be logged by the function call.
594 return ReplaceOatFileWithSymlink(input_oat->GetPath(),
595 output_oat->GetPath(),
596 output_oat_opened_from_fd,
597 new_oat_out);
598 } else {
599 CHECK(is_oat_pic == NOT_PIC);
600 }
601
Alex Light53cb16b2014-06-12 11:26:29 -0700602 PatchOat p(elf.release(), delta, timings);
603 t.NewTiming("Patch Oat file");
604 if (!p.PatchElf()) {
605 return false;
606 }
607
608 t.NewTiming("Writing oat file");
609 if (!p.WriteElf(output_oat)) {
610 return false;
611 }
612 return true;
613}
614
Tong Shen62d1ca32014-09-03 17:24:56 -0700615template <typename ElfFileImpl, typename ptr_t>
616bool PatchOat::CheckOatFile(ElfFileImpl* oat_file) {
617 auto patches_sec = oat_file->FindSectionByName(".oat_patches");
618 if (patches_sec->sh_type != SHT_OAT_PATCH) {
Alex Light53cb16b2014-06-12 11:26:29 -0700619 return false;
620 }
Tong Shen62d1ca32014-09-03 17:24:56 -0700621 ptr_t* patches = reinterpret_cast<ptr_t*>(oat_file->Begin() + patches_sec->sh_offset);
622 ptr_t* patches_end = patches + (patches_sec->sh_size / sizeof(ptr_t));
623 auto oat_data_sec = oat_file->FindSectionByName(".rodata");
624 auto oat_text_sec = oat_file->FindSectionByName(".text");
Alex Light53cb16b2014-06-12 11:26:29 -0700625 if (oat_data_sec == nullptr) {
626 return false;
627 }
628 if (oat_text_sec == nullptr) {
629 return false;
630 }
631 if (oat_text_sec->sh_offset <= oat_data_sec->sh_offset) {
632 return false;
633 }
634
635 for (; patches < patches_end; patches++) {
636 if (oat_text_sec->sh_size <= *patches) {
637 return false;
638 }
639 }
640
641 return true;
642}
643
Tong Shen62d1ca32014-09-03 17:24:56 -0700644template <typename ElfFileImpl>
645bool PatchOat::PatchOatHeader(ElfFileImpl* oat_file) {
646 auto rodata_sec = oat_file->FindSectionByName(".rodata");
Alex Lighta59dd802014-07-02 16:28:08 -0700647 if (rodata_sec == nullptr) {
648 return false;
649 }
Tong Shen62d1ca32014-09-03 17:24:56 -0700650 OatHeader* oat_header = reinterpret_cast<OatHeader*>(oat_file->Begin() + rodata_sec->sh_offset);
Alex Lighta59dd802014-07-02 16:28:08 -0700651 if (!oat_header->IsValid()) {
Tong Shen62d1ca32014-09-03 17:24:56 -0700652 LOG(ERROR) << "Elf file " << oat_file->GetFile().GetPath() << " has an invalid oat header";
Alex Lighta59dd802014-07-02 16:28:08 -0700653 return false;
654 }
655 oat_header->RelocateOat(delta_);
656 return true;
657}
658
Alex Light53cb16b2014-06-12 11:26:29 -0700659bool PatchOat::PatchElf() {
Ian Rogersd4c4d952014-10-16 20:31:53 -0700660 if (oat_file_->Is64Bit())
Tong Shen62d1ca32014-09-03 17:24:56 -0700661 return PatchElf<ElfFileImpl64>(oat_file_->GetImpl64());
662 else
663 return PatchElf<ElfFileImpl32>(oat_file_->GetImpl32());
664}
665
666template <typename ElfFileImpl>
667bool PatchOat::PatchElf(ElfFileImpl* oat_file) {
Alex Lighta59dd802014-07-02 16:28:08 -0700668 TimingLogger::ScopedTiming t("Fixup Elf Text Section", timings_);
Tong Shen62d1ca32014-09-03 17:24:56 -0700669 if (!PatchTextSection<ElfFileImpl>(oat_file)) {
Alex Lighta59dd802014-07-02 16:28:08 -0700670 return false;
671 }
672
Tong Shen62d1ca32014-09-03 17:24:56 -0700673 if (!PatchOatHeader<ElfFileImpl>(oat_file)) {
Alex Lighta59dd802014-07-02 16:28:08 -0700674 return false;
675 }
676
677 bool need_fixup = false;
Ian Rogersd4c4d952014-10-16 20:31:53 -0700678 for (unsigned int i = 0; i < oat_file->GetProgramHeaderNum(); ++i) {
Tong Shen62d1ca32014-09-03 17:24:56 -0700679 auto hdr = oat_file->GetProgramHeader(i);
Ian Rogersd4c4d952014-10-16 20:31:53 -0700680 if ((hdr->p_vaddr != 0 && hdr->p_vaddr != hdr->p_offset) ||
681 (hdr->p_paddr != 0 && hdr->p_paddr != hdr->p_offset)) {
Alex Lighta59dd802014-07-02 16:28:08 -0700682 need_fixup = true;
Ian Rogersd4c4d952014-10-16 20:31:53 -0700683 break;
Alex Light53cb16b2014-06-12 11:26:29 -0700684 }
685 }
Alex Lighta59dd802014-07-02 16:28:08 -0700686 if (!need_fixup) {
687 // This was never passed through ElfFixup so all headers/symbols just have their offset as
688 // their addr. Therefore we do not need to update these parts.
689 return true;
690 }
Tong Shen62d1ca32014-09-03 17:24:56 -0700691
692 t.NewTiming("Fixup Elf Headers");
693 // Fixup Phdr's
694 oat_file->FixupProgramHeaders(delta_);
695
Alex Lighta59dd802014-07-02 16:28:08 -0700696 t.NewTiming("Fixup Section Headers");
Tong Shen62d1ca32014-09-03 17:24:56 -0700697 // Fixup Shdr's
698 oat_file->FixupSectionHeaders(delta_);
Alex Light53cb16b2014-06-12 11:26:29 -0700699
Alex Lighta59dd802014-07-02 16:28:08 -0700700 t.NewTiming("Fixup Dynamics");
Tong Shen62d1ca32014-09-03 17:24:56 -0700701 oat_file->FixupDynamic(delta_);
Alex Light53cb16b2014-06-12 11:26:29 -0700702
703 t.NewTiming("Fixup Elf Symbols");
704 // Fixup dynsym
Tong Shen62d1ca32014-09-03 17:24:56 -0700705 if (!oat_file->FixupSymbols(delta_, true)) {
Alex Light53cb16b2014-06-12 11:26:29 -0700706 return false;
707 }
Alex Light53cb16b2014-06-12 11:26:29 -0700708 // Fixup symtab
Tong Shen62d1ca32014-09-03 17:24:56 -0700709 if (!oat_file->FixupSymbols(delta_, false)) {
710 return false;
Alex Light53cb16b2014-06-12 11:26:29 -0700711 }
712
Yevgeny Roubane3ea8382014-08-08 16:29:38 +0700713 t.NewTiming("Fixup Debug Sections");
Tong Shen62d1ca32014-09-03 17:24:56 -0700714 if (!oat_file->FixupDebugSections(delta_)) {
Yevgeny Roubane3ea8382014-08-08 16:29:38 +0700715 return false;
716 }
717
Alex Light53cb16b2014-06-12 11:26:29 -0700718 return true;
719}
720
Tong Shen62d1ca32014-09-03 17:24:56 -0700721template <typename ElfFileImpl>
722bool PatchOat::PatchTextSection(ElfFileImpl* oat_file) {
723 auto patches_sec = oat_file->FindSectionByName(".oat_patches");
Alex Light53cb16b2014-06-12 11:26:29 -0700724 if (patches_sec == nullptr) {
Alex Lighta59dd802014-07-02 16:28:08 -0700725 LOG(ERROR) << ".oat_patches section not found. Aborting patch";
Alex Light53cb16b2014-06-12 11:26:29 -0700726 return false;
727 }
Alex Light4b0d2d92014-08-06 13:37:23 -0700728 if (patches_sec->sh_type != SHT_OAT_PATCH) {
729 LOG(ERROR) << "Unexpected type of .oat_patches";
730 return false;
731 }
732
733 switch (patches_sec->sh_entsize) {
734 case sizeof(uint32_t):
Tong Shen62d1ca32014-09-03 17:24:56 -0700735 return PatchTextSection<ElfFileImpl, uint32_t>(oat_file);
Alex Light4b0d2d92014-08-06 13:37:23 -0700736 case sizeof(uint64_t):
Tong Shen62d1ca32014-09-03 17:24:56 -0700737 return PatchTextSection<ElfFileImpl, uint64_t>(oat_file);
Alex Light4b0d2d92014-08-06 13:37:23 -0700738 default:
739 LOG(ERROR) << ".oat_patches Entsize of " << patches_sec->sh_entsize << "bits "
740 << "is not valid";
741 return false;
742 }
743}
744
Tong Shen62d1ca32014-09-03 17:24:56 -0700745template <typename ElfFileImpl, typename patch_loc_t>
746bool PatchOat::PatchTextSection(ElfFileImpl* oat_file) {
747 bool oat_file_valid = CheckOatFile<ElfFileImpl, patch_loc_t>(oat_file);
748 CHECK(oat_file_valid) << "Oat file invalid";
749 auto patches_sec = oat_file->FindSectionByName(".oat_patches");
750 patch_loc_t* patches = reinterpret_cast<patch_loc_t*>(oat_file->Begin() + patches_sec->sh_offset);
751 patch_loc_t* patches_end = patches + (patches_sec->sh_size / sizeof(patch_loc_t));
752 auto oat_text_sec = oat_file->FindSectionByName(".text");
Alex Light53cb16b2014-06-12 11:26:29 -0700753 CHECK(oat_text_sec != nullptr);
Ian Rogers13735952014-10-08 12:43:28 -0700754 uint8_t* to_patch = oat_file->Begin() + oat_text_sec->sh_offset;
Alex Light53cb16b2014-06-12 11:26:29 -0700755 uintptr_t to_patch_end = reinterpret_cast<uintptr_t>(to_patch) + oat_text_sec->sh_size;
756
757 for (; patches < patches_end; patches++) {
758 CHECK_LT(*patches, oat_text_sec->sh_size) << "Bad Patch";
759 uint32_t* patch_loc = reinterpret_cast<uint32_t*>(to_patch + *patches);
760 CHECK_LT(reinterpret_cast<uintptr_t>(patch_loc), to_patch_end);
761 *patch_loc += delta_;
762 }
Alex Light53cb16b2014-06-12 11:26:29 -0700763 return true;
764}
765
766static int orig_argc;
767static char** orig_argv;
768
769static std::string CommandLine() {
770 std::vector<std::string> command;
771 for (int i = 0; i < orig_argc; ++i) {
772 command.push_back(orig_argv[i]);
773 }
774 return Join(command, ' ');
775}
776
777static void UsageErrorV(const char* fmt, va_list ap) {
778 std::string error;
779 StringAppendV(&error, fmt, ap);
780 LOG(ERROR) << error;
781}
782
783static void UsageError(const char* fmt, ...) {
784 va_list ap;
785 va_start(ap, fmt);
786 UsageErrorV(fmt, ap);
787 va_end(ap);
788}
789
Ian Rogers7223d442014-10-10 20:05:39 -0700790[[noreturn]] static void Usage(const char *fmt, ...) {
Alex Light53cb16b2014-06-12 11:26:29 -0700791 va_list ap;
792 va_start(ap, fmt);
793 UsageErrorV(fmt, ap);
794 va_end(ap);
795
796 UsageError("Command: %s", CommandLine().c_str());
797 UsageError("Usage: patchoat [options]...");
798 UsageError("");
799 UsageError(" --instruction-set=<isa>: Specifies the instruction set the patched code is");
800 UsageError(" compiled for. Required if you use --input-oat-location");
801 UsageError("");
802 UsageError(" --input-oat-file=<file.oat>: Specifies the exact filename of the oat file to be");
803 UsageError(" patched.");
804 UsageError("");
805 UsageError(" --input-oat-fd=<file-descriptor>: Specifies the file-descriptor of the oat file");
806 UsageError(" to be patched.");
807 UsageError("");
808 UsageError(" --input-oat-location=<file.oat>: Specifies the 'location' to read the patched");
809 UsageError(" oat file from. If used one must also supply the --instruction-set");
810 UsageError("");
811 UsageError(" --input-image-location=<file.art>: Specifies the 'location' of the image file to");
812 UsageError(" be patched. If --instruction-set is not given it will use the instruction set");
813 UsageError(" extracted from the --input-oat-file.");
814 UsageError("");
815 UsageError(" --output-oat-file=<file.oat>: Specifies the exact file to write the patched oat");
816 UsageError(" file to.");
817 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700818 UsageError(" --output-oat-fd=<file-descriptor>: Specifies the file-descriptor to write the");
819 UsageError(" the patched oat file to.");
820 UsageError("");
821 UsageError(" --output-image-file=<file.art>: Specifies the exact file to write the patched");
822 UsageError(" image file to.");
823 UsageError("");
824 UsageError(" --output-image-fd=<file-descriptor>: Specifies the file-descriptor to write the");
825 UsageError(" the patched image file to.");
826 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700827 UsageError(" --orig-base-offset=<original-base-offset>: Specify the base offset the input file");
828 UsageError(" was compiled with. This is needed if one is specifying a --base-offset");
829 UsageError("");
830 UsageError(" --base-offset=<new-base-offset>: Specify the base offset we will repatch the");
831 UsageError(" given files to use. This requires that --orig-base-offset is also given.");
832 UsageError("");
833 UsageError(" --base-offset-delta=<delta>: Specify the amount to change the old base-offset by.");
834 UsageError(" This value may be negative.");
835 UsageError("");
836 UsageError(" --patched-image-file=<file.art>: Use the same patch delta as was used to patch");
837 UsageError(" the given image file.");
838 UsageError("");
839 UsageError(" --patched-image-location=<file.art>: Use the same patch delta as was used to");
840 UsageError(" patch the given image location. If used one must also specify the");
Alex Lighta59dd802014-07-02 16:28:08 -0700841 UsageError(" --instruction-set flag. It will search for this image in the same way that");
842 UsageError(" is done when loading one.");
Alex Light53cb16b2014-06-12 11:26:29 -0700843 UsageError("");
Alex Lightcf4bf382014-07-24 11:29:14 -0700844 UsageError(" --lock-output: Obtain a flock on output oat file before starting.");
845 UsageError("");
846 UsageError(" --no-lock-output: Do not attempt to obtain a flock on output oat file.");
847 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700848 UsageError(" --dump-timings: dump out patch timing information");
849 UsageError("");
850 UsageError(" --no-dump-timings: do not dump out patch timing information");
851 UsageError("");
852
853 exit(EXIT_FAILURE);
854}
855
Alex Lighteefbe392014-07-08 09:53:18 -0700856static bool ReadBaseDelta(const char* name, off_t* delta, std::string* error_msg) {
Alex Light53cb16b2014-06-12 11:26:29 -0700857 CHECK(name != nullptr);
858 CHECK(delta != nullptr);
859 std::unique_ptr<File> file;
860 if (OS::FileExists(name)) {
861 file.reset(OS::OpenFileForReading(name));
862 if (file.get() == nullptr) {
Alex Lighteefbe392014-07-08 09:53:18 -0700863 *error_msg = "Failed to open file %s for reading";
Alex Light53cb16b2014-06-12 11:26:29 -0700864 return false;
865 }
866 } else {
Alex Lighteefbe392014-07-08 09:53:18 -0700867 *error_msg = "File %s does not exist";
Alex Light53cb16b2014-06-12 11:26:29 -0700868 return false;
869 }
870 CHECK(file.get() != nullptr);
871 ImageHeader hdr;
872 if (sizeof(hdr) != file->Read(reinterpret_cast<char*>(&hdr), sizeof(hdr), 0)) {
Alex Lighteefbe392014-07-08 09:53:18 -0700873 *error_msg = "Failed to read file %s";
Alex Light53cb16b2014-06-12 11:26:29 -0700874 return false;
875 }
876 if (!hdr.IsValid()) {
Alex Lighteefbe392014-07-08 09:53:18 -0700877 *error_msg = "%s does not contain a valid image header.";
Alex Light53cb16b2014-06-12 11:26:29 -0700878 return false;
879 }
880 *delta = hdr.GetPatchDelta();
881 return true;
882}
883
884static File* CreateOrOpen(const char* name, bool* created) {
885 if (OS::FileExists(name)) {
886 *created = false;
887 return OS::OpenFileReadWrite(name);
888 } else {
889 *created = true;
Alex Lightcf4bf382014-07-24 11:29:14 -0700890 std::unique_ptr<File> f(OS::CreateEmptyFile(name));
891 if (f.get() != nullptr) {
892 if (fchmod(f->Fd(), 0644) != 0) {
893 PLOG(ERROR) << "Unable to make " << name << " world readable";
Brian Carlstrom8c52a3f2014-09-30 16:18:01 -0700894 TEMP_FAILURE_RETRY(unlink(name));
Alex Lightcf4bf382014-07-24 11:29:14 -0700895 return nullptr;
896 }
897 }
898 return f.release();
Alex Light53cb16b2014-06-12 11:26:29 -0700899 }
900}
901
Andreas Gampe4303ba92014-11-06 01:00:46 -0800902// Either try to close the file (close=true), or erase it.
903static bool FinishFile(File* file, bool close) {
904 if (close) {
905 if (file->FlushCloseOrErase() != 0) {
906 PLOG(ERROR) << "Failed to flush and close file.";
907 return false;
908 }
909 return true;
910 } else {
911 file->Erase();
912 return false;
913 }
914}
915
Alex Lighteefbe392014-07-08 09:53:18 -0700916static int patchoat(int argc, char **argv) {
Alex Light53cb16b2014-06-12 11:26:29 -0700917 InitLogging(argv);
Mathieu Chartier6e88ef62014-10-14 15:01:24 -0700918 MemMap::Init();
Alex Light53cb16b2014-06-12 11:26:29 -0700919 const bool debug = kIsDebugBuild;
920 orig_argc = argc;
921 orig_argv = argv;
922 TimingLogger timings("patcher", false, false);
923
924 InitLogging(argv);
925
926 // Skip over the command name.
927 argv++;
928 argc--;
929
930 if (argc == 0) {
931 Usage("No arguments specified");
932 }
933
934 timings.StartTiming("Patchoat");
935
936 // cmd line args
937 bool isa_set = false;
938 InstructionSet isa = kNone;
939 std::string input_oat_filename;
940 std::string input_oat_location;
941 int input_oat_fd = -1;
942 bool have_input_oat = false;
943 std::string input_image_location;
944 std::string output_oat_filename;
Alex Light53cb16b2014-06-12 11:26:29 -0700945 int output_oat_fd = -1;
946 bool have_output_oat = false;
947 std::string output_image_filename;
Alex Light53cb16b2014-06-12 11:26:29 -0700948 int output_image_fd = -1;
949 bool have_output_image = false;
950 uintptr_t base_offset = 0;
951 bool base_offset_set = false;
952 uintptr_t orig_base_offset = 0;
953 bool orig_base_offset_set = false;
954 off_t base_delta = 0;
955 bool base_delta_set = false;
956 std::string patched_image_filename;
957 std::string patched_image_location;
958 bool dump_timings = kIsDebugBuild;
Alex Lightcf4bf382014-07-24 11:29:14 -0700959 bool lock_output = true;
Alex Light53cb16b2014-06-12 11:26:29 -0700960
Ian Rogersd4c4d952014-10-16 20:31:53 -0700961 for (int i = 0; i < argc; ++i) {
Alex Light53cb16b2014-06-12 11:26:29 -0700962 const StringPiece option(argv[i]);
963 const bool log_options = false;
964 if (log_options) {
965 LOG(INFO) << "patchoat: option[" << i << "]=" << argv[i];
966 }
Alex Light53cb16b2014-06-12 11:26:29 -0700967 if (option.starts_with("--instruction-set=")) {
968 isa_set = true;
969 const char* isa_str = option.substr(strlen("--instruction-set=")).data();
Andreas Gampe20c89302014-08-19 17:28:06 -0700970 isa = GetInstructionSetFromString(isa_str);
971 if (isa == kNone) {
972 Usage("Unknown or invalid instruction set %s", isa_str);
Alex Light53cb16b2014-06-12 11:26:29 -0700973 }
974 } else if (option.starts_with("--input-oat-location=")) {
975 if (have_input_oat) {
976 Usage("Only one of --input-oat-file, --input-oat-location and --input-oat-fd may be used.");
977 }
978 have_input_oat = true;
979 input_oat_location = option.substr(strlen("--input-oat-location=")).data();
980 } else if (option.starts_with("--input-oat-file=")) {
981 if (have_input_oat) {
982 Usage("Only one of --input-oat-file, --input-oat-location and --input-oat-fd may be used.");
983 }
984 have_input_oat = true;
985 input_oat_filename = option.substr(strlen("--input-oat-file=")).data();
986 } else if (option.starts_with("--input-oat-fd=")) {
987 if (have_input_oat) {
988 Usage("Only one of --input-oat-file, --input-oat-location and --input-oat-fd may be used.");
989 }
990 have_input_oat = true;
991 const char* oat_fd_str = option.substr(strlen("--input-oat-fd=")).data();
992 if (!ParseInt(oat_fd_str, &input_oat_fd)) {
993 Usage("Failed to parse --input-oat-fd argument '%s' as an integer", oat_fd_str);
994 }
995 if (input_oat_fd < 0) {
996 Usage("--input-oat-fd pass a negative value %d", input_oat_fd);
997 }
998 } else if (option.starts_with("--input-image-location=")) {
999 input_image_location = option.substr(strlen("--input-image-location=")).data();
Alex Light53cb16b2014-06-12 11:26:29 -07001000 } else if (option.starts_with("--output-oat-file=")) {
1001 if (have_output_oat) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001002 Usage("Only one of --output-oat-file, and --output-oat-fd may be used.");
Alex Light53cb16b2014-06-12 11:26:29 -07001003 }
1004 have_output_oat = true;
1005 output_oat_filename = option.substr(strlen("--output-oat-file=")).data();
1006 } else if (option.starts_with("--output-oat-fd=")) {
1007 if (have_output_oat) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001008 Usage("Only one of --output-oat-file, --output-oat-fd may be used.");
Alex Light53cb16b2014-06-12 11:26:29 -07001009 }
1010 have_output_oat = true;
1011 const char* oat_fd_str = option.substr(strlen("--output-oat-fd=")).data();
1012 if (!ParseInt(oat_fd_str, &output_oat_fd)) {
1013 Usage("Failed to parse --output-oat-fd argument '%s' as an integer", oat_fd_str);
1014 }
1015 if (output_oat_fd < 0) {
1016 Usage("--output-oat-fd pass a negative value %d", output_oat_fd);
1017 }
Alex Light53cb16b2014-06-12 11:26:29 -07001018 } else if (option.starts_with("--output-image-file=")) {
1019 if (have_output_image) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001020 Usage("Only one of --output-image-file, and --output-image-fd may be used.");
Alex Light53cb16b2014-06-12 11:26:29 -07001021 }
1022 have_output_image = true;
1023 output_image_filename = option.substr(strlen("--output-image-file=")).data();
1024 } else if (option.starts_with("--output-image-fd=")) {
1025 if (have_output_image) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001026 Usage("Only one of --output-image-file, and --output-image-fd may be used.");
Alex Light53cb16b2014-06-12 11:26:29 -07001027 }
1028 have_output_image = true;
1029 const char* image_fd_str = option.substr(strlen("--output-image-fd=")).data();
1030 if (!ParseInt(image_fd_str, &output_image_fd)) {
1031 Usage("Failed to parse --output-image-fd argument '%s' as an integer", image_fd_str);
1032 }
1033 if (output_image_fd < 0) {
1034 Usage("--output-image-fd pass a negative value %d", output_image_fd);
1035 }
1036 } else if (option.starts_with("--orig-base-offset=")) {
1037 const char* orig_base_offset_str = option.substr(strlen("--orig-base-offset=")).data();
1038 orig_base_offset_set = true;
1039 if (!ParseUint(orig_base_offset_str, &orig_base_offset)) {
1040 Usage("Failed to parse --orig-base-offset argument '%s' as an uintptr_t",
1041 orig_base_offset_str);
1042 }
1043 } else if (option.starts_with("--base-offset=")) {
1044 const char* base_offset_str = option.substr(strlen("--base-offset=")).data();
1045 base_offset_set = true;
1046 if (!ParseUint(base_offset_str, &base_offset)) {
1047 Usage("Failed to parse --base-offset argument '%s' as an uintptr_t", base_offset_str);
1048 }
1049 } else if (option.starts_with("--base-offset-delta=")) {
1050 const char* base_delta_str = option.substr(strlen("--base-offset-delta=")).data();
1051 base_delta_set = true;
1052 if (!ParseInt(base_delta_str, &base_delta)) {
1053 Usage("Failed to parse --base-offset-delta argument '%s' as an off_t", base_delta_str);
1054 }
1055 } else if (option.starts_with("--patched-image-location=")) {
1056 patched_image_location = option.substr(strlen("--patched-image-location=")).data();
1057 } else if (option.starts_with("--patched-image-file=")) {
1058 patched_image_filename = option.substr(strlen("--patched-image-file=")).data();
Alex Lightcf4bf382014-07-24 11:29:14 -07001059 } else if (option == "--lock-output") {
1060 lock_output = true;
1061 } else if (option == "--no-lock-output") {
1062 lock_output = false;
Alex Light53cb16b2014-06-12 11:26:29 -07001063 } else if (option == "--dump-timings") {
1064 dump_timings = true;
1065 } else if (option == "--no-dump-timings") {
1066 dump_timings = false;
1067 } else {
1068 Usage("Unknown argument %s", option.data());
1069 }
1070 }
1071
1072 {
1073 // Only 1 of these may be set.
1074 uint32_t cnt = 0;
1075 cnt += (base_delta_set) ? 1 : 0;
1076 cnt += (base_offset_set && orig_base_offset_set) ? 1 : 0;
1077 cnt += (!patched_image_filename.empty()) ? 1 : 0;
1078 cnt += (!patched_image_location.empty()) ? 1 : 0;
1079 if (cnt > 1) {
1080 Usage("Only one of --base-offset/--orig-base-offset, --base-offset-delta, "
1081 "--patched-image-filename or --patched-image-location may be used.");
1082 } else if (cnt == 0) {
1083 Usage("Must specify --base-offset-delta, --base-offset and --orig-base-offset, "
1084 "--patched-image-location or --patched-image-file");
1085 }
1086 }
1087
1088 if (have_input_oat != have_output_oat) {
1089 Usage("Either both input and output oat must be supplied or niether must be.");
1090 }
1091
1092 if ((!input_image_location.empty()) != have_output_image) {
1093 Usage("Either both input and output image must be supplied or niether must be.");
1094 }
1095
1096 // We know we have both the input and output so rename for clarity.
1097 bool have_image_files = have_output_image;
1098 bool have_oat_files = have_output_oat;
1099
1100 if (!have_oat_files && !have_image_files) {
1101 Usage("Must be patching either an oat or an image file or both.");
1102 }
1103
1104 if (!have_oat_files && !isa_set) {
1105 Usage("Must include ISA if patching an image file without an oat file.");
1106 }
1107
1108 if (!input_oat_location.empty()) {
1109 if (!isa_set) {
1110 Usage("specifying a location requires specifying an instruction set");
1111 }
Alex Lightcf4bf382014-07-24 11:29:14 -07001112 if (!LocationToFilename(input_oat_location, isa, &input_oat_filename)) {
1113 Usage("Unable to find filename for input oat location %s", input_oat_location.c_str());
1114 }
Alex Light53cb16b2014-06-12 11:26:29 -07001115 if (debug) {
1116 LOG(INFO) << "Using input-oat-file " << input_oat_filename;
1117 }
1118 }
Alex Light53cb16b2014-06-12 11:26:29 -07001119 if (!patched_image_location.empty()) {
1120 if (!isa_set) {
1121 Usage("specifying a location requires specifying an instruction set");
1122 }
Alex Lighta59dd802014-07-02 16:28:08 -07001123 std::string system_filename;
1124 bool has_system = false;
1125 std::string cache_filename;
1126 bool has_cache = false;
1127 bool has_android_data_unused = false;
Andreas Gampe3c13a792014-09-18 20:56:04 -07001128 bool is_global_cache = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001129 if (!gc::space::ImageSpace::FindImageFilename(patched_image_location.c_str(), isa,
1130 &system_filename, &has_system, &cache_filename,
Andreas Gampe3c13a792014-09-18 20:56:04 -07001131 &has_android_data_unused, &has_cache,
1132 &is_global_cache)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001133 Usage("Unable to determine image file for location %s", patched_image_location.c_str());
1134 }
1135 if (has_cache) {
1136 patched_image_filename = cache_filename;
1137 } else if (has_system) {
1138 LOG(WARNING) << "Only image file found was in /system for image location "
1139 << patched_image_location;
1140 patched_image_filename = system_filename;
1141 } else {
1142 Usage("Unable to determine image file for location %s", patched_image_location.c_str());
1143 }
Alex Light53cb16b2014-06-12 11:26:29 -07001144 if (debug) {
1145 LOG(INFO) << "Using patched-image-file " << patched_image_filename;
1146 }
1147 }
1148
1149 if (!base_delta_set) {
1150 if (orig_base_offset_set && base_offset_set) {
1151 base_delta_set = true;
1152 base_delta = base_offset - orig_base_offset;
1153 } else if (!patched_image_filename.empty()) {
1154 base_delta_set = true;
1155 std::string error_msg;
Alex Lighteefbe392014-07-08 09:53:18 -07001156 if (!ReadBaseDelta(patched_image_filename.c_str(), &base_delta, &error_msg)) {
Alex Light53cb16b2014-06-12 11:26:29 -07001157 Usage(error_msg.c_str(), patched_image_filename.c_str());
1158 }
1159 } else {
1160 if (base_offset_set) {
1161 Usage("Unable to determine original base offset.");
1162 } else {
1163 Usage("Must supply a desired new offset or delta.");
1164 }
1165 }
1166 }
1167
1168 if (!IsAligned<kPageSize>(base_delta)) {
1169 Usage("Base offset/delta must be alligned to a pagesize (0x%08x) boundary.", kPageSize);
1170 }
1171
1172 // Do we need to cleanup output files if we fail?
1173 bool new_image_out = false;
1174 bool new_oat_out = false;
1175
1176 std::unique_ptr<File> input_oat;
1177 std::unique_ptr<File> output_oat;
1178 std::unique_ptr<File> output_image;
1179
1180 if (have_image_files) {
1181 CHECK(!input_image_location.empty());
1182
1183 if (output_image_fd != -1) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001184 if (output_image_filename.empty()) {
1185 output_image_filename = "output-image-file";
1186 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001187 output_image.reset(new File(output_image_fd, output_image_filename, true));
Alex Light53cb16b2014-06-12 11:26:29 -07001188 } else {
1189 CHECK(!output_image_filename.empty());
1190 output_image.reset(CreateOrOpen(output_image_filename.c_str(), &new_image_out));
1191 }
1192 } else {
1193 CHECK(output_image_filename.empty() && output_image_fd == -1 && input_image_location.empty());
1194 }
1195
1196 if (have_oat_files) {
1197 if (input_oat_fd != -1) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001198 if (input_oat_filename.empty()) {
1199 input_oat_filename = "input-oat-file";
1200 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001201 input_oat.reset(new File(input_oat_fd, input_oat_filename, false));
Igor Murashkin46774762014-10-22 11:37:02 -07001202 if (input_oat == nullptr) {
1203 // Unlikely, but ensure exhaustive logging in non-0 exit code case
1204 LOG(ERROR) << "Failed to open input oat file by its FD" << input_oat_fd;
1205 }
Alex Light53cb16b2014-06-12 11:26:29 -07001206 } else {
1207 CHECK(!input_oat_filename.empty());
1208 input_oat.reset(OS::OpenFileForReading(input_oat_filename.c_str()));
Igor Murashkin46774762014-10-22 11:37:02 -07001209 if (input_oat == nullptr) {
1210 int err = errno;
1211 LOG(ERROR) << "Failed to open input oat file " << input_oat_filename
1212 << ": " << strerror(err) << "(" << err << ")";
Andreas Gampe1c83cbc2014-07-22 18:52:29 -07001213 }
Alex Light53cb16b2014-06-12 11:26:29 -07001214 }
1215
1216 if (output_oat_fd != -1) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001217 if (output_oat_filename.empty()) {
1218 output_oat_filename = "output-oat-file";
Alex Lighta59dd802014-07-02 16:28:08 -07001219 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001220 output_oat.reset(new File(output_oat_fd, output_oat_filename, true));
Igor Murashkin46774762014-10-22 11:37:02 -07001221 if (output_oat == nullptr) {
1222 // Unlikely, but ensure exhaustive logging in non-0 exit code case
1223 LOG(ERROR) << "Failed to open output oat file by its FD" << output_oat_fd;
1224 }
Alex Light53cb16b2014-06-12 11:26:29 -07001225 } else {
1226 CHECK(!output_oat_filename.empty());
1227 output_oat.reset(CreateOrOpen(output_oat_filename.c_str(), &new_oat_out));
Igor Murashkin46774762014-10-22 11:37:02 -07001228 if (output_oat == nullptr) {
1229 int err = errno;
1230 LOG(ERROR) << "Failed to open output oat file " << output_oat_filename
1231 << ": " << strerror(err) << "(" << err << ")";
1232 }
Alex Light53cb16b2014-06-12 11:26:29 -07001233 }
1234 }
1235
Igor Murashkin46774762014-10-22 11:37:02 -07001236 // TODO: get rid of this.
Alex Light53cb16b2014-06-12 11:26:29 -07001237 auto cleanup = [&output_image_filename, &output_oat_filename,
1238 &new_oat_out, &new_image_out, &timings, &dump_timings](bool success) {
1239 timings.EndTiming();
1240 if (!success) {
1241 if (new_oat_out) {
1242 CHECK(!output_oat_filename.empty());
Brian Carlstrom8c52a3f2014-09-30 16:18:01 -07001243 TEMP_FAILURE_RETRY(unlink(output_oat_filename.c_str()));
Alex Light53cb16b2014-06-12 11:26:29 -07001244 }
1245 if (new_image_out) {
1246 CHECK(!output_image_filename.empty());
Brian Carlstrom8c52a3f2014-09-30 16:18:01 -07001247 TEMP_FAILURE_RETRY(unlink(output_image_filename.c_str()));
Alex Light53cb16b2014-06-12 11:26:29 -07001248 }
1249 }
1250 if (dump_timings) {
1251 LOG(INFO) << Dumpable<TimingLogger>(timings);
1252 }
Igor Murashkin46774762014-10-22 11:37:02 -07001253
1254 if (kIsDebugBuild) {
1255 LOG(INFO) << "Cleaning up.. success? " << success;
1256 }
Alex Light53cb16b2014-06-12 11:26:29 -07001257 };
1258
Igor Murashkin46774762014-10-22 11:37:02 -07001259 if (have_oat_files && (input_oat.get() == nullptr || output_oat.get() == nullptr)) {
1260 LOG(ERROR) << "Failed to open input/output oat files";
1261 cleanup(false);
1262 return EXIT_FAILURE;
1263 } else if (have_image_files && output_image.get() == nullptr) {
1264 LOG(ERROR) << "Failed to open output image file";
Alex Lightcf4bf382014-07-24 11:29:14 -07001265 cleanup(false);
1266 return EXIT_FAILURE;
1267 }
1268
Igor Murashkin46774762014-10-22 11:37:02 -07001269 if (debug) {
1270 LOG(INFO) << "moving offset by " << base_delta
1271 << " (0x" << std::hex << base_delta << ") bytes or "
1272 << std::dec << (base_delta/kPageSize) << " pages.";
1273 }
1274
1275 // TODO: is it going to be promatic to unlink a file that was flock-ed?
Alex Lightcf4bf382014-07-24 11:29:14 -07001276 ScopedFlock output_oat_lock;
1277 if (lock_output) {
1278 std::string error_msg;
1279 if (have_oat_files && !output_oat_lock.Init(output_oat.get(), &error_msg)) {
1280 LOG(ERROR) << "Unable to lock output oat " << output_image->GetPath() << ": " << error_msg;
1281 cleanup(false);
1282 return EXIT_FAILURE;
1283 }
1284 }
1285
Alex Light53cb16b2014-06-12 11:26:29 -07001286 bool ret;
1287 if (have_image_files && have_oat_files) {
1288 TimingLogger::ScopedTiming pt("patch image and oat", &timings);
1289 ret = PatchOat::Patch(input_oat.get(), input_image_location, base_delta,
Igor Murashkin46774762014-10-22 11:37:02 -07001290 output_oat.get(), output_image.get(), isa, &timings,
1291 output_oat_fd >= 0, // was it opened from FD?
1292 new_oat_out);
Andreas Gampe4303ba92014-11-06 01:00:46 -08001293 // The order here doesn't matter. If the first one is successfully saved and the second one
1294 // erased, ImageSpace will still detect a problem and not use the files.
1295 ret = ret && FinishFile(output_image.get(), ret);
1296 ret = ret && FinishFile(output_oat.get(), ret);
Alex Light53cb16b2014-06-12 11:26:29 -07001297 } else if (have_oat_files) {
1298 TimingLogger::ScopedTiming pt("patch oat", &timings);
Igor Murashkin46774762014-10-22 11:37:02 -07001299 ret = PatchOat::Patch(input_oat.get(), base_delta, output_oat.get(), &timings,
1300 output_oat_fd >= 0, // was it opened from FD?
1301 new_oat_out);
Andreas Gampe4303ba92014-11-06 01:00:46 -08001302 ret = ret && FinishFile(output_oat.get(), ret);
Igor Murashkin46774762014-10-22 11:37:02 -07001303 } else if (have_image_files) {
Alex Light53cb16b2014-06-12 11:26:29 -07001304 TimingLogger::ScopedTiming pt("patch image", &timings);
Alex Lighteefbe392014-07-08 09:53:18 -07001305 ret = PatchOat::Patch(input_image_location, base_delta, output_image.get(), isa, &timings);
Andreas Gampe4303ba92014-11-06 01:00:46 -08001306 ret = ret && FinishFile(output_image.get(), ret);
Igor Murashkin46774762014-10-22 11:37:02 -07001307 } else {
1308 CHECK(false);
1309 ret = true;
1310 }
1311
1312 if (kIsDebugBuild) {
1313 LOG(INFO) << "Exiting with return ... " << ret;
Alex Light53cb16b2014-06-12 11:26:29 -07001314 }
1315 cleanup(ret);
Alex Light53cb16b2014-06-12 11:26:29 -07001316 return (ret) ? EXIT_SUCCESS : EXIT_FAILURE;
1317}
1318
1319} // namespace art
1320
1321int main(int argc, char **argv) {
1322 return art::patchoat(argc, argv);
1323}