blob: 3c6a23d8a1bfb88e81e53d348c4c47ea8f85db50 [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
Alex Lightcf4bf382014-07-24 11:29:14 -070051static bool LocationToFilename(const std::string& location, InstructionSet isa,
52 std::string* filename) {
53 bool has_system = false;
54 bool has_cache = false;
55 // image_location = /system/framework/boot.art
Igor Murashkin46774762014-10-22 11:37:02 -070056 // system_image_filename = /system/framework/<image_isa>/boot.art
Alex Lightcf4bf382014-07-24 11:29:14 -070057 std::string system_filename(GetSystemImageFilename(location.c_str(), isa));
58 if (OS::FileExists(system_filename.c_str())) {
59 has_system = true;
60 }
61
62 bool have_android_data = false;
63 bool dalvik_cache_exists = false;
Andreas Gampe3c13a792014-09-18 20:56:04 -070064 bool is_global_cache = false;
Alex Lightcf4bf382014-07-24 11:29:14 -070065 std::string dalvik_cache;
66 GetDalvikCache(GetInstructionSetString(isa), false, &dalvik_cache,
Andreas Gampe3c13a792014-09-18 20:56:04 -070067 &have_android_data, &dalvik_cache_exists, &is_global_cache);
Alex Lightcf4bf382014-07-24 11:29:14 -070068
69 std::string cache_filename;
70 if (have_android_data && dalvik_cache_exists) {
71 // Always set output location even if it does not exist,
72 // so that the caller knows where to create the image.
73 //
74 // image_location = /system/framework/boot.art
75 // *image_filename = /data/dalvik-cache/<image_isa>/boot.art
76 std::string error_msg;
77 if (GetDalvikCacheFilename(location.c_str(), dalvik_cache.c_str(),
78 &cache_filename, &error_msg)) {
79 has_cache = true;
80 }
81 }
82 if (has_system) {
83 *filename = system_filename;
84 return true;
85 } else if (has_cache) {
86 *filename = cache_filename;
87 return true;
88 } else {
89 return false;
90 }
91}
92
Alex Light53cb16b2014-06-12 11:26:29 -070093bool PatchOat::Patch(const std::string& image_location, off_t delta,
94 File* output_image, InstructionSet isa,
Alex Lighteefbe392014-07-08 09:53:18 -070095 TimingLogger* timings) {
Alex Light53cb16b2014-06-12 11:26:29 -070096 CHECK(Runtime::Current() == nullptr);
97 CHECK(output_image != nullptr);
98 CHECK_GE(output_image->Fd(), 0);
99 CHECK(!image_location.empty()) << "image file must have a filename.";
100 CHECK_NE(isa, kNone);
101
Alex Lighteefbe392014-07-08 09:53:18 -0700102 TimingLogger::ScopedTiming t("Runtime Setup", timings);
Alex Light53cb16b2014-06-12 11:26:29 -0700103 const char *isa_name = GetInstructionSetString(isa);
Alex Lightcf4bf382014-07-24 11:29:14 -0700104 std::string image_filename;
105 if (!LocationToFilename(image_location, isa, &image_filename)) {
106 LOG(ERROR) << "Unable to find image at location " << image_location;
107 return false;
108 }
Alex Light53cb16b2014-06-12 11:26:29 -0700109 std::unique_ptr<File> input_image(OS::OpenFileForReading(image_filename.c_str()));
110 if (input_image.get() == nullptr) {
Alex Lightcf4bf382014-07-24 11:29:14 -0700111 LOG(ERROR) << "unable to open input image file at " << image_filename
112 << " for location " << image_location;
Alex Light53cb16b2014-06-12 11:26:29 -0700113 return false;
114 }
Igor Murashkin46774762014-10-22 11:37:02 -0700115
Alex Light53cb16b2014-06-12 11:26:29 -0700116 int64_t image_len = input_image->GetLength();
117 if (image_len < 0) {
118 LOG(ERROR) << "Error while getting image length";
119 return false;
120 }
121 ImageHeader image_header;
122 if (sizeof(image_header) != input_image->Read(reinterpret_cast<char*>(&image_header),
123 sizeof(image_header), 0)) {
124 LOG(ERROR) << "Unable to read image header from image file " << input_image->GetPath();
125 return false;
126 }
127
Igor Murashkin46774762014-10-22 11:37:02 -0700128 /*bool is_image_pic = */IsImagePic(image_header, input_image->GetPath());
129 // Nothing special to do right now since the image always needs to get patched.
130 // Perhaps in some far-off future we may have images with relative addresses that are true-PIC.
131
Alex Light53cb16b2014-06-12 11:26:29 -0700132 // Set up the runtime
Ian Rogerse63db272014-07-15 15:36:11 -0700133 RuntimeOptions options;
Alex Light53cb16b2014-06-12 11:26:29 -0700134 NoopCompilerCallbacks callbacks;
135 options.push_back(std::make_pair("compilercallbacks", &callbacks));
136 std::string img = "-Ximage:" + image_location;
137 options.push_back(std::make_pair(img.c_str(), nullptr));
138 options.push_back(std::make_pair("imageinstructionset", reinterpret_cast<const void*>(isa_name)));
139 if (!Runtime::Create(options, false)) {
140 LOG(ERROR) << "Unable to initialize runtime";
141 return false;
142 }
143 // Runtime::Create acquired the mutator_lock_ that is normally given away when we Runtime::Start,
144 // give it away now and then switch to a more manageable ScopedObjectAccess.
145 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
146 ScopedObjectAccess soa(Thread::Current());
147
148 t.NewTiming("Image and oat Patching setup");
149 // Create the map where we will write the image patches to.
Alex Lighteefbe392014-07-08 09:53:18 -0700150 std::string error_msg;
Alex Light53cb16b2014-06-12 11:26:29 -0700151 std::unique_ptr<MemMap> image(MemMap::MapFile(image_len, PROT_READ | PROT_WRITE, MAP_PRIVATE,
152 input_image->Fd(), 0,
153 input_image->GetPath().c_str(),
154 &error_msg));
155 if (image.get() == nullptr) {
156 LOG(ERROR) << "unable to map image file " << input_image->GetPath() << " : " << error_msg;
157 return false;
158 }
159 gc::space::ImageSpace* ispc = Runtime::Current()->GetHeap()->GetImageSpace();
160
Mathieu Chartier2d721012014-11-10 11:08:06 -0800161 PatchOat p(isa, image.release(), ispc->GetLiveBitmap(), ispc->GetMemMap(),
Alex Light53cb16b2014-06-12 11:26:29 -0700162 delta, timings);
163 t.NewTiming("Patching files");
164 if (!p.PatchImage()) {
Alex Lighta59dd802014-07-02 16:28:08 -0700165 LOG(ERROR) << "Failed to patch image file " << input_image->GetPath();
Alex Light53cb16b2014-06-12 11:26:29 -0700166 return false;
167 }
168
169 t.NewTiming("Writing files");
170 if (!p.WriteImage(output_image)) {
171 return false;
172 }
173 return true;
174}
175
Igor Murashkin46774762014-10-22 11:37:02 -0700176bool PatchOat::Patch(File* input_oat, const std::string& image_location, off_t delta,
Alex Light53cb16b2014-06-12 11:26:29 -0700177 File* output_oat, File* output_image, InstructionSet isa,
Igor Murashkin46774762014-10-22 11:37:02 -0700178 TimingLogger* timings,
179 bool output_oat_opened_from_fd,
180 bool new_oat_out) {
Alex Light53cb16b2014-06-12 11:26:29 -0700181 CHECK(Runtime::Current() == nullptr);
182 CHECK(output_image != nullptr);
183 CHECK_GE(output_image->Fd(), 0);
184 CHECK(input_oat != nullptr);
185 CHECK(output_oat != nullptr);
186 CHECK_GE(input_oat->Fd(), 0);
187 CHECK_GE(output_oat->Fd(), 0);
188 CHECK(!image_location.empty()) << "image file must have a filename.";
189
Alex Lighteefbe392014-07-08 09:53:18 -0700190 TimingLogger::ScopedTiming t("Runtime Setup", timings);
Alex Light53cb16b2014-06-12 11:26:29 -0700191
192 if (isa == kNone) {
193 Elf32_Ehdr elf_hdr;
194 if (sizeof(elf_hdr) != input_oat->Read(reinterpret_cast<char*>(&elf_hdr), sizeof(elf_hdr), 0)) {
195 LOG(ERROR) << "unable to read elf header";
196 return false;
197 }
Andreas Gampe6f611412015-01-21 22:25:24 -0800198 isa = GetInstructionSetFromELF(elf_hdr.e_machine, elf_hdr.e_flags);
Alex Light53cb16b2014-06-12 11:26:29 -0700199 }
200 const char* isa_name = GetInstructionSetString(isa);
Alex Lightcf4bf382014-07-24 11:29:14 -0700201 std::string image_filename;
202 if (!LocationToFilename(image_location, isa, &image_filename)) {
203 LOG(ERROR) << "Unable to find image at location " << image_location;
204 return false;
205 }
Alex Light53cb16b2014-06-12 11:26:29 -0700206 std::unique_ptr<File> input_image(OS::OpenFileForReading(image_filename.c_str()));
207 if (input_image.get() == nullptr) {
Alex Lightcf4bf382014-07-24 11:29:14 -0700208 LOG(ERROR) << "unable to open input image file at " << image_filename
209 << " for location " << image_location;
Alex Light53cb16b2014-06-12 11:26:29 -0700210 return false;
211 }
212 int64_t image_len = input_image->GetLength();
213 if (image_len < 0) {
214 LOG(ERROR) << "Error while getting image length";
215 return false;
216 }
217 ImageHeader image_header;
218 if (sizeof(image_header) != input_image->Read(reinterpret_cast<char*>(&image_header),
219 sizeof(image_header), 0)) {
220 LOG(ERROR) << "Unable to read image header from image file " << input_image->GetPath();
221 }
222
Igor Murashkin46774762014-10-22 11:37:02 -0700223 /*bool is_image_pic = */IsImagePic(image_header, input_image->GetPath());
224 // Nothing special to do right now since the image always needs to get patched.
225 // Perhaps in some far-off future we may have images with relative addresses that are true-PIC.
226
Alex Light53cb16b2014-06-12 11:26:29 -0700227 // Set up the runtime
Ian Rogerse63db272014-07-15 15:36:11 -0700228 RuntimeOptions options;
Alex Light53cb16b2014-06-12 11:26:29 -0700229 NoopCompilerCallbacks callbacks;
230 options.push_back(std::make_pair("compilercallbacks", &callbacks));
231 std::string img = "-Ximage:" + image_location;
232 options.push_back(std::make_pair(img.c_str(), nullptr));
233 options.push_back(std::make_pair("imageinstructionset", reinterpret_cast<const void*>(isa_name)));
234 if (!Runtime::Create(options, false)) {
235 LOG(ERROR) << "Unable to initialize runtime";
236 return false;
237 }
238 // Runtime::Create acquired the mutator_lock_ that is normally given away when we Runtime::Start,
239 // give it away now and then switch to a more manageable ScopedObjectAccess.
240 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
241 ScopedObjectAccess soa(Thread::Current());
242
243 t.NewTiming("Image and oat Patching setup");
244 // Create the map where we will write the image patches to.
Alex Lighteefbe392014-07-08 09:53:18 -0700245 std::string error_msg;
Alex Light53cb16b2014-06-12 11:26:29 -0700246 std::unique_ptr<MemMap> image(MemMap::MapFile(image_len, PROT_READ | PROT_WRITE, MAP_PRIVATE,
247 input_image->Fd(), 0,
248 input_image->GetPath().c_str(),
249 &error_msg));
250 if (image.get() == nullptr) {
251 LOG(ERROR) << "unable to map image file " << input_image->GetPath() << " : " << error_msg;
252 return false;
253 }
254 gc::space::ImageSpace* ispc = Runtime::Current()->GetHeap()->GetImageSpace();
255
Igor Murashkin46774762014-10-22 11:37:02 -0700256 std::unique_ptr<ElfFile> elf(ElfFile::Open(input_oat,
Alex Light53cb16b2014-06-12 11:26:29 -0700257 PROT_READ | PROT_WRITE, MAP_PRIVATE, &error_msg));
258 if (elf.get() == nullptr) {
259 LOG(ERROR) << "unable to open oat file " << input_oat->GetPath() << " : " << error_msg;
260 return false;
261 }
262
Igor Murashkin46774762014-10-22 11:37:02 -0700263 bool skip_patching_oat = false;
264 MaybePic is_oat_pic = IsOatPic(elf.get());
265 if (is_oat_pic >= ERROR_FIRST) {
266 // Error logged by IsOatPic
267 return false;
268 } else if (is_oat_pic == PIC) {
269 // Do not need to do ELF-file patching. Create a symlink and skip the ELF patching.
270 if (!ReplaceOatFileWithSymlink(input_oat->GetPath(),
271 output_oat->GetPath(),
272 output_oat_opened_from_fd,
273 new_oat_out)) {
274 // Errors already logged by above call.
275 return false;
276 }
277 // Don't patch the OAT, since we just symlinked it. Image still needs patching.
278 skip_patching_oat = true;
279 } else {
280 CHECK(is_oat_pic == NOT_PIC);
281 }
282
Mathieu Chartier2d721012014-11-10 11:08:06 -0800283 PatchOat p(isa, elf.release(), image.release(), ispc->GetLiveBitmap(), ispc->GetMemMap(),
Alex Light53cb16b2014-06-12 11:26:29 -0700284 delta, timings);
285 t.NewTiming("Patching files");
Igor Murashkin46774762014-10-22 11:37:02 -0700286 if (!skip_patching_oat && !p.PatchElf()) {
Alex Lighta59dd802014-07-02 16:28:08 -0700287 LOG(ERROR) << "Failed to patch oat file " << input_oat->GetPath();
Alex Light53cb16b2014-06-12 11:26:29 -0700288 return false;
289 }
290 if (!p.PatchImage()) {
Alex Lighta59dd802014-07-02 16:28:08 -0700291 LOG(ERROR) << "Failed to patch image file " << input_image->GetPath();
Alex Light53cb16b2014-06-12 11:26:29 -0700292 return false;
293 }
294
295 t.NewTiming("Writing files");
Igor Murashkin46774762014-10-22 11:37:02 -0700296 if (!skip_patching_oat && !p.WriteElf(output_oat)) {
297 LOG(ERROR) << "Failed to write oat file " << input_oat->GetPath();
Alex Light53cb16b2014-06-12 11:26:29 -0700298 return false;
299 }
300 if (!p.WriteImage(output_image)) {
Igor Murashkin46774762014-10-22 11:37:02 -0700301 LOG(ERROR) << "Failed to write image file " << input_image->GetPath();
Alex Light53cb16b2014-06-12 11:26:29 -0700302 return false;
303 }
304 return true;
305}
306
307bool PatchOat::WriteElf(File* out) {
Alex Lighteefbe392014-07-08 09:53:18 -0700308 TimingLogger::ScopedTiming t("Writing Elf File", timings_);
Alex Lighta59dd802014-07-02 16:28:08 -0700309
Alex Light53cb16b2014-06-12 11:26:29 -0700310 CHECK(oat_file_.get() != nullptr);
311 CHECK(out != nullptr);
312 size_t expect = oat_file_->Size();
313 if (out->WriteFully(reinterpret_cast<char*>(oat_file_->Begin()), expect) &&
314 out->SetLength(expect) == 0) {
315 return true;
316 } else {
317 LOG(ERROR) << "Writing to oat file " << out->GetPath() << " failed.";
318 return false;
319 }
320}
321
322bool PatchOat::WriteImage(File* out) {
Alex Lighteefbe392014-07-08 09:53:18 -0700323 TimingLogger::ScopedTiming t("Writing image File", timings_);
Alex Lighta59dd802014-07-02 16:28:08 -0700324 std::string error_msg;
325
Alex Lightcf4bf382014-07-24 11:29:14 -0700326 ScopedFlock img_flock;
327 img_flock.Init(out, &error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -0700328
Alex Light53cb16b2014-06-12 11:26:29 -0700329 CHECK(image_ != nullptr);
330 CHECK(out != nullptr);
331 size_t expect = image_->Size();
332 if (out->WriteFully(reinterpret_cast<char*>(image_->Begin()), expect) &&
333 out->SetLength(expect) == 0) {
334 return true;
335 } else {
336 LOG(ERROR) << "Writing to image file " << out->GetPath() << " failed.";
337 return false;
338 }
339}
340
Igor Murashkin46774762014-10-22 11:37:02 -0700341bool PatchOat::IsImagePic(const ImageHeader& image_header, const std::string& image_path) {
342 if (!image_header.CompilePic()) {
343 if (kIsDebugBuild) {
344 LOG(INFO) << "image at location " << image_path << " was *not* compiled pic";
345 }
346 return false;
347 }
348
349 if (kIsDebugBuild) {
350 LOG(INFO) << "image at location " << image_path << " was compiled PIC";
351 }
352
353 return true;
354}
355
356PatchOat::MaybePic PatchOat::IsOatPic(const ElfFile* oat_in) {
357 if (oat_in == nullptr) {
358 LOG(ERROR) << "No ELF input oat fie available";
359 return ERROR_OAT_FILE;
360 }
361
362 const std::string& file_path = oat_in->GetFile().GetPath();
363
364 const OatHeader* oat_header = GetOatHeader(oat_in);
365 if (oat_header == nullptr) {
366 LOG(ERROR) << "Failed to find oat header in oat file " << file_path;
367 return ERROR_OAT_FILE;
368 }
369
370 if (!oat_header->IsValid()) {
371 LOG(ERROR) << "Elf file " << file_path << " has an invalid oat header";
372 return ERROR_OAT_FILE;
373 }
374
375 bool is_pic = oat_header->IsPic();
376 if (kIsDebugBuild) {
377 LOG(INFO) << "Oat file at " << file_path << " is " << (is_pic ? "PIC" : "not pic");
378 }
379
380 return is_pic ? PIC : NOT_PIC;
381}
382
383bool PatchOat::ReplaceOatFileWithSymlink(const std::string& input_oat_filename,
384 const std::string& output_oat_filename,
385 bool output_oat_opened_from_fd,
386 bool new_oat_out) {
387 // Need a file when we are PIC, since we symlink over it. Refusing to symlink into FD.
388 if (output_oat_opened_from_fd) {
389 // TODO: installd uses --output-oat-fd. Should we change class linking logic for PIC?
390 LOG(ERROR) << "No output oat filename specified, needs filename for when we are PIC";
391 return false;
392 }
393
394 // Image was PIC. Create symlink where the oat is supposed to go.
395 if (!new_oat_out) {
396 LOG(ERROR) << "Oat file " << output_oat_filename << " already exists, refusing to overwrite";
397 return false;
398 }
399
400 // Delete the original file, since we won't need it.
401 TEMP_FAILURE_RETRY(unlink(output_oat_filename.c_str()));
402
403 // Create a symlink from the old oat to the new oat
404 if (symlink(input_oat_filename.c_str(), output_oat_filename.c_str()) < 0) {
405 int err = errno;
406 LOG(ERROR) << "Failed to create symlink at " << output_oat_filename
407 << " error(" << err << "): " << strerror(err);
408 return false;
409 }
410
411 if (kIsDebugBuild) {
412 LOG(INFO) << "Created symlink " << output_oat_filename << " -> " << input_oat_filename;
413 }
414
415 return true;
416}
417
Alex Light53cb16b2014-06-12 11:26:29 -0700418bool PatchOat::PatchImage() {
419 ImageHeader* image_header = reinterpret_cast<ImageHeader*>(image_->Begin());
420 CHECK_GT(image_->Size(), sizeof(ImageHeader));
421 // These are the roots from the original file.
422 mirror::Object* img_roots = image_header->GetImageRoots();
423 image_header->RelocateImage(delta_);
424
425 VisitObject(img_roots);
426 if (!image_header->IsValid()) {
427 LOG(ERROR) << "reloction renders image header invalid";
428 return false;
429 }
430
431 {
Alex Lighteefbe392014-07-08 09:53:18 -0700432 TimingLogger::ScopedTiming t("Walk Bitmap", timings_);
Alex Light53cb16b2014-06-12 11:26:29 -0700433 // Walk the bitmap.
434 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
435 bitmap_->Walk(PatchOat::BitmapCallback, this);
436 }
437 return true;
438}
439
440bool PatchOat::InHeap(mirror::Object* o) {
441 uintptr_t begin = reinterpret_cast<uintptr_t>(heap_->Begin());
442 uintptr_t end = reinterpret_cast<uintptr_t>(heap_->End());
443 uintptr_t obj = reinterpret_cast<uintptr_t>(o);
444 return o == nullptr || (begin <= obj && obj < end);
445}
446
447void PatchOat::PatchVisitor::operator() (mirror::Object* obj, MemberOffset off,
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700448 bool is_static_unused ATTRIBUTE_UNUSED) const {
Alex Light53cb16b2014-06-12 11:26:29 -0700449 mirror::Object* referent = obj->GetFieldObject<mirror::Object, kVerifyNone>(off);
450 DCHECK(patcher_->InHeap(referent)) << "Referent is not in the heap.";
451 mirror::Object* moved_object = patcher_->RelocatedAddressOf(referent);
452 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(off, moved_object);
453}
454
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700455void PatchOat::PatchVisitor::operator() (mirror::Class* cls ATTRIBUTE_UNUSED,
456 mirror::Reference* ref) const {
Alex Light53cb16b2014-06-12 11:26:29 -0700457 MemberOffset off = mirror::Reference::ReferentOffset();
458 mirror::Object* referent = ref->GetReferent();
459 DCHECK(patcher_->InHeap(referent)) << "Referent is not in the heap.";
460 mirror::Object* moved_object = patcher_->RelocatedAddressOf(referent);
461 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(off, moved_object);
462}
463
464mirror::Object* PatchOat::RelocatedCopyOf(mirror::Object* obj) {
465 if (obj == nullptr) {
466 return nullptr;
467 }
468 DCHECK_GT(reinterpret_cast<uintptr_t>(obj), reinterpret_cast<uintptr_t>(heap_->Begin()));
469 DCHECK_LT(reinterpret_cast<uintptr_t>(obj), reinterpret_cast<uintptr_t>(heap_->End()));
470 uintptr_t heap_off =
471 reinterpret_cast<uintptr_t>(obj) - reinterpret_cast<uintptr_t>(heap_->Begin());
472 DCHECK_LT(heap_off, image_->Size());
473 return reinterpret_cast<mirror::Object*>(image_->Begin() + heap_off);
474}
475
476mirror::Object* PatchOat::RelocatedAddressOf(mirror::Object* obj) {
477 if (obj == nullptr) {
478 return nullptr;
479 } else {
Ian Rogers13735952014-10-08 12:43:28 -0700480 return reinterpret_cast<mirror::Object*>(reinterpret_cast<uint8_t*>(obj) + delta_);
Alex Light53cb16b2014-06-12 11:26:29 -0700481 }
482}
483
Igor Murashkin46774762014-10-22 11:37:02 -0700484const OatHeader* PatchOat::GetOatHeader(const ElfFile* elf_file) {
485 if (elf_file->Is64Bit()) {
486 return GetOatHeader<ElfFileImpl64>(elf_file->GetImpl64());
487 } else {
488 return GetOatHeader<ElfFileImpl32>(elf_file->GetImpl32());
489 }
490}
491
492template <typename ElfFileImpl>
493const OatHeader* PatchOat::GetOatHeader(const ElfFileImpl* elf_file) {
494 auto rodata_sec = elf_file->FindSectionByName(".rodata");
495 if (rodata_sec == nullptr) {
496 return nullptr;
497 }
498
499 OatHeader* oat_header = reinterpret_cast<OatHeader*>(elf_file->Begin() + rodata_sec->sh_offset);
500 return oat_header;
501}
502
Alex Light53cb16b2014-06-12 11:26:29 -0700503// Called by BitmapCallback
504void PatchOat::VisitObject(mirror::Object* object) {
505 mirror::Object* copy = RelocatedCopyOf(object);
506 CHECK(copy != nullptr);
507 if (kUseBakerOrBrooksReadBarrier) {
508 object->AssertReadBarrierPointer();
509 if (kUseBrooksReadBarrier) {
510 mirror::Object* moved_to = RelocatedAddressOf(object);
511 copy->SetReadBarrierPointer(moved_to);
512 DCHECK_EQ(copy->GetReadBarrierPointer(), moved_to);
513 }
514 }
515 PatchOat::PatchVisitor visitor(this, copy);
516 object->VisitReferences<true, kVerifyNone>(visitor, visitor);
517 if (object->IsArtMethod<kVerifyNone>()) {
Mathieu Chartier2d721012014-11-10 11:08:06 -0800518 FixupMethod(down_cast<mirror::ArtMethod*>(object), down_cast<mirror::ArtMethod*>(copy));
Alex Light53cb16b2014-06-12 11:26:29 -0700519 }
520}
521
522void PatchOat::FixupMethod(mirror::ArtMethod* object, mirror::ArtMethod* copy) {
Mathieu Chartier2d721012014-11-10 11:08:06 -0800523 const size_t pointer_size = InstructionSetPointerSize(isa_);
Alex Light53cb16b2014-06-12 11:26:29 -0700524 // Just update the entry points if it looks like we should.
Alex Lighteefbe392014-07-08 09:53:18 -0700525 // TODO: sanity check all the pointers' values
Alex Light53cb16b2014-06-12 11:26:29 -0700526 uintptr_t quick= reinterpret_cast<uintptr_t>(
Mathieu Chartier2d721012014-11-10 11:08:06 -0800527 object->GetEntryPointFromQuickCompiledCodePtrSize<kVerifyNone>(pointer_size));
Alex Light53cb16b2014-06-12 11:26:29 -0700528 if (quick != 0) {
Mathieu Chartier2d721012014-11-10 11:08:06 -0800529 copy->SetEntryPointFromQuickCompiledCodePtrSize(reinterpret_cast<void*>(quick + delta_),
530 pointer_size);
Alex Light53cb16b2014-06-12 11:26:29 -0700531 }
532 uintptr_t interpreter = reinterpret_cast<uintptr_t>(
Mathieu Chartier2d721012014-11-10 11:08:06 -0800533 object->GetEntryPointFromInterpreterPtrSize<kVerifyNone>(pointer_size));
Alex Light53cb16b2014-06-12 11:26:29 -0700534 if (interpreter != 0) {
Mathieu Chartier2d721012014-11-10 11:08:06 -0800535 copy->SetEntryPointFromInterpreterPtrSize(
536 reinterpret_cast<mirror::EntryPointFromInterpreter*>(interpreter + delta_), pointer_size);
Alex Light53cb16b2014-06-12 11:26:29 -0700537 }
538
Mathieu Chartier2d721012014-11-10 11:08:06 -0800539 uintptr_t native_method = reinterpret_cast<uintptr_t>(
540 object->GetEntryPointFromJniPtrSize(pointer_size));
Alex Light53cb16b2014-06-12 11:26:29 -0700541 if (native_method != 0) {
Mathieu Chartier2d721012014-11-10 11:08:06 -0800542 copy->SetEntryPointFromJniPtrSize(reinterpret_cast<void*>(native_method + delta_),
543 pointer_size);
Alex Light53cb16b2014-06-12 11:26:29 -0700544 }
Alex Light53cb16b2014-06-12 11:26:29 -0700545}
546
Igor Murashkin46774762014-10-22 11:37:02 -0700547bool PatchOat::Patch(File* input_oat, off_t delta, File* output_oat, TimingLogger* timings,
548 bool output_oat_opened_from_fd, bool new_oat_out) {
Alex Light53cb16b2014-06-12 11:26:29 -0700549 CHECK(input_oat != nullptr);
550 CHECK(output_oat != nullptr);
551 CHECK_GE(input_oat->Fd(), 0);
552 CHECK_GE(output_oat->Fd(), 0);
Alex Lighteefbe392014-07-08 09:53:18 -0700553 TimingLogger::ScopedTiming t("Setup Oat File Patching", timings);
Alex Light53cb16b2014-06-12 11:26:29 -0700554
555 std::string error_msg;
Igor Murashkin46774762014-10-22 11:37:02 -0700556 std::unique_ptr<ElfFile> elf(ElfFile::Open(input_oat,
Alex Light53cb16b2014-06-12 11:26:29 -0700557 PROT_READ | PROT_WRITE, MAP_PRIVATE, &error_msg));
558 if (elf.get() == nullptr) {
559 LOG(ERROR) << "unable to open oat file " << input_oat->GetPath() << " : " << error_msg;
560 return false;
561 }
562
Igor Murashkin46774762014-10-22 11:37:02 -0700563 MaybePic is_oat_pic = IsOatPic(elf.get());
564 if (is_oat_pic >= ERROR_FIRST) {
565 // Error logged by IsOatPic
566 return false;
567 } else if (is_oat_pic == PIC) {
568 // Do not need to do ELF-file patching. Create a symlink and skip the rest.
569 // Any errors will be logged by the function call.
570 return ReplaceOatFileWithSymlink(input_oat->GetPath(),
571 output_oat->GetPath(),
572 output_oat_opened_from_fd,
573 new_oat_out);
574 } else {
575 CHECK(is_oat_pic == NOT_PIC);
576 }
577
Alex Light53cb16b2014-06-12 11:26:29 -0700578 PatchOat p(elf.release(), delta, timings);
579 t.NewTiming("Patch Oat file");
580 if (!p.PatchElf()) {
581 return false;
582 }
583
584 t.NewTiming("Writing oat file");
585 if (!p.WriteElf(output_oat)) {
586 return false;
587 }
588 return true;
589}
590
Tong Shen62d1ca32014-09-03 17:24:56 -0700591template <typename ElfFileImpl, typename ptr_t>
592bool PatchOat::CheckOatFile(ElfFileImpl* oat_file) {
593 auto patches_sec = oat_file->FindSectionByName(".oat_patches");
594 if (patches_sec->sh_type != SHT_OAT_PATCH) {
Alex Light53cb16b2014-06-12 11:26:29 -0700595 return false;
596 }
Tong Shen62d1ca32014-09-03 17:24:56 -0700597 ptr_t* patches = reinterpret_cast<ptr_t*>(oat_file->Begin() + patches_sec->sh_offset);
598 ptr_t* patches_end = patches + (patches_sec->sh_size / sizeof(ptr_t));
599 auto oat_data_sec = oat_file->FindSectionByName(".rodata");
600 auto oat_text_sec = oat_file->FindSectionByName(".text");
Alex Light53cb16b2014-06-12 11:26:29 -0700601 if (oat_data_sec == nullptr) {
602 return false;
603 }
604 if (oat_text_sec == nullptr) {
605 return false;
606 }
607 if (oat_text_sec->sh_offset <= oat_data_sec->sh_offset) {
608 return false;
609 }
610
611 for (; patches < patches_end; patches++) {
612 if (oat_text_sec->sh_size <= *patches) {
613 return false;
614 }
615 }
616
617 return true;
618}
619
Tong Shen62d1ca32014-09-03 17:24:56 -0700620template <typename ElfFileImpl>
621bool PatchOat::PatchOatHeader(ElfFileImpl* oat_file) {
622 auto rodata_sec = oat_file->FindSectionByName(".rodata");
Alex Lighta59dd802014-07-02 16:28:08 -0700623 if (rodata_sec == nullptr) {
624 return false;
625 }
Tong Shen62d1ca32014-09-03 17:24:56 -0700626 OatHeader* oat_header = reinterpret_cast<OatHeader*>(oat_file->Begin() + rodata_sec->sh_offset);
Alex Lighta59dd802014-07-02 16:28:08 -0700627 if (!oat_header->IsValid()) {
Tong Shen62d1ca32014-09-03 17:24:56 -0700628 LOG(ERROR) << "Elf file " << oat_file->GetFile().GetPath() << " has an invalid oat header";
Alex Lighta59dd802014-07-02 16:28:08 -0700629 return false;
630 }
631 oat_header->RelocateOat(delta_);
632 return true;
633}
634
Alex Light53cb16b2014-06-12 11:26:29 -0700635bool PatchOat::PatchElf() {
Ian Rogersd4c4d952014-10-16 20:31:53 -0700636 if (oat_file_->Is64Bit())
Tong Shen62d1ca32014-09-03 17:24:56 -0700637 return PatchElf<ElfFileImpl64>(oat_file_->GetImpl64());
638 else
639 return PatchElf<ElfFileImpl32>(oat_file_->GetImpl32());
640}
641
642template <typename ElfFileImpl>
643bool PatchOat::PatchElf(ElfFileImpl* oat_file) {
Alex Lighta59dd802014-07-02 16:28:08 -0700644 TimingLogger::ScopedTiming t("Fixup Elf Text Section", timings_);
Tong Shen62d1ca32014-09-03 17:24:56 -0700645 if (!PatchTextSection<ElfFileImpl>(oat_file)) {
Alex Lighta59dd802014-07-02 16:28:08 -0700646 return false;
647 }
648
Tong Shen62d1ca32014-09-03 17:24:56 -0700649 if (!PatchOatHeader<ElfFileImpl>(oat_file)) {
Alex Lighta59dd802014-07-02 16:28:08 -0700650 return false;
651 }
652
653 bool need_fixup = false;
Ian Rogersd4c4d952014-10-16 20:31:53 -0700654 for (unsigned int i = 0; i < oat_file->GetProgramHeaderNum(); ++i) {
Tong Shen62d1ca32014-09-03 17:24:56 -0700655 auto hdr = oat_file->GetProgramHeader(i);
Ian Rogersd4c4d952014-10-16 20:31:53 -0700656 if ((hdr->p_vaddr != 0 && hdr->p_vaddr != hdr->p_offset) ||
657 (hdr->p_paddr != 0 && hdr->p_paddr != hdr->p_offset)) {
Alex Lighta59dd802014-07-02 16:28:08 -0700658 need_fixup = true;
Ian Rogersd4c4d952014-10-16 20:31:53 -0700659 break;
Alex Light53cb16b2014-06-12 11:26:29 -0700660 }
661 }
Alex Lighta59dd802014-07-02 16:28:08 -0700662 if (!need_fixup) {
663 // This was never passed through ElfFixup so all headers/symbols just have their offset as
664 // their addr. Therefore we do not need to update these parts.
665 return true;
666 }
Tong Shen62d1ca32014-09-03 17:24:56 -0700667
668 t.NewTiming("Fixup Elf Headers");
669 // Fixup Phdr's
670 oat_file->FixupProgramHeaders(delta_);
671
Alex Lighta59dd802014-07-02 16:28:08 -0700672 t.NewTiming("Fixup Section Headers");
Tong Shen62d1ca32014-09-03 17:24:56 -0700673 // Fixup Shdr's
674 oat_file->FixupSectionHeaders(delta_);
Alex Light53cb16b2014-06-12 11:26:29 -0700675
Alex Lighta59dd802014-07-02 16:28:08 -0700676 t.NewTiming("Fixup Dynamics");
Tong Shen62d1ca32014-09-03 17:24:56 -0700677 oat_file->FixupDynamic(delta_);
Alex Light53cb16b2014-06-12 11:26:29 -0700678
679 t.NewTiming("Fixup Elf Symbols");
680 // Fixup dynsym
Tong Shen62d1ca32014-09-03 17:24:56 -0700681 if (!oat_file->FixupSymbols(delta_, true)) {
Alex Light53cb16b2014-06-12 11:26:29 -0700682 return false;
683 }
Alex Light53cb16b2014-06-12 11:26:29 -0700684 // Fixup symtab
Tong Shen62d1ca32014-09-03 17:24:56 -0700685 if (!oat_file->FixupSymbols(delta_, false)) {
686 return false;
Alex Light53cb16b2014-06-12 11:26:29 -0700687 }
688
Yevgeny Roubane3ea8382014-08-08 16:29:38 +0700689 t.NewTiming("Fixup Debug Sections");
Tong Shen62d1ca32014-09-03 17:24:56 -0700690 if (!oat_file->FixupDebugSections(delta_)) {
Yevgeny Roubane3ea8382014-08-08 16:29:38 +0700691 return false;
692 }
693
Alex Light53cb16b2014-06-12 11:26:29 -0700694 return true;
695}
696
Tong Shen62d1ca32014-09-03 17:24:56 -0700697template <typename ElfFileImpl>
698bool PatchOat::PatchTextSection(ElfFileImpl* oat_file) {
699 auto patches_sec = oat_file->FindSectionByName(".oat_patches");
Alex Light53cb16b2014-06-12 11:26:29 -0700700 if (patches_sec == nullptr) {
Alex Lighta59dd802014-07-02 16:28:08 -0700701 LOG(ERROR) << ".oat_patches section not found. Aborting patch";
Alex Light53cb16b2014-06-12 11:26:29 -0700702 return false;
703 }
Alex Light4b0d2d92014-08-06 13:37:23 -0700704 if (patches_sec->sh_type != SHT_OAT_PATCH) {
705 LOG(ERROR) << "Unexpected type of .oat_patches";
706 return false;
707 }
708
709 switch (patches_sec->sh_entsize) {
710 case sizeof(uint32_t):
Tong Shen62d1ca32014-09-03 17:24:56 -0700711 return PatchTextSection<ElfFileImpl, uint32_t>(oat_file);
Alex Light4b0d2d92014-08-06 13:37:23 -0700712 case sizeof(uint64_t):
Tong Shen62d1ca32014-09-03 17:24:56 -0700713 return PatchTextSection<ElfFileImpl, uint64_t>(oat_file);
Alex Light4b0d2d92014-08-06 13:37:23 -0700714 default:
715 LOG(ERROR) << ".oat_patches Entsize of " << patches_sec->sh_entsize << "bits "
716 << "is not valid";
717 return false;
718 }
719}
720
Tong Shen62d1ca32014-09-03 17:24:56 -0700721template <typename ElfFileImpl, typename patch_loc_t>
722bool PatchOat::PatchTextSection(ElfFileImpl* oat_file) {
723 bool oat_file_valid = CheckOatFile<ElfFileImpl, patch_loc_t>(oat_file);
724 CHECK(oat_file_valid) << "Oat file invalid";
725 auto patches_sec = oat_file->FindSectionByName(".oat_patches");
726 patch_loc_t* patches = reinterpret_cast<patch_loc_t*>(oat_file->Begin() + patches_sec->sh_offset);
727 patch_loc_t* patches_end = patches + (patches_sec->sh_size / sizeof(patch_loc_t));
728 auto oat_text_sec = oat_file->FindSectionByName(".text");
Alex Light53cb16b2014-06-12 11:26:29 -0700729 CHECK(oat_text_sec != nullptr);
Ian Rogers13735952014-10-08 12:43:28 -0700730 uint8_t* to_patch = oat_file->Begin() + oat_text_sec->sh_offset;
Alex Light53cb16b2014-06-12 11:26:29 -0700731 uintptr_t to_patch_end = reinterpret_cast<uintptr_t>(to_patch) + oat_text_sec->sh_size;
732
733 for (; patches < patches_end; patches++) {
734 CHECK_LT(*patches, oat_text_sec->sh_size) << "Bad Patch";
735 uint32_t* patch_loc = reinterpret_cast<uint32_t*>(to_patch + *patches);
736 CHECK_LT(reinterpret_cast<uintptr_t>(patch_loc), to_patch_end);
737 *patch_loc += delta_;
738 }
Alex Light53cb16b2014-06-12 11:26:29 -0700739 return true;
740}
741
742static int orig_argc;
743static char** orig_argv;
744
745static std::string CommandLine() {
746 std::vector<std::string> command;
747 for (int i = 0; i < orig_argc; ++i) {
748 command.push_back(orig_argv[i]);
749 }
750 return Join(command, ' ');
751}
752
753static void UsageErrorV(const char* fmt, va_list ap) {
754 std::string error;
755 StringAppendV(&error, fmt, ap);
756 LOG(ERROR) << error;
757}
758
759static void UsageError(const char* fmt, ...) {
760 va_list ap;
761 va_start(ap, fmt);
762 UsageErrorV(fmt, ap);
763 va_end(ap);
764}
765
Andreas Gampe794ad762015-02-23 08:12:24 -0800766NO_RETURN static void Usage(const char *fmt, ...) {
Alex Light53cb16b2014-06-12 11:26:29 -0700767 va_list ap;
768 va_start(ap, fmt);
769 UsageErrorV(fmt, ap);
770 va_end(ap);
771
772 UsageError("Command: %s", CommandLine().c_str());
773 UsageError("Usage: patchoat [options]...");
774 UsageError("");
775 UsageError(" --instruction-set=<isa>: Specifies the instruction set the patched code is");
776 UsageError(" compiled for. Required if you use --input-oat-location");
777 UsageError("");
778 UsageError(" --input-oat-file=<file.oat>: Specifies the exact filename of the oat file to be");
779 UsageError(" patched.");
780 UsageError("");
781 UsageError(" --input-oat-fd=<file-descriptor>: Specifies the file-descriptor of the oat file");
782 UsageError(" to be patched.");
783 UsageError("");
784 UsageError(" --input-oat-location=<file.oat>: Specifies the 'location' to read the patched");
785 UsageError(" oat file from. If used one must also supply the --instruction-set");
786 UsageError("");
787 UsageError(" --input-image-location=<file.art>: Specifies the 'location' of the image file to");
788 UsageError(" be patched. If --instruction-set is not given it will use the instruction set");
789 UsageError(" extracted from the --input-oat-file.");
790 UsageError("");
791 UsageError(" --output-oat-file=<file.oat>: Specifies the exact file to write the patched oat");
792 UsageError(" file to.");
793 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700794 UsageError(" --output-oat-fd=<file-descriptor>: Specifies the file-descriptor to write the");
795 UsageError(" the patched oat file to.");
796 UsageError("");
797 UsageError(" --output-image-file=<file.art>: Specifies the exact file to write the patched");
798 UsageError(" image file to.");
799 UsageError("");
800 UsageError(" --output-image-fd=<file-descriptor>: Specifies the file-descriptor to write the");
801 UsageError(" the patched image file to.");
802 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700803 UsageError(" --orig-base-offset=<original-base-offset>: Specify the base offset the input file");
804 UsageError(" was compiled with. This is needed if one is specifying a --base-offset");
805 UsageError("");
806 UsageError(" --base-offset=<new-base-offset>: Specify the base offset we will repatch the");
807 UsageError(" given files to use. This requires that --orig-base-offset is also given.");
808 UsageError("");
809 UsageError(" --base-offset-delta=<delta>: Specify the amount to change the old base-offset by.");
810 UsageError(" This value may be negative.");
811 UsageError("");
812 UsageError(" --patched-image-file=<file.art>: Use the same patch delta as was used to patch");
813 UsageError(" the given image file.");
814 UsageError("");
815 UsageError(" --patched-image-location=<file.art>: Use the same patch delta as was used to");
816 UsageError(" patch the given image location. If used one must also specify the");
Alex Lighta59dd802014-07-02 16:28:08 -0700817 UsageError(" --instruction-set flag. It will search for this image in the same way that");
818 UsageError(" is done when loading one.");
Alex Light53cb16b2014-06-12 11:26:29 -0700819 UsageError("");
Alex Lightcf4bf382014-07-24 11:29:14 -0700820 UsageError(" --lock-output: Obtain a flock on output oat file before starting.");
821 UsageError("");
822 UsageError(" --no-lock-output: Do not attempt to obtain a flock on output oat file.");
823 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700824 UsageError(" --dump-timings: dump out patch timing information");
825 UsageError("");
826 UsageError(" --no-dump-timings: do not dump out patch timing information");
827 UsageError("");
828
829 exit(EXIT_FAILURE);
830}
831
Alex Lighteefbe392014-07-08 09:53:18 -0700832static bool ReadBaseDelta(const char* name, off_t* delta, std::string* error_msg) {
Alex Light53cb16b2014-06-12 11:26:29 -0700833 CHECK(name != nullptr);
834 CHECK(delta != nullptr);
835 std::unique_ptr<File> file;
836 if (OS::FileExists(name)) {
837 file.reset(OS::OpenFileForReading(name));
838 if (file.get() == nullptr) {
Alex Lighteefbe392014-07-08 09:53:18 -0700839 *error_msg = "Failed to open file %s for reading";
Alex Light53cb16b2014-06-12 11:26:29 -0700840 return false;
841 }
842 } else {
Alex Lighteefbe392014-07-08 09:53:18 -0700843 *error_msg = "File %s does not exist";
Alex Light53cb16b2014-06-12 11:26:29 -0700844 return false;
845 }
846 CHECK(file.get() != nullptr);
847 ImageHeader hdr;
848 if (sizeof(hdr) != file->Read(reinterpret_cast<char*>(&hdr), sizeof(hdr), 0)) {
Alex Lighteefbe392014-07-08 09:53:18 -0700849 *error_msg = "Failed to read file %s";
Alex Light53cb16b2014-06-12 11:26:29 -0700850 return false;
851 }
852 if (!hdr.IsValid()) {
Alex Lighteefbe392014-07-08 09:53:18 -0700853 *error_msg = "%s does not contain a valid image header.";
Alex Light53cb16b2014-06-12 11:26:29 -0700854 return false;
855 }
856 *delta = hdr.GetPatchDelta();
857 return true;
858}
859
860static File* CreateOrOpen(const char* name, bool* created) {
861 if (OS::FileExists(name)) {
862 *created = false;
863 return OS::OpenFileReadWrite(name);
864 } else {
865 *created = true;
Alex Lightcf4bf382014-07-24 11:29:14 -0700866 std::unique_ptr<File> f(OS::CreateEmptyFile(name));
867 if (f.get() != nullptr) {
868 if (fchmod(f->Fd(), 0644) != 0) {
869 PLOG(ERROR) << "Unable to make " << name << " world readable";
Brian Carlstrom8c52a3f2014-09-30 16:18:01 -0700870 TEMP_FAILURE_RETRY(unlink(name));
Alex Lightcf4bf382014-07-24 11:29:14 -0700871 return nullptr;
872 }
873 }
874 return f.release();
Alex Light53cb16b2014-06-12 11:26:29 -0700875 }
876}
877
Andreas Gampe4303ba92014-11-06 01:00:46 -0800878// Either try to close the file (close=true), or erase it.
879static bool FinishFile(File* file, bool close) {
880 if (close) {
881 if (file->FlushCloseOrErase() != 0) {
882 PLOG(ERROR) << "Failed to flush and close file.";
883 return false;
884 }
885 return true;
886 } else {
887 file->Erase();
888 return false;
889 }
890}
891
Alex Lighteefbe392014-07-08 09:53:18 -0700892static int patchoat(int argc, char **argv) {
Alex Light53cb16b2014-06-12 11:26:29 -0700893 InitLogging(argv);
Mathieu Chartier6e88ef62014-10-14 15:01:24 -0700894 MemMap::Init();
Alex Light53cb16b2014-06-12 11:26:29 -0700895 const bool debug = kIsDebugBuild;
896 orig_argc = argc;
897 orig_argv = argv;
898 TimingLogger timings("patcher", false, false);
899
900 InitLogging(argv);
901
902 // Skip over the command name.
903 argv++;
904 argc--;
905
906 if (argc == 0) {
907 Usage("No arguments specified");
908 }
909
910 timings.StartTiming("Patchoat");
911
912 // cmd line args
913 bool isa_set = false;
914 InstructionSet isa = kNone;
915 std::string input_oat_filename;
916 std::string input_oat_location;
917 int input_oat_fd = -1;
918 bool have_input_oat = false;
919 std::string input_image_location;
920 std::string output_oat_filename;
Alex Light53cb16b2014-06-12 11:26:29 -0700921 int output_oat_fd = -1;
922 bool have_output_oat = false;
923 std::string output_image_filename;
Alex Light53cb16b2014-06-12 11:26:29 -0700924 int output_image_fd = -1;
925 bool have_output_image = false;
926 uintptr_t base_offset = 0;
927 bool base_offset_set = false;
928 uintptr_t orig_base_offset = 0;
929 bool orig_base_offset_set = false;
930 off_t base_delta = 0;
931 bool base_delta_set = false;
932 std::string patched_image_filename;
933 std::string patched_image_location;
934 bool dump_timings = kIsDebugBuild;
Alex Lightcf4bf382014-07-24 11:29:14 -0700935 bool lock_output = true;
Alex Light53cb16b2014-06-12 11:26:29 -0700936
Ian Rogersd4c4d952014-10-16 20:31:53 -0700937 for (int i = 0; i < argc; ++i) {
Alex Light53cb16b2014-06-12 11:26:29 -0700938 const StringPiece option(argv[i]);
939 const bool log_options = false;
940 if (log_options) {
941 LOG(INFO) << "patchoat: option[" << i << "]=" << argv[i];
942 }
Alex Light53cb16b2014-06-12 11:26:29 -0700943 if (option.starts_with("--instruction-set=")) {
944 isa_set = true;
945 const char* isa_str = option.substr(strlen("--instruction-set=")).data();
Andreas Gampe20c89302014-08-19 17:28:06 -0700946 isa = GetInstructionSetFromString(isa_str);
947 if (isa == kNone) {
948 Usage("Unknown or invalid instruction set %s", isa_str);
Alex Light53cb16b2014-06-12 11:26:29 -0700949 }
950 } else if (option.starts_with("--input-oat-location=")) {
951 if (have_input_oat) {
952 Usage("Only one of --input-oat-file, --input-oat-location and --input-oat-fd may be used.");
953 }
954 have_input_oat = true;
955 input_oat_location = option.substr(strlen("--input-oat-location=")).data();
956 } else if (option.starts_with("--input-oat-file=")) {
957 if (have_input_oat) {
958 Usage("Only one of --input-oat-file, --input-oat-location and --input-oat-fd may be used.");
959 }
960 have_input_oat = true;
961 input_oat_filename = option.substr(strlen("--input-oat-file=")).data();
962 } else if (option.starts_with("--input-oat-fd=")) {
963 if (have_input_oat) {
964 Usage("Only one of --input-oat-file, --input-oat-location and --input-oat-fd may be used.");
965 }
966 have_input_oat = true;
967 const char* oat_fd_str = option.substr(strlen("--input-oat-fd=")).data();
968 if (!ParseInt(oat_fd_str, &input_oat_fd)) {
969 Usage("Failed to parse --input-oat-fd argument '%s' as an integer", oat_fd_str);
970 }
971 if (input_oat_fd < 0) {
972 Usage("--input-oat-fd pass a negative value %d", input_oat_fd);
973 }
974 } else if (option.starts_with("--input-image-location=")) {
975 input_image_location = option.substr(strlen("--input-image-location=")).data();
Alex Light53cb16b2014-06-12 11:26:29 -0700976 } else if (option.starts_with("--output-oat-file=")) {
977 if (have_output_oat) {
Alex Lightcf4bf382014-07-24 11:29:14 -0700978 Usage("Only one of --output-oat-file, and --output-oat-fd may be used.");
Alex Light53cb16b2014-06-12 11:26:29 -0700979 }
980 have_output_oat = true;
981 output_oat_filename = option.substr(strlen("--output-oat-file=")).data();
982 } else if (option.starts_with("--output-oat-fd=")) {
983 if (have_output_oat) {
Alex Lightcf4bf382014-07-24 11:29:14 -0700984 Usage("Only one of --output-oat-file, --output-oat-fd may be used.");
Alex Light53cb16b2014-06-12 11:26:29 -0700985 }
986 have_output_oat = true;
987 const char* oat_fd_str = option.substr(strlen("--output-oat-fd=")).data();
988 if (!ParseInt(oat_fd_str, &output_oat_fd)) {
989 Usage("Failed to parse --output-oat-fd argument '%s' as an integer", oat_fd_str);
990 }
991 if (output_oat_fd < 0) {
992 Usage("--output-oat-fd pass a negative value %d", output_oat_fd);
993 }
Alex Light53cb16b2014-06-12 11:26:29 -0700994 } else if (option.starts_with("--output-image-file=")) {
995 if (have_output_image) {
Alex Lightcf4bf382014-07-24 11:29:14 -0700996 Usage("Only one of --output-image-file, and --output-image-fd may be used.");
Alex Light53cb16b2014-06-12 11:26:29 -0700997 }
998 have_output_image = true;
999 output_image_filename = option.substr(strlen("--output-image-file=")).data();
1000 } else if (option.starts_with("--output-image-fd=")) {
1001 if (have_output_image) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001002 Usage("Only one of --output-image-file, and --output-image-fd may be used.");
Alex Light53cb16b2014-06-12 11:26:29 -07001003 }
1004 have_output_image = true;
1005 const char* image_fd_str = option.substr(strlen("--output-image-fd=")).data();
1006 if (!ParseInt(image_fd_str, &output_image_fd)) {
1007 Usage("Failed to parse --output-image-fd argument '%s' as an integer", image_fd_str);
1008 }
1009 if (output_image_fd < 0) {
1010 Usage("--output-image-fd pass a negative value %d", output_image_fd);
1011 }
1012 } else if (option.starts_with("--orig-base-offset=")) {
1013 const char* orig_base_offset_str = option.substr(strlen("--orig-base-offset=")).data();
1014 orig_base_offset_set = true;
1015 if (!ParseUint(orig_base_offset_str, &orig_base_offset)) {
1016 Usage("Failed to parse --orig-base-offset argument '%s' as an uintptr_t",
1017 orig_base_offset_str);
1018 }
1019 } else if (option.starts_with("--base-offset=")) {
1020 const char* base_offset_str = option.substr(strlen("--base-offset=")).data();
1021 base_offset_set = true;
1022 if (!ParseUint(base_offset_str, &base_offset)) {
1023 Usage("Failed to parse --base-offset argument '%s' as an uintptr_t", base_offset_str);
1024 }
1025 } else if (option.starts_with("--base-offset-delta=")) {
1026 const char* base_delta_str = option.substr(strlen("--base-offset-delta=")).data();
1027 base_delta_set = true;
1028 if (!ParseInt(base_delta_str, &base_delta)) {
1029 Usage("Failed to parse --base-offset-delta argument '%s' as an off_t", base_delta_str);
1030 }
1031 } else if (option.starts_with("--patched-image-location=")) {
1032 patched_image_location = option.substr(strlen("--patched-image-location=")).data();
1033 } else if (option.starts_with("--patched-image-file=")) {
1034 patched_image_filename = option.substr(strlen("--patched-image-file=")).data();
Alex Lightcf4bf382014-07-24 11:29:14 -07001035 } else if (option == "--lock-output") {
1036 lock_output = true;
1037 } else if (option == "--no-lock-output") {
1038 lock_output = false;
Alex Light53cb16b2014-06-12 11:26:29 -07001039 } else if (option == "--dump-timings") {
1040 dump_timings = true;
1041 } else if (option == "--no-dump-timings") {
1042 dump_timings = false;
1043 } else {
1044 Usage("Unknown argument %s", option.data());
1045 }
1046 }
1047
1048 {
1049 // Only 1 of these may be set.
1050 uint32_t cnt = 0;
1051 cnt += (base_delta_set) ? 1 : 0;
1052 cnt += (base_offset_set && orig_base_offset_set) ? 1 : 0;
1053 cnt += (!patched_image_filename.empty()) ? 1 : 0;
1054 cnt += (!patched_image_location.empty()) ? 1 : 0;
1055 if (cnt > 1) {
1056 Usage("Only one of --base-offset/--orig-base-offset, --base-offset-delta, "
1057 "--patched-image-filename or --patched-image-location may be used.");
1058 } else if (cnt == 0) {
1059 Usage("Must specify --base-offset-delta, --base-offset and --orig-base-offset, "
1060 "--patched-image-location or --patched-image-file");
1061 }
1062 }
1063
1064 if (have_input_oat != have_output_oat) {
1065 Usage("Either both input and output oat must be supplied or niether must be.");
1066 }
1067
1068 if ((!input_image_location.empty()) != have_output_image) {
1069 Usage("Either both input and output image must be supplied or niether must be.");
1070 }
1071
1072 // We know we have both the input and output so rename for clarity.
1073 bool have_image_files = have_output_image;
1074 bool have_oat_files = have_output_oat;
1075
1076 if (!have_oat_files && !have_image_files) {
1077 Usage("Must be patching either an oat or an image file or both.");
1078 }
1079
1080 if (!have_oat_files && !isa_set) {
1081 Usage("Must include ISA if patching an image file without an oat file.");
1082 }
1083
1084 if (!input_oat_location.empty()) {
1085 if (!isa_set) {
1086 Usage("specifying a location requires specifying an instruction set");
1087 }
Alex Lightcf4bf382014-07-24 11:29:14 -07001088 if (!LocationToFilename(input_oat_location, isa, &input_oat_filename)) {
1089 Usage("Unable to find filename for input oat location %s", input_oat_location.c_str());
1090 }
Alex Light53cb16b2014-06-12 11:26:29 -07001091 if (debug) {
1092 LOG(INFO) << "Using input-oat-file " << input_oat_filename;
1093 }
1094 }
Alex Light53cb16b2014-06-12 11:26:29 -07001095 if (!patched_image_location.empty()) {
1096 if (!isa_set) {
1097 Usage("specifying a location requires specifying an instruction set");
1098 }
Alex Lighta59dd802014-07-02 16:28:08 -07001099 std::string system_filename;
1100 bool has_system = false;
1101 std::string cache_filename;
1102 bool has_cache = false;
1103 bool has_android_data_unused = false;
Andreas Gampe3c13a792014-09-18 20:56:04 -07001104 bool is_global_cache = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001105 if (!gc::space::ImageSpace::FindImageFilename(patched_image_location.c_str(), isa,
1106 &system_filename, &has_system, &cache_filename,
Andreas Gampe3c13a792014-09-18 20:56:04 -07001107 &has_android_data_unused, &has_cache,
1108 &is_global_cache)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001109 Usage("Unable to determine image file for location %s", patched_image_location.c_str());
1110 }
1111 if (has_cache) {
1112 patched_image_filename = cache_filename;
1113 } else if (has_system) {
1114 LOG(WARNING) << "Only image file found was in /system for image location "
1115 << patched_image_location;
1116 patched_image_filename = system_filename;
1117 } else {
1118 Usage("Unable to determine image file for location %s", patched_image_location.c_str());
1119 }
Alex Light53cb16b2014-06-12 11:26:29 -07001120 if (debug) {
1121 LOG(INFO) << "Using patched-image-file " << patched_image_filename;
1122 }
1123 }
1124
1125 if (!base_delta_set) {
1126 if (orig_base_offset_set && base_offset_set) {
1127 base_delta_set = true;
1128 base_delta = base_offset - orig_base_offset;
1129 } else if (!patched_image_filename.empty()) {
1130 base_delta_set = true;
1131 std::string error_msg;
Alex Lighteefbe392014-07-08 09:53:18 -07001132 if (!ReadBaseDelta(patched_image_filename.c_str(), &base_delta, &error_msg)) {
Alex Light53cb16b2014-06-12 11:26:29 -07001133 Usage(error_msg.c_str(), patched_image_filename.c_str());
1134 }
1135 } else {
1136 if (base_offset_set) {
1137 Usage("Unable to determine original base offset.");
1138 } else {
1139 Usage("Must supply a desired new offset or delta.");
1140 }
1141 }
1142 }
1143
1144 if (!IsAligned<kPageSize>(base_delta)) {
1145 Usage("Base offset/delta must be alligned to a pagesize (0x%08x) boundary.", kPageSize);
1146 }
1147
1148 // Do we need to cleanup output files if we fail?
1149 bool new_image_out = false;
1150 bool new_oat_out = false;
1151
1152 std::unique_ptr<File> input_oat;
1153 std::unique_ptr<File> output_oat;
1154 std::unique_ptr<File> output_image;
1155
1156 if (have_image_files) {
1157 CHECK(!input_image_location.empty());
1158
1159 if (output_image_fd != -1) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001160 if (output_image_filename.empty()) {
1161 output_image_filename = "output-image-file";
1162 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001163 output_image.reset(new File(output_image_fd, output_image_filename, true));
Alex Light53cb16b2014-06-12 11:26:29 -07001164 } else {
1165 CHECK(!output_image_filename.empty());
1166 output_image.reset(CreateOrOpen(output_image_filename.c_str(), &new_image_out));
1167 }
1168 } else {
1169 CHECK(output_image_filename.empty() && output_image_fd == -1 && input_image_location.empty());
1170 }
1171
1172 if (have_oat_files) {
1173 if (input_oat_fd != -1) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001174 if (input_oat_filename.empty()) {
1175 input_oat_filename = "input-oat-file";
1176 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001177 input_oat.reset(new File(input_oat_fd, input_oat_filename, false));
Igor Murashkin46774762014-10-22 11:37:02 -07001178 if (input_oat == nullptr) {
1179 // Unlikely, but ensure exhaustive logging in non-0 exit code case
1180 LOG(ERROR) << "Failed to open input oat file by its FD" << input_oat_fd;
1181 }
Alex Light53cb16b2014-06-12 11:26:29 -07001182 } else {
1183 CHECK(!input_oat_filename.empty());
1184 input_oat.reset(OS::OpenFileForReading(input_oat_filename.c_str()));
Igor Murashkin46774762014-10-22 11:37:02 -07001185 if (input_oat == nullptr) {
1186 int err = errno;
1187 LOG(ERROR) << "Failed to open input oat file " << input_oat_filename
1188 << ": " << strerror(err) << "(" << err << ")";
Andreas Gampe1c83cbc2014-07-22 18:52:29 -07001189 }
Alex Light53cb16b2014-06-12 11:26:29 -07001190 }
1191
1192 if (output_oat_fd != -1) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001193 if (output_oat_filename.empty()) {
1194 output_oat_filename = "output-oat-file";
Alex Lighta59dd802014-07-02 16:28:08 -07001195 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001196 output_oat.reset(new File(output_oat_fd, output_oat_filename, true));
Igor Murashkin46774762014-10-22 11:37:02 -07001197 if (output_oat == nullptr) {
1198 // Unlikely, but ensure exhaustive logging in non-0 exit code case
1199 LOG(ERROR) << "Failed to open output oat file by its FD" << output_oat_fd;
1200 }
Alex Light53cb16b2014-06-12 11:26:29 -07001201 } else {
1202 CHECK(!output_oat_filename.empty());
1203 output_oat.reset(CreateOrOpen(output_oat_filename.c_str(), &new_oat_out));
Igor Murashkin46774762014-10-22 11:37:02 -07001204 if (output_oat == nullptr) {
1205 int err = errno;
1206 LOG(ERROR) << "Failed to open output oat file " << output_oat_filename
1207 << ": " << strerror(err) << "(" << err << ")";
1208 }
Alex Light53cb16b2014-06-12 11:26:29 -07001209 }
1210 }
1211
Igor Murashkin46774762014-10-22 11:37:02 -07001212 // TODO: get rid of this.
Alex Light53cb16b2014-06-12 11:26:29 -07001213 auto cleanup = [&output_image_filename, &output_oat_filename,
1214 &new_oat_out, &new_image_out, &timings, &dump_timings](bool success) {
1215 timings.EndTiming();
1216 if (!success) {
1217 if (new_oat_out) {
1218 CHECK(!output_oat_filename.empty());
Brian Carlstrom8c52a3f2014-09-30 16:18:01 -07001219 TEMP_FAILURE_RETRY(unlink(output_oat_filename.c_str()));
Alex Light53cb16b2014-06-12 11:26:29 -07001220 }
1221 if (new_image_out) {
1222 CHECK(!output_image_filename.empty());
Brian Carlstrom8c52a3f2014-09-30 16:18:01 -07001223 TEMP_FAILURE_RETRY(unlink(output_image_filename.c_str()));
Alex Light53cb16b2014-06-12 11:26:29 -07001224 }
1225 }
1226 if (dump_timings) {
1227 LOG(INFO) << Dumpable<TimingLogger>(timings);
1228 }
Igor Murashkin46774762014-10-22 11:37:02 -07001229
1230 if (kIsDebugBuild) {
1231 LOG(INFO) << "Cleaning up.. success? " << success;
1232 }
Alex Light53cb16b2014-06-12 11:26:29 -07001233 };
1234
Igor Murashkin46774762014-10-22 11:37:02 -07001235 if (have_oat_files && (input_oat.get() == nullptr || output_oat.get() == nullptr)) {
1236 LOG(ERROR) << "Failed to open input/output oat files";
1237 cleanup(false);
1238 return EXIT_FAILURE;
1239 } else if (have_image_files && output_image.get() == nullptr) {
1240 LOG(ERROR) << "Failed to open output image file";
Alex Lightcf4bf382014-07-24 11:29:14 -07001241 cleanup(false);
1242 return EXIT_FAILURE;
1243 }
1244
Igor Murashkin46774762014-10-22 11:37:02 -07001245 if (debug) {
1246 LOG(INFO) << "moving offset by " << base_delta
1247 << " (0x" << std::hex << base_delta << ") bytes or "
1248 << std::dec << (base_delta/kPageSize) << " pages.";
1249 }
1250
1251 // TODO: is it going to be promatic to unlink a file that was flock-ed?
Alex Lightcf4bf382014-07-24 11:29:14 -07001252 ScopedFlock output_oat_lock;
1253 if (lock_output) {
1254 std::string error_msg;
1255 if (have_oat_files && !output_oat_lock.Init(output_oat.get(), &error_msg)) {
1256 LOG(ERROR) << "Unable to lock output oat " << output_image->GetPath() << ": " << error_msg;
1257 cleanup(false);
1258 return EXIT_FAILURE;
1259 }
1260 }
1261
Alex Light53cb16b2014-06-12 11:26:29 -07001262 bool ret;
1263 if (have_image_files && have_oat_files) {
1264 TimingLogger::ScopedTiming pt("patch image and oat", &timings);
1265 ret = PatchOat::Patch(input_oat.get(), input_image_location, base_delta,
Igor Murashkin46774762014-10-22 11:37:02 -07001266 output_oat.get(), output_image.get(), isa, &timings,
1267 output_oat_fd >= 0, // was it opened from FD?
1268 new_oat_out);
Andreas Gampe4303ba92014-11-06 01:00:46 -08001269 // The order here doesn't matter. If the first one is successfully saved and the second one
1270 // erased, ImageSpace will still detect a problem and not use the files.
1271 ret = ret && FinishFile(output_image.get(), ret);
1272 ret = ret && FinishFile(output_oat.get(), ret);
Alex Light53cb16b2014-06-12 11:26:29 -07001273 } else if (have_oat_files) {
1274 TimingLogger::ScopedTiming pt("patch oat", &timings);
Igor Murashkin46774762014-10-22 11:37:02 -07001275 ret = PatchOat::Patch(input_oat.get(), base_delta, output_oat.get(), &timings,
1276 output_oat_fd >= 0, // was it opened from FD?
1277 new_oat_out);
Andreas Gampe4303ba92014-11-06 01:00:46 -08001278 ret = ret && FinishFile(output_oat.get(), ret);
Igor Murashkin46774762014-10-22 11:37:02 -07001279 } else if (have_image_files) {
Alex Light53cb16b2014-06-12 11:26:29 -07001280 TimingLogger::ScopedTiming pt("patch image", &timings);
Alex Lighteefbe392014-07-08 09:53:18 -07001281 ret = PatchOat::Patch(input_image_location, base_delta, output_image.get(), isa, &timings);
Andreas Gampe4303ba92014-11-06 01:00:46 -08001282 ret = ret && FinishFile(output_image.get(), ret);
Igor Murashkin46774762014-10-22 11:37:02 -07001283 } else {
1284 CHECK(false);
1285 ret = true;
1286 }
1287
1288 if (kIsDebugBuild) {
1289 LOG(INFO) << "Exiting with return ... " << ret;
Alex Light53cb16b2014-06-12 11:26:29 -07001290 }
1291 cleanup(ret);
Alex Light53cb16b2014-06-12 11:26:29 -07001292 return (ret) ? EXIT_SUCCESS : EXIT_FAILURE;
1293}
1294
1295} // namespace art
1296
1297int main(int argc, char **argv) {
1298 return art::patchoat(argc, argv);
1299}