blob: d54e1b2dd4e22f80fcdd2b28256d7f9e587c7ca4 [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
Mathieu Chartierc7853442015-03-27 14:35:38 -070027#include "art_field-inl.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070028#include "art_method-inl.h"
Ian Rogersc7dd2952014-10-21 23:31:19 -070029#include "base/dumpable.h"
Alex Lighta59dd802014-07-02 16:28:08 -070030#include "base/scoped_flock.h"
Alex Light53cb16b2014-06-12 11:26:29 -070031#include "base/stringpiece.h"
32#include "base/stringprintf.h"
Ian Rogersd4c4d952014-10-16 20:31:53 -070033#include "base/unix_file/fd_file.h"
Alex Light53cb16b2014-06-12 11:26:29 -070034#include "elf_utils.h"
35#include "elf_file.h"
Tong Shen62d1ca32014-09-03 17:24:56 -070036#include "elf_file_impl.h"
Ian Rogerse63db272014-07-15 15:36:11 -070037#include "gc/space/image_space.h"
Alex Light53cb16b2014-06-12 11:26:29 -070038#include "image.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070039#include "mirror/abstract_method.h"
Alex Light53cb16b2014-06-12 11:26:29 -070040#include "mirror/object-inl.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070041#include "mirror/method.h"
Alex Light53cb16b2014-06-12 11:26:29 -070042#include "mirror/reference.h"
43#include "noop_compiler_callbacks.h"
44#include "offsets.h"
45#include "os.h"
46#include "runtime.h"
47#include "scoped_thread_state_change.h"
48#include "thread.h"
49#include "utils.h"
50
51namespace art {
52
Alex Lightcf4bf382014-07-24 11:29:14 -070053static bool LocationToFilename(const std::string& location, InstructionSet isa,
54 std::string* filename) {
55 bool has_system = false;
56 bool has_cache = false;
57 // image_location = /system/framework/boot.art
Igor Murashkin46774762014-10-22 11:37:02 -070058 // system_image_filename = /system/framework/<image_isa>/boot.art
Alex Lightcf4bf382014-07-24 11:29:14 -070059 std::string system_filename(GetSystemImageFilename(location.c_str(), isa));
60 if (OS::FileExists(system_filename.c_str())) {
61 has_system = true;
62 }
63
64 bool have_android_data = false;
65 bool dalvik_cache_exists = false;
Andreas Gampe3c13a792014-09-18 20:56:04 -070066 bool is_global_cache = false;
Alex Lightcf4bf382014-07-24 11:29:14 -070067 std::string dalvik_cache;
68 GetDalvikCache(GetInstructionSetString(isa), false, &dalvik_cache,
Andreas Gampe3c13a792014-09-18 20:56:04 -070069 &have_android_data, &dalvik_cache_exists, &is_global_cache);
Alex Lightcf4bf382014-07-24 11:29:14 -070070
71 std::string cache_filename;
72 if (have_android_data && dalvik_cache_exists) {
73 // Always set output location even if it does not exist,
74 // so that the caller knows where to create the image.
75 //
76 // image_location = /system/framework/boot.art
77 // *image_filename = /data/dalvik-cache/<image_isa>/boot.art
78 std::string error_msg;
79 if (GetDalvikCacheFilename(location.c_str(), dalvik_cache.c_str(),
80 &cache_filename, &error_msg)) {
81 has_cache = true;
82 }
83 }
84 if (has_system) {
85 *filename = system_filename;
86 return true;
87 } else if (has_cache) {
88 *filename = cache_filename;
89 return true;
90 } else {
91 return false;
92 }
93}
94
Alex Light53cb16b2014-06-12 11:26:29 -070095bool PatchOat::Patch(const std::string& image_location, off_t delta,
96 File* output_image, InstructionSet isa,
Alex Lighteefbe392014-07-08 09:53:18 -070097 TimingLogger* timings) {
Alex Light53cb16b2014-06-12 11:26:29 -070098 CHECK(Runtime::Current() == nullptr);
99 CHECK(output_image != nullptr);
100 CHECK_GE(output_image->Fd(), 0);
101 CHECK(!image_location.empty()) << "image file must have a filename.";
102 CHECK_NE(isa, kNone);
103
Alex Lighteefbe392014-07-08 09:53:18 -0700104 TimingLogger::ScopedTiming t("Runtime Setup", timings);
Alex Light53cb16b2014-06-12 11:26:29 -0700105 const char *isa_name = GetInstructionSetString(isa);
Alex Lightcf4bf382014-07-24 11:29:14 -0700106 std::string image_filename;
107 if (!LocationToFilename(image_location, isa, &image_filename)) {
108 LOG(ERROR) << "Unable to find image at location " << image_location;
109 return false;
110 }
Alex Light53cb16b2014-06-12 11:26:29 -0700111 std::unique_ptr<File> input_image(OS::OpenFileForReading(image_filename.c_str()));
112 if (input_image.get() == nullptr) {
Alex Lightcf4bf382014-07-24 11:29:14 -0700113 LOG(ERROR) << "unable to open input image file at " << image_filename
114 << " for location " << image_location;
Alex Light53cb16b2014-06-12 11:26:29 -0700115 return false;
116 }
Igor Murashkin46774762014-10-22 11:37:02 -0700117
Alex Light53cb16b2014-06-12 11:26:29 -0700118 int64_t image_len = input_image->GetLength();
119 if (image_len < 0) {
120 LOG(ERROR) << "Error while getting image length";
121 return false;
122 }
123 ImageHeader image_header;
124 if (sizeof(image_header) != input_image->Read(reinterpret_cast<char*>(&image_header),
Mathieu Chartiere401d142015-04-22 13:56:20 -0700125 sizeof(image_header), 0)) {
Alex Light53cb16b2014-06-12 11:26:29 -0700126 LOG(ERROR) << "Unable to read image header from image file " << input_image->GetPath();
127 return false;
128 }
129
Igor Murashkin46774762014-10-22 11:37:02 -0700130 /*bool is_image_pic = */IsImagePic(image_header, input_image->GetPath());
131 // Nothing special to do right now since the image always needs to get patched.
132 // Perhaps in some far-off future we may have images with relative addresses that are true-PIC.
133
Alex Light53cb16b2014-06-12 11:26:29 -0700134 // Set up the runtime
Ian Rogerse63db272014-07-15 15:36:11 -0700135 RuntimeOptions options;
Alex Light53cb16b2014-06-12 11:26:29 -0700136 NoopCompilerCallbacks callbacks;
137 options.push_back(std::make_pair("compilercallbacks", &callbacks));
138 std::string img = "-Ximage:" + image_location;
139 options.push_back(std::make_pair(img.c_str(), nullptr));
140 options.push_back(std::make_pair("imageinstructionset", reinterpret_cast<const void*>(isa_name)));
Calin Juravle01aaf6e2015-06-19 22:05:39 +0100141 options.push_back(std::make_pair("-Xno-sig-chain", nullptr));
Alex Light53cb16b2014-06-12 11:26:29 -0700142 if (!Runtime::Create(options, false)) {
143 LOG(ERROR) << "Unable to initialize runtime";
144 return false;
145 }
146 // Runtime::Create acquired the mutator_lock_ that is normally given away when we Runtime::Start,
147 // give it away now and then switch to a more manageable ScopedObjectAccess.
148 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
149 ScopedObjectAccess soa(Thread::Current());
150
151 t.NewTiming("Image and oat Patching setup");
152 // Create the map where we will write the image patches to.
Alex Lighteefbe392014-07-08 09:53:18 -0700153 std::string error_msg;
Alex Light53cb16b2014-06-12 11:26:29 -0700154 std::unique_ptr<MemMap> image(MemMap::MapFile(image_len, PROT_READ | PROT_WRITE, MAP_PRIVATE,
155 input_image->Fd(), 0,
156 input_image->GetPath().c_str(),
157 &error_msg));
158 if (image.get() == nullptr) {
159 LOG(ERROR) << "unable to map image file " << input_image->GetPath() << " : " << error_msg;
160 return false;
161 }
162 gc::space::ImageSpace* ispc = Runtime::Current()->GetHeap()->GetImageSpace();
163
Mathieu Chartier2d721012014-11-10 11:08:06 -0800164 PatchOat p(isa, image.release(), ispc->GetLiveBitmap(), ispc->GetMemMap(),
Alex Light53cb16b2014-06-12 11:26:29 -0700165 delta, timings);
166 t.NewTiming("Patching files");
167 if (!p.PatchImage()) {
Alex Lighta59dd802014-07-02 16:28:08 -0700168 LOG(ERROR) << "Failed to patch image file " << input_image->GetPath();
Alex Light53cb16b2014-06-12 11:26:29 -0700169 return false;
170 }
171
172 t.NewTiming("Writing files");
173 if (!p.WriteImage(output_image)) {
174 return false;
175 }
176 return true;
177}
178
Igor Murashkin46774762014-10-22 11:37:02 -0700179bool PatchOat::Patch(File* input_oat, const std::string& image_location, off_t delta,
Alex Light53cb16b2014-06-12 11:26:29 -0700180 File* output_oat, File* output_image, InstructionSet isa,
Igor Murashkin46774762014-10-22 11:37:02 -0700181 TimingLogger* timings,
182 bool output_oat_opened_from_fd,
183 bool new_oat_out) {
Alex Light53cb16b2014-06-12 11:26:29 -0700184 CHECK(Runtime::Current() == nullptr);
185 CHECK(output_image != nullptr);
186 CHECK_GE(output_image->Fd(), 0);
187 CHECK(input_oat != nullptr);
188 CHECK(output_oat != nullptr);
189 CHECK_GE(input_oat->Fd(), 0);
190 CHECK_GE(output_oat->Fd(), 0);
191 CHECK(!image_location.empty()) << "image file must have a filename.";
192
Alex Lighteefbe392014-07-08 09:53:18 -0700193 TimingLogger::ScopedTiming t("Runtime Setup", timings);
Alex Light53cb16b2014-06-12 11:26:29 -0700194
195 if (isa == kNone) {
196 Elf32_Ehdr elf_hdr;
197 if (sizeof(elf_hdr) != input_oat->Read(reinterpret_cast<char*>(&elf_hdr), sizeof(elf_hdr), 0)) {
198 LOG(ERROR) << "unable to read elf header";
199 return false;
200 }
Andreas Gampe6f611412015-01-21 22:25:24 -0800201 isa = GetInstructionSetFromELF(elf_hdr.e_machine, elf_hdr.e_flags);
Alex Light53cb16b2014-06-12 11:26:29 -0700202 }
203 const char* isa_name = GetInstructionSetString(isa);
Alex Lightcf4bf382014-07-24 11:29:14 -0700204 std::string image_filename;
205 if (!LocationToFilename(image_location, isa, &image_filename)) {
206 LOG(ERROR) << "Unable to find image at location " << image_location;
207 return false;
208 }
Alex Light53cb16b2014-06-12 11:26:29 -0700209 std::unique_ptr<File> input_image(OS::OpenFileForReading(image_filename.c_str()));
210 if (input_image.get() == nullptr) {
Alex Lightcf4bf382014-07-24 11:29:14 -0700211 LOG(ERROR) << "unable to open input image file at " << image_filename
212 << " for location " << image_location;
Alex Light53cb16b2014-06-12 11:26:29 -0700213 return false;
214 }
215 int64_t image_len = input_image->GetLength();
216 if (image_len < 0) {
217 LOG(ERROR) << "Error while getting image length";
218 return false;
219 }
220 ImageHeader image_header;
221 if (sizeof(image_header) != input_image->Read(reinterpret_cast<char*>(&image_header),
222 sizeof(image_header), 0)) {
223 LOG(ERROR) << "Unable to read image header from image file " << input_image->GetPath();
224 }
225
Igor Murashkin46774762014-10-22 11:37:02 -0700226 /*bool is_image_pic = */IsImagePic(image_header, input_image->GetPath());
227 // Nothing special to do right now since the image always needs to get patched.
228 // Perhaps in some far-off future we may have images with relative addresses that are true-PIC.
229
Alex Light53cb16b2014-06-12 11:26:29 -0700230 // Set up the runtime
Ian Rogerse63db272014-07-15 15:36:11 -0700231 RuntimeOptions options;
Alex Light53cb16b2014-06-12 11:26:29 -0700232 NoopCompilerCallbacks callbacks;
233 options.push_back(std::make_pair("compilercallbacks", &callbacks));
234 std::string img = "-Ximage:" + image_location;
235 options.push_back(std::make_pair(img.c_str(), nullptr));
236 options.push_back(std::make_pair("imageinstructionset", reinterpret_cast<const void*>(isa_name)));
Calin Juravle01aaf6e2015-06-19 22:05:39 +0100237 options.push_back(std::make_pair("-Xno-sig-chain", nullptr));
Alex Light53cb16b2014-06-12 11:26:29 -0700238 if (!Runtime::Create(options, false)) {
239 LOG(ERROR) << "Unable to initialize runtime";
240 return false;
241 }
242 // Runtime::Create acquired the mutator_lock_ that is normally given away when we Runtime::Start,
243 // give it away now and then switch to a more manageable ScopedObjectAccess.
244 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
245 ScopedObjectAccess soa(Thread::Current());
246
247 t.NewTiming("Image and oat Patching setup");
248 // Create the map where we will write the image patches to.
Alex Lighteefbe392014-07-08 09:53:18 -0700249 std::string error_msg;
Alex Light53cb16b2014-06-12 11:26:29 -0700250 std::unique_ptr<MemMap> image(MemMap::MapFile(image_len, PROT_READ | PROT_WRITE, MAP_PRIVATE,
251 input_image->Fd(), 0,
252 input_image->GetPath().c_str(),
253 &error_msg));
254 if (image.get() == nullptr) {
255 LOG(ERROR) << "unable to map image file " << input_image->GetPath() << " : " << error_msg;
256 return false;
257 }
258 gc::space::ImageSpace* ispc = Runtime::Current()->GetHeap()->GetImageSpace();
259
Igor Murashkin46774762014-10-22 11:37:02 -0700260 std::unique_ptr<ElfFile> elf(ElfFile::Open(input_oat,
Alex Light53cb16b2014-06-12 11:26:29 -0700261 PROT_READ | PROT_WRITE, MAP_PRIVATE, &error_msg));
262 if (elf.get() == nullptr) {
263 LOG(ERROR) << "unable to open oat file " << input_oat->GetPath() << " : " << error_msg;
264 return false;
265 }
266
Igor Murashkin46774762014-10-22 11:37:02 -0700267 bool skip_patching_oat = false;
268 MaybePic is_oat_pic = IsOatPic(elf.get());
269 if (is_oat_pic >= ERROR_FIRST) {
270 // Error logged by IsOatPic
271 return false;
272 } else if (is_oat_pic == PIC) {
273 // Do not need to do ELF-file patching. Create a symlink and skip the ELF patching.
274 if (!ReplaceOatFileWithSymlink(input_oat->GetPath(),
275 output_oat->GetPath(),
276 output_oat_opened_from_fd,
277 new_oat_out)) {
278 // Errors already logged by above call.
279 return false;
280 }
281 // Don't patch the OAT, since we just symlinked it. Image still needs patching.
282 skip_patching_oat = true;
283 } else {
284 CHECK(is_oat_pic == NOT_PIC);
285 }
286
Mathieu Chartier2d721012014-11-10 11:08:06 -0800287 PatchOat p(isa, elf.release(), image.release(), ispc->GetLiveBitmap(), ispc->GetMemMap(),
Alex Light53cb16b2014-06-12 11:26:29 -0700288 delta, timings);
289 t.NewTiming("Patching files");
Igor Murashkin46774762014-10-22 11:37:02 -0700290 if (!skip_patching_oat && !p.PatchElf()) {
Alex Lighta59dd802014-07-02 16:28:08 -0700291 LOG(ERROR) << "Failed to patch oat file " << input_oat->GetPath();
Alex Light53cb16b2014-06-12 11:26:29 -0700292 return false;
293 }
294 if (!p.PatchImage()) {
Alex Lighta59dd802014-07-02 16:28:08 -0700295 LOG(ERROR) << "Failed to patch image file " << input_image->GetPath();
Alex Light53cb16b2014-06-12 11:26:29 -0700296 return false;
297 }
298
299 t.NewTiming("Writing files");
Igor Murashkin46774762014-10-22 11:37:02 -0700300 if (!skip_patching_oat && !p.WriteElf(output_oat)) {
301 LOG(ERROR) << "Failed to write oat file " << input_oat->GetPath();
Alex Light53cb16b2014-06-12 11:26:29 -0700302 return false;
303 }
304 if (!p.WriteImage(output_image)) {
Igor Murashkin46774762014-10-22 11:37:02 -0700305 LOG(ERROR) << "Failed to write image file " << input_image->GetPath();
Alex Light53cb16b2014-06-12 11:26:29 -0700306 return false;
307 }
308 return true;
309}
310
311bool PatchOat::WriteElf(File* out) {
Alex Lighteefbe392014-07-08 09:53:18 -0700312 TimingLogger::ScopedTiming t("Writing Elf File", timings_);
Alex Lighta59dd802014-07-02 16:28:08 -0700313
Alex Light53cb16b2014-06-12 11:26:29 -0700314 CHECK(oat_file_.get() != nullptr);
315 CHECK(out != nullptr);
316 size_t expect = oat_file_->Size();
317 if (out->WriteFully(reinterpret_cast<char*>(oat_file_->Begin()), expect) &&
318 out->SetLength(expect) == 0) {
319 return true;
320 } else {
321 LOG(ERROR) << "Writing to oat file " << out->GetPath() << " failed.";
322 return false;
323 }
324}
325
326bool PatchOat::WriteImage(File* out) {
Alex Lighteefbe392014-07-08 09:53:18 -0700327 TimingLogger::ScopedTiming t("Writing image File", timings_);
Alex Lighta59dd802014-07-02 16:28:08 -0700328 std::string error_msg;
329
Alex Lightcf4bf382014-07-24 11:29:14 -0700330 ScopedFlock img_flock;
331 img_flock.Init(out, &error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -0700332
Alex Light53cb16b2014-06-12 11:26:29 -0700333 CHECK(image_ != nullptr);
334 CHECK(out != nullptr);
335 size_t expect = image_->Size();
336 if (out->WriteFully(reinterpret_cast<char*>(image_->Begin()), expect) &&
337 out->SetLength(expect) == 0) {
338 return true;
339 } else {
340 LOG(ERROR) << "Writing to image file " << out->GetPath() << " failed.";
341 return false;
342 }
343}
344
Igor Murashkin46774762014-10-22 11:37:02 -0700345bool PatchOat::IsImagePic(const ImageHeader& image_header, const std::string& image_path) {
346 if (!image_header.CompilePic()) {
347 if (kIsDebugBuild) {
348 LOG(INFO) << "image at location " << image_path << " was *not* compiled pic";
349 }
350 return false;
351 }
352
353 if (kIsDebugBuild) {
354 LOG(INFO) << "image at location " << image_path << " was compiled PIC";
355 }
356
357 return true;
358}
359
360PatchOat::MaybePic PatchOat::IsOatPic(const ElfFile* oat_in) {
361 if (oat_in == nullptr) {
362 LOG(ERROR) << "No ELF input oat fie available";
363 return ERROR_OAT_FILE;
364 }
365
366 const std::string& file_path = oat_in->GetFile().GetPath();
367
368 const OatHeader* oat_header = GetOatHeader(oat_in);
369 if (oat_header == nullptr) {
370 LOG(ERROR) << "Failed to find oat header in oat file " << file_path;
371 return ERROR_OAT_FILE;
372 }
373
374 if (!oat_header->IsValid()) {
375 LOG(ERROR) << "Elf file " << file_path << " has an invalid oat header";
376 return ERROR_OAT_FILE;
377 }
378
379 bool is_pic = oat_header->IsPic();
380 if (kIsDebugBuild) {
381 LOG(INFO) << "Oat file at " << file_path << " is " << (is_pic ? "PIC" : "not pic");
382 }
383
384 return is_pic ? PIC : NOT_PIC;
385}
386
387bool PatchOat::ReplaceOatFileWithSymlink(const std::string& input_oat_filename,
388 const std::string& output_oat_filename,
389 bool output_oat_opened_from_fd,
390 bool new_oat_out) {
391 // Need a file when we are PIC, since we symlink over it. Refusing to symlink into FD.
392 if (output_oat_opened_from_fd) {
393 // TODO: installd uses --output-oat-fd. Should we change class linking logic for PIC?
394 LOG(ERROR) << "No output oat filename specified, needs filename for when we are PIC";
395 return false;
396 }
397
398 // Image was PIC. Create symlink where the oat is supposed to go.
399 if (!new_oat_out) {
400 LOG(ERROR) << "Oat file " << output_oat_filename << " already exists, refusing to overwrite";
401 return false;
402 }
403
404 // Delete the original file, since we won't need it.
405 TEMP_FAILURE_RETRY(unlink(output_oat_filename.c_str()));
406
407 // Create a symlink from the old oat to the new oat
408 if (symlink(input_oat_filename.c_str(), output_oat_filename.c_str()) < 0) {
409 int err = errno;
410 LOG(ERROR) << "Failed to create symlink at " << output_oat_filename
411 << " error(" << err << "): " << strerror(err);
412 return false;
413 }
414
415 if (kIsDebugBuild) {
416 LOG(INFO) << "Created symlink " << output_oat_filename << " -> " << input_oat_filename;
417 }
418
419 return true;
420}
421
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700422class PatchOatArtFieldVisitor : public ArtFieldVisitor {
423 public:
424 explicit PatchOatArtFieldVisitor(PatchOat* patch_oat) : patch_oat_(patch_oat) {}
425
426 void Visit(ArtField* field) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
427 ArtField* const dest = patch_oat_->RelocatedCopyOf(field);
428 dest->SetDeclaringClass(patch_oat_->RelocatedAddressOfPointer(field->GetDeclaringClass()));
Mathieu Chartiere401d142015-04-22 13:56:20 -0700429 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700430
431 private:
432 PatchOat* const patch_oat_;
433};
434
435void PatchOat::PatchArtFields(const ImageHeader* image_header) {
436 PatchOatArtFieldVisitor visitor(this);
437 const auto& section = image_header->GetImageSection(ImageHeader::kSectionArtFields);
438 section.VisitPackedArtFields(&visitor, heap_->Begin());
Mathieu Chartiere401d142015-04-22 13:56:20 -0700439}
440
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700441class PatchOatArtMethodVisitor : public ArtMethodVisitor {
442 public:
443 explicit PatchOatArtMethodVisitor(PatchOat* patch_oat) : patch_oat_(patch_oat) {}
444
445 void Visit(ArtMethod* method) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
446 ArtMethod* const dest = patch_oat_->RelocatedCopyOf(method);
447 patch_oat_->FixupMethod(method, dest);
448 }
449
450 private:
451 PatchOat* const patch_oat_;
452};
453
Mathieu Chartiere401d142015-04-22 13:56:20 -0700454void PatchOat::PatchArtMethods(const ImageHeader* image_header) {
455 const auto& section = image_header->GetMethodsSection();
456 const size_t pointer_size = InstructionSetPointerSize(isa_);
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700457 PatchOatArtMethodVisitor visitor(this);
Vladimir Markocf36d492015-08-12 19:27:26 +0100458 section.VisitPackedArtMethods(&visitor, heap_->Begin(), pointer_size);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700459}
460
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700461class FixupRootVisitor : public RootVisitor {
462 public:
463 explicit FixupRootVisitor(const PatchOat* patch_oat) : patch_oat_(patch_oat) {
464 }
465
466 void VisitRoots(mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -0700467 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700468 for (size_t i = 0; i < count; ++i) {
469 *roots[i] = patch_oat_->RelocatedAddressOfPointer(*roots[i]);
470 }
471 }
472
473 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots, size_t count,
474 const RootInfo& info ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -0700475 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700476 for (size_t i = 0; i < count; ++i) {
477 roots[i]->Assign(patch_oat_->RelocatedAddressOfPointer(roots[i]->AsMirrorPtr()));
478 }
479 }
480
481 private:
482 const PatchOat* const patch_oat_;
483};
484
485void PatchOat::PatchInternedStrings(const ImageHeader* image_header) {
486 const auto& section = image_header->GetImageSection(ImageHeader::kSectionInternedStrings);
487 InternTable temp_table;
488 // Note that we require that ReadFromMemory does not make an internal copy of the elements.
489 // This also relies on visit roots not doing any verification which could fail after we update
490 // the roots to be the image addresses.
491 temp_table.ReadFromMemory(image_->Begin() + section.Offset());
492 FixupRootVisitor visitor(this);
493 temp_table.VisitRoots(&visitor, kVisitRootFlagAllRoots);
494}
495
Mathieu Chartierc7853442015-03-27 14:35:38 -0700496void PatchOat::PatchDexFileArrays(mirror::ObjectArray<mirror::Object>* img_roots) {
497 auto* dex_caches = down_cast<mirror::ObjectArray<mirror::DexCache>*>(
498 img_roots->Get(ImageHeader::kDexCaches));
499 for (size_t i = 0, count = dex_caches->GetLength(); i < count; ++i) {
500 auto* dex_cache = dex_caches->GetWithoutChecks(i);
501 auto* fields = dex_cache->GetResolvedFields();
Mathieu Chartiere401d142015-04-22 13:56:20 -0700502 if (fields != nullptr) {
503 CHECK(!fields->IsObjectArray());
504 CHECK(fields->IsArrayInstance());
505 FixupNativePointerArray(fields);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700506 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700507 auto* methods = dex_cache->GetResolvedMethods();
508 if (methods != nullptr) {
509 CHECK(!methods->IsObjectArray());
510 CHECK(methods->IsArrayInstance());
511 FixupNativePointerArray(methods);
512 }
513 }
514}
515
516void PatchOat::FixupNativePointerArray(mirror::PointerArray* object) {
517 if (object->IsIntArray()) {
518 mirror::IntArray* arr = object->AsIntArray();
519 mirror::IntArray* copy_arr = down_cast<mirror::IntArray*>(RelocatedCopyOf(arr));
520 for (size_t j = 0, count2 = arr->GetLength(); j < count2; ++j) {
521 copy_arr->SetWithoutChecks<false>(
522 j, RelocatedAddressOfIntPointer(arr->GetWithoutChecks(j)));
523 }
524 } else {
525 CHECK(object->IsLongArray());
526 mirror::LongArray* arr = object->AsLongArray();
527 mirror::LongArray* copy_arr = down_cast<mirror::LongArray*>(RelocatedCopyOf(arr));
528 for (size_t j = 0, count2 = arr->GetLength(); j < count2; ++j) {
529 copy_arr->SetWithoutChecks<false>(
530 j, RelocatedAddressOfIntPointer(arr->GetWithoutChecks(j)));
Mathieu Chartierc7853442015-03-27 14:35:38 -0700531 }
532 }
533}
534
Alex Light53cb16b2014-06-12 11:26:29 -0700535bool PatchOat::PatchImage() {
536 ImageHeader* image_header = reinterpret_cast<ImageHeader*>(image_->Begin());
537 CHECK_GT(image_->Size(), sizeof(ImageHeader));
538 // These are the roots from the original file.
Mathieu Chartierc7853442015-03-27 14:35:38 -0700539 auto* img_roots = image_header->GetImageRoots();
Alex Light53cb16b2014-06-12 11:26:29 -0700540 image_header->RelocateImage(delta_);
541
Mathieu Chartierc7853442015-03-27 14:35:38 -0700542 PatchArtFields(image_header);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700543 PatchArtMethods(image_header);
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700544 PatchInternedStrings(image_header);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700545 // Patch dex file int/long arrays which point to ArtFields.
546 PatchDexFileArrays(img_roots);
547
Alex Light53cb16b2014-06-12 11:26:29 -0700548 VisitObject(img_roots);
549 if (!image_header->IsValid()) {
550 LOG(ERROR) << "reloction renders image header invalid";
551 return false;
552 }
553
554 {
Alex Lighteefbe392014-07-08 09:53:18 -0700555 TimingLogger::ScopedTiming t("Walk Bitmap", timings_);
Alex Light53cb16b2014-06-12 11:26:29 -0700556 // Walk the bitmap.
557 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
558 bitmap_->Walk(PatchOat::BitmapCallback, this);
559 }
560 return true;
561}
562
563bool PatchOat::InHeap(mirror::Object* o) {
564 uintptr_t begin = reinterpret_cast<uintptr_t>(heap_->Begin());
565 uintptr_t end = reinterpret_cast<uintptr_t>(heap_->End());
566 uintptr_t obj = reinterpret_cast<uintptr_t>(o);
567 return o == nullptr || (begin <= obj && obj < end);
568}
569
570void PatchOat::PatchVisitor::operator() (mirror::Object* obj, MemberOffset off,
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700571 bool is_static_unused ATTRIBUTE_UNUSED) const {
Alex Light53cb16b2014-06-12 11:26:29 -0700572 mirror::Object* referent = obj->GetFieldObject<mirror::Object, kVerifyNone>(off);
573 DCHECK(patcher_->InHeap(referent)) << "Referent is not in the heap.";
Mathieu Chartierc7853442015-03-27 14:35:38 -0700574 mirror::Object* moved_object = patcher_->RelocatedAddressOfPointer(referent);
Alex Light53cb16b2014-06-12 11:26:29 -0700575 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(off, moved_object);
576}
577
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700578void PatchOat::PatchVisitor::operator() (mirror::Class* cls ATTRIBUTE_UNUSED,
579 mirror::Reference* ref) const {
Alex Light53cb16b2014-06-12 11:26:29 -0700580 MemberOffset off = mirror::Reference::ReferentOffset();
581 mirror::Object* referent = ref->GetReferent();
582 DCHECK(patcher_->InHeap(referent)) << "Referent is not in the heap.";
Mathieu Chartierc7853442015-03-27 14:35:38 -0700583 mirror::Object* moved_object = patcher_->RelocatedAddressOfPointer(referent);
Alex Light53cb16b2014-06-12 11:26:29 -0700584 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(off, moved_object);
585}
586
Igor Murashkin46774762014-10-22 11:37:02 -0700587const OatHeader* PatchOat::GetOatHeader(const ElfFile* elf_file) {
588 if (elf_file->Is64Bit()) {
589 return GetOatHeader<ElfFileImpl64>(elf_file->GetImpl64());
590 } else {
591 return GetOatHeader<ElfFileImpl32>(elf_file->GetImpl32());
592 }
593}
594
595template <typename ElfFileImpl>
596const OatHeader* PatchOat::GetOatHeader(const ElfFileImpl* elf_file) {
597 auto rodata_sec = elf_file->FindSectionByName(".rodata");
598 if (rodata_sec == nullptr) {
599 return nullptr;
600 }
601
602 OatHeader* oat_header = reinterpret_cast<OatHeader*>(elf_file->Begin() + rodata_sec->sh_offset);
603 return oat_header;
604}
605
Alex Light53cb16b2014-06-12 11:26:29 -0700606// Called by BitmapCallback
607void PatchOat::VisitObject(mirror::Object* object) {
608 mirror::Object* copy = RelocatedCopyOf(object);
609 CHECK(copy != nullptr);
610 if (kUseBakerOrBrooksReadBarrier) {
611 object->AssertReadBarrierPointer();
612 if (kUseBrooksReadBarrier) {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700613 mirror::Object* moved_to = RelocatedAddressOfPointer(object);
Alex Light53cb16b2014-06-12 11:26:29 -0700614 copy->SetReadBarrierPointer(moved_to);
615 DCHECK_EQ(copy->GetReadBarrierPointer(), moved_to);
616 }
617 }
618 PatchOat::PatchVisitor visitor(this, copy);
619 object->VisitReferences<true, kVerifyNone>(visitor, visitor);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700620 if (object->IsClass<kVerifyNone>()) {
621 auto* klass = object->AsClass();
622 auto* copy_klass = down_cast<mirror::Class*>(copy);
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700623 copy_klass->SetSFieldsPtrUnchecked(RelocatedAddressOfPointer(klass->GetSFieldsPtr()));
624 copy_klass->SetIFieldsPtrUnchecked(RelocatedAddressOfPointer(klass->GetIFieldsPtr()));
Mathieu Chartiere401d142015-04-22 13:56:20 -0700625 copy_klass->SetDirectMethodsPtrUnchecked(
626 RelocatedAddressOfPointer(klass->GetDirectMethodsPtr()));
627 copy_klass->SetVirtualMethodsPtr(RelocatedAddressOfPointer(klass->GetVirtualMethodsPtr()));
628 auto* vtable = klass->GetVTable();
629 if (vtable != nullptr) {
630 FixupNativePointerArray(vtable);
631 }
632 auto* iftable = klass->GetIfTable();
633 if (iftable != nullptr) {
634 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
635 if (iftable->GetMethodArrayCount(i) > 0) {
636 auto* method_array = iftable->GetMethodArray(i);
637 CHECK(method_array != nullptr);
638 FixupNativePointerArray(method_array);
639 }
640 }
641 }
642 if (klass->ShouldHaveEmbeddedImtAndVTable()) {
643 const size_t pointer_size = InstructionSetPointerSize(isa_);
644 for (int32_t i = 0; i < klass->GetEmbeddedVTableLength(); ++i) {
645 copy_klass->SetEmbeddedVTableEntryUnchecked(i, RelocatedAddressOfPointer(
646 klass->GetEmbeddedVTableEntry(i, pointer_size)), pointer_size);
647 }
648 for (size_t i = 0; i < mirror::Class::kImtSize; ++i) {
649 copy_klass->SetEmbeddedImTableEntry(i, RelocatedAddressOfPointer(
650 klass->GetEmbeddedImTableEntry(i, pointer_size)), pointer_size);
651 }
652 }
653 }
654 if (object->GetClass() == mirror::Method::StaticClass() ||
655 object->GetClass() == mirror::Constructor::StaticClass()) {
656 // Need to go update the ArtMethod.
657 auto* dest = down_cast<mirror::AbstractMethod*>(copy);
658 auto* src = down_cast<mirror::AbstractMethod*>(object);
659 dest->SetArtMethod(RelocatedAddressOfPointer(src->GetArtMethod()));
Alex Light53cb16b2014-06-12 11:26:29 -0700660 }
661}
662
Mathieu Chartiere401d142015-04-22 13:56:20 -0700663void PatchOat::FixupMethod(ArtMethod* object, ArtMethod* copy) {
Mathieu Chartier2d721012014-11-10 11:08:06 -0800664 const size_t pointer_size = InstructionSetPointerSize(isa_);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700665 copy->CopyFrom(object, pointer_size);
Alex Light53cb16b2014-06-12 11:26:29 -0700666 // Just update the entry points if it looks like we should.
Alex Lighteefbe392014-07-08 09:53:18 -0700667 // TODO: sanity check all the pointers' values
Mathieu Chartiere401d142015-04-22 13:56:20 -0700668 copy->SetDeclaringClass(RelocatedAddressOfPointer(object->GetDeclaringClass()));
669 copy->SetDexCacheResolvedMethods(RelocatedAddressOfPointer(object->GetDexCacheResolvedMethods()));
670 copy->SetDexCacheResolvedTypes(RelocatedAddressOfPointer(object->GetDexCacheResolvedTypes()));
671 copy->SetEntryPointFromQuickCompiledCodePtrSize(RelocatedAddressOfPointer(
672 object->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size)), pointer_size);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700673 copy->SetEntryPointFromJniPtrSize(RelocatedAddressOfPointer(
674 object->GetEntryPointFromJniPtrSize(pointer_size)), pointer_size);
Alex Light53cb16b2014-06-12 11:26:29 -0700675}
676
Igor Murashkin46774762014-10-22 11:37:02 -0700677bool PatchOat::Patch(File* input_oat, off_t delta, File* output_oat, TimingLogger* timings,
678 bool output_oat_opened_from_fd, bool new_oat_out) {
Alex Light53cb16b2014-06-12 11:26:29 -0700679 CHECK(input_oat != nullptr);
680 CHECK(output_oat != nullptr);
681 CHECK_GE(input_oat->Fd(), 0);
682 CHECK_GE(output_oat->Fd(), 0);
Alex Lighteefbe392014-07-08 09:53:18 -0700683 TimingLogger::ScopedTiming t("Setup Oat File Patching", timings);
Alex Light53cb16b2014-06-12 11:26:29 -0700684
685 std::string error_msg;
Igor Murashkin46774762014-10-22 11:37:02 -0700686 std::unique_ptr<ElfFile> elf(ElfFile::Open(input_oat,
Alex Light53cb16b2014-06-12 11:26:29 -0700687 PROT_READ | PROT_WRITE, MAP_PRIVATE, &error_msg));
688 if (elf.get() == nullptr) {
689 LOG(ERROR) << "unable to open oat file " << input_oat->GetPath() << " : " << error_msg;
690 return false;
691 }
692
Igor Murashkin46774762014-10-22 11:37:02 -0700693 MaybePic is_oat_pic = IsOatPic(elf.get());
694 if (is_oat_pic >= ERROR_FIRST) {
695 // Error logged by IsOatPic
696 return false;
697 } else if (is_oat_pic == PIC) {
698 // Do not need to do ELF-file patching. Create a symlink and skip the rest.
699 // Any errors will be logged by the function call.
700 return ReplaceOatFileWithSymlink(input_oat->GetPath(),
701 output_oat->GetPath(),
702 output_oat_opened_from_fd,
703 new_oat_out);
704 } else {
705 CHECK(is_oat_pic == NOT_PIC);
706 }
707
Alex Light53cb16b2014-06-12 11:26:29 -0700708 PatchOat p(elf.release(), delta, timings);
709 t.NewTiming("Patch Oat file");
710 if (!p.PatchElf()) {
711 return false;
712 }
713
714 t.NewTiming("Writing oat file");
715 if (!p.WriteElf(output_oat)) {
716 return false;
717 }
718 return true;
719}
720
Tong Shen62d1ca32014-09-03 17:24:56 -0700721template <typename ElfFileImpl>
722bool PatchOat::PatchOatHeader(ElfFileImpl* oat_file) {
723 auto rodata_sec = oat_file->FindSectionByName(".rodata");
Alex Lighta59dd802014-07-02 16:28:08 -0700724 if (rodata_sec == nullptr) {
725 return false;
726 }
Tong Shen62d1ca32014-09-03 17:24:56 -0700727 OatHeader* oat_header = reinterpret_cast<OatHeader*>(oat_file->Begin() + rodata_sec->sh_offset);
Alex Lighta59dd802014-07-02 16:28:08 -0700728 if (!oat_header->IsValid()) {
Tong Shen62d1ca32014-09-03 17:24:56 -0700729 LOG(ERROR) << "Elf file " << oat_file->GetFile().GetPath() << " has an invalid oat header";
Alex Lighta59dd802014-07-02 16:28:08 -0700730 return false;
731 }
732 oat_header->RelocateOat(delta_);
733 return true;
734}
735
Alex Light53cb16b2014-06-12 11:26:29 -0700736bool PatchOat::PatchElf() {
Ian Rogersd4c4d952014-10-16 20:31:53 -0700737 if (oat_file_->Is64Bit())
Tong Shen62d1ca32014-09-03 17:24:56 -0700738 return PatchElf<ElfFileImpl64>(oat_file_->GetImpl64());
739 else
740 return PatchElf<ElfFileImpl32>(oat_file_->GetImpl32());
741}
742
743template <typename ElfFileImpl>
744bool PatchOat::PatchElf(ElfFileImpl* oat_file) {
Alex Lighta59dd802014-07-02 16:28:08 -0700745 TimingLogger::ScopedTiming t("Fixup Elf Text Section", timings_);
Vladimir Marko3fc99032015-05-13 19:06:30 +0100746
747 // Fix up absolute references to locations within the boot image.
David Srbecky2f6cdb02015-04-11 00:17:53 +0100748 if (!oat_file->ApplyOatPatchesTo(".text", delta_)) {
Alex Lighta59dd802014-07-02 16:28:08 -0700749 return false;
750 }
751
Vladimir Marko3fc99032015-05-13 19:06:30 +0100752 // Update the OatHeader fields referencing the boot image.
Tong Shen62d1ca32014-09-03 17:24:56 -0700753 if (!PatchOatHeader<ElfFileImpl>(oat_file)) {
Alex Lighta59dd802014-07-02 16:28:08 -0700754 return false;
755 }
756
Vladimir Marko3fc99032015-05-13 19:06:30 +0100757 bool need_boot_oat_fixup = true;
Ian Rogersd4c4d952014-10-16 20:31:53 -0700758 for (unsigned int i = 0; i < oat_file->GetProgramHeaderNum(); ++i) {
Tong Shen62d1ca32014-09-03 17:24:56 -0700759 auto hdr = oat_file->GetProgramHeader(i);
Vladimir Marko3fc99032015-05-13 19:06:30 +0100760 if (hdr->p_type == PT_LOAD && hdr->p_vaddr == 0u) {
761 need_boot_oat_fixup = false;
Ian Rogersd4c4d952014-10-16 20:31:53 -0700762 break;
Alex Light53cb16b2014-06-12 11:26:29 -0700763 }
764 }
Vladimir Marko3fc99032015-05-13 19:06:30 +0100765 if (!need_boot_oat_fixup) {
766 // This is an app oat file that can be loaded at an arbitrary address in memory.
767 // Boot image references were patched above and there's nothing else to do.
Alex Lighta59dd802014-07-02 16:28:08 -0700768 return true;
769 }
Tong Shen62d1ca32014-09-03 17:24:56 -0700770
Vladimir Marko3fc99032015-05-13 19:06:30 +0100771 // This is a boot oat file that's loaded at a particular address and we need
772 // to patch all absolute addresses, starting with ELF program headers.
773
Tong Shen62d1ca32014-09-03 17:24:56 -0700774 t.NewTiming("Fixup Elf Headers");
775 // Fixup Phdr's
776 oat_file->FixupProgramHeaders(delta_);
777
Alex Lighta59dd802014-07-02 16:28:08 -0700778 t.NewTiming("Fixup Section Headers");
Tong Shen62d1ca32014-09-03 17:24:56 -0700779 // Fixup Shdr's
780 oat_file->FixupSectionHeaders(delta_);
Alex Light53cb16b2014-06-12 11:26:29 -0700781
Alex Lighta59dd802014-07-02 16:28:08 -0700782 t.NewTiming("Fixup Dynamics");
Tong Shen62d1ca32014-09-03 17:24:56 -0700783 oat_file->FixupDynamic(delta_);
Alex Light53cb16b2014-06-12 11:26:29 -0700784
785 t.NewTiming("Fixup Elf Symbols");
786 // Fixup dynsym
Tong Shen62d1ca32014-09-03 17:24:56 -0700787 if (!oat_file->FixupSymbols(delta_, true)) {
Alex Light53cb16b2014-06-12 11:26:29 -0700788 return false;
789 }
Alex Light53cb16b2014-06-12 11:26:29 -0700790 // Fixup symtab
Tong Shen62d1ca32014-09-03 17:24:56 -0700791 if (!oat_file->FixupSymbols(delta_, false)) {
792 return false;
Alex Light53cb16b2014-06-12 11:26:29 -0700793 }
794
Yevgeny Roubane3ea8382014-08-08 16:29:38 +0700795 t.NewTiming("Fixup Debug Sections");
Tong Shen62d1ca32014-09-03 17:24:56 -0700796 if (!oat_file->FixupDebugSections(delta_)) {
Yevgeny Roubane3ea8382014-08-08 16:29:38 +0700797 return false;
798 }
799
Alex Light53cb16b2014-06-12 11:26:29 -0700800 return true;
801}
802
Alex Light53cb16b2014-06-12 11:26:29 -0700803static int orig_argc;
804static char** orig_argv;
805
806static std::string CommandLine() {
807 std::vector<std::string> command;
808 for (int i = 0; i < orig_argc; ++i) {
809 command.push_back(orig_argv[i]);
810 }
811 return Join(command, ' ');
812}
813
814static void UsageErrorV(const char* fmt, va_list ap) {
815 std::string error;
816 StringAppendV(&error, fmt, ap);
817 LOG(ERROR) << error;
818}
819
820static void UsageError(const char* fmt, ...) {
821 va_list ap;
822 va_start(ap, fmt);
823 UsageErrorV(fmt, ap);
824 va_end(ap);
825}
826
Andreas Gampe794ad762015-02-23 08:12:24 -0800827NO_RETURN static void Usage(const char *fmt, ...) {
Alex Light53cb16b2014-06-12 11:26:29 -0700828 va_list ap;
829 va_start(ap, fmt);
830 UsageErrorV(fmt, ap);
831 va_end(ap);
832
833 UsageError("Command: %s", CommandLine().c_str());
834 UsageError("Usage: patchoat [options]...");
835 UsageError("");
836 UsageError(" --instruction-set=<isa>: Specifies the instruction set the patched code is");
837 UsageError(" compiled for. Required if you use --input-oat-location");
838 UsageError("");
839 UsageError(" --input-oat-file=<file.oat>: Specifies the exact filename of the oat file to be");
840 UsageError(" patched.");
841 UsageError("");
842 UsageError(" --input-oat-fd=<file-descriptor>: Specifies the file-descriptor of the oat file");
843 UsageError(" to be patched.");
844 UsageError("");
845 UsageError(" --input-oat-location=<file.oat>: Specifies the 'location' to read the patched");
846 UsageError(" oat file from. If used one must also supply the --instruction-set");
847 UsageError("");
848 UsageError(" --input-image-location=<file.art>: Specifies the 'location' of the image file to");
849 UsageError(" be patched. If --instruction-set is not given it will use the instruction set");
850 UsageError(" extracted from the --input-oat-file.");
851 UsageError("");
852 UsageError(" --output-oat-file=<file.oat>: Specifies the exact file to write the patched oat");
853 UsageError(" file to.");
854 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700855 UsageError(" --output-oat-fd=<file-descriptor>: Specifies the file-descriptor to write the");
856 UsageError(" the patched oat file to.");
857 UsageError("");
858 UsageError(" --output-image-file=<file.art>: Specifies the exact file to write the patched");
859 UsageError(" image file to.");
860 UsageError("");
861 UsageError(" --output-image-fd=<file-descriptor>: Specifies the file-descriptor to write the");
862 UsageError(" the patched image file to.");
863 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700864 UsageError(" --orig-base-offset=<original-base-offset>: Specify the base offset the input file");
865 UsageError(" was compiled with. This is needed if one is specifying a --base-offset");
866 UsageError("");
867 UsageError(" --base-offset=<new-base-offset>: Specify the base offset we will repatch the");
868 UsageError(" given files to use. This requires that --orig-base-offset is also given.");
869 UsageError("");
870 UsageError(" --base-offset-delta=<delta>: Specify the amount to change the old base-offset by.");
871 UsageError(" This value may be negative.");
872 UsageError("");
873 UsageError(" --patched-image-file=<file.art>: Use the same patch delta as was used to patch");
874 UsageError(" the given image file.");
875 UsageError("");
876 UsageError(" --patched-image-location=<file.art>: Use the same patch delta as was used to");
877 UsageError(" patch the given image location. If used one must also specify the");
Alex Lighta59dd802014-07-02 16:28:08 -0700878 UsageError(" --instruction-set flag. It will search for this image in the same way that");
879 UsageError(" is done when loading one.");
Alex Light53cb16b2014-06-12 11:26:29 -0700880 UsageError("");
Alex Lightcf4bf382014-07-24 11:29:14 -0700881 UsageError(" --lock-output: Obtain a flock on output oat file before starting.");
882 UsageError("");
883 UsageError(" --no-lock-output: Do not attempt to obtain a flock on output oat file.");
884 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700885 UsageError(" --dump-timings: dump out patch timing information");
886 UsageError("");
887 UsageError(" --no-dump-timings: do not dump out patch timing information");
888 UsageError("");
889
890 exit(EXIT_FAILURE);
891}
892
Alex Lighteefbe392014-07-08 09:53:18 -0700893static bool ReadBaseDelta(const char* name, off_t* delta, std::string* error_msg) {
Alex Light53cb16b2014-06-12 11:26:29 -0700894 CHECK(name != nullptr);
895 CHECK(delta != nullptr);
896 std::unique_ptr<File> file;
897 if (OS::FileExists(name)) {
898 file.reset(OS::OpenFileForReading(name));
899 if (file.get() == nullptr) {
Alex Lighteefbe392014-07-08 09:53:18 -0700900 *error_msg = "Failed to open file %s for reading";
Alex Light53cb16b2014-06-12 11:26:29 -0700901 return false;
902 }
903 } else {
Alex Lighteefbe392014-07-08 09:53:18 -0700904 *error_msg = "File %s does not exist";
Alex Light53cb16b2014-06-12 11:26:29 -0700905 return false;
906 }
907 CHECK(file.get() != nullptr);
908 ImageHeader hdr;
909 if (sizeof(hdr) != file->Read(reinterpret_cast<char*>(&hdr), sizeof(hdr), 0)) {
Alex Lighteefbe392014-07-08 09:53:18 -0700910 *error_msg = "Failed to read file %s";
Alex Light53cb16b2014-06-12 11:26:29 -0700911 return false;
912 }
913 if (!hdr.IsValid()) {
Alex Lighteefbe392014-07-08 09:53:18 -0700914 *error_msg = "%s does not contain a valid image header.";
Alex Light53cb16b2014-06-12 11:26:29 -0700915 return false;
916 }
917 *delta = hdr.GetPatchDelta();
918 return true;
919}
920
921static File* CreateOrOpen(const char* name, bool* created) {
922 if (OS::FileExists(name)) {
923 *created = false;
924 return OS::OpenFileReadWrite(name);
925 } else {
926 *created = true;
Alex Lightcf4bf382014-07-24 11:29:14 -0700927 std::unique_ptr<File> f(OS::CreateEmptyFile(name));
928 if (f.get() != nullptr) {
929 if (fchmod(f->Fd(), 0644) != 0) {
930 PLOG(ERROR) << "Unable to make " << name << " world readable";
Brian Carlstrom8c52a3f2014-09-30 16:18:01 -0700931 TEMP_FAILURE_RETRY(unlink(name));
Alex Lightcf4bf382014-07-24 11:29:14 -0700932 return nullptr;
933 }
934 }
935 return f.release();
Alex Light53cb16b2014-06-12 11:26:29 -0700936 }
937}
938
Andreas Gampe4303ba92014-11-06 01:00:46 -0800939// Either try to close the file (close=true), or erase it.
940static bool FinishFile(File* file, bool close) {
941 if (close) {
942 if (file->FlushCloseOrErase() != 0) {
943 PLOG(ERROR) << "Failed to flush and close file.";
944 return false;
945 }
946 return true;
947 } else {
948 file->Erase();
949 return false;
950 }
951}
952
Alex Lighteefbe392014-07-08 09:53:18 -0700953static int patchoat(int argc, char **argv) {
Alex Light53cb16b2014-06-12 11:26:29 -0700954 InitLogging(argv);
Mathieu Chartier6e88ef62014-10-14 15:01:24 -0700955 MemMap::Init();
Alex Light53cb16b2014-06-12 11:26:29 -0700956 const bool debug = kIsDebugBuild;
957 orig_argc = argc;
958 orig_argv = argv;
959 TimingLogger timings("patcher", false, false);
960
961 InitLogging(argv);
962
963 // Skip over the command name.
964 argv++;
965 argc--;
966
967 if (argc == 0) {
968 Usage("No arguments specified");
969 }
970
971 timings.StartTiming("Patchoat");
972
973 // cmd line args
974 bool isa_set = false;
975 InstructionSet isa = kNone;
976 std::string input_oat_filename;
977 std::string input_oat_location;
978 int input_oat_fd = -1;
979 bool have_input_oat = false;
980 std::string input_image_location;
981 std::string output_oat_filename;
Alex Light53cb16b2014-06-12 11:26:29 -0700982 int output_oat_fd = -1;
983 bool have_output_oat = false;
984 std::string output_image_filename;
Alex Light53cb16b2014-06-12 11:26:29 -0700985 int output_image_fd = -1;
986 bool have_output_image = false;
987 uintptr_t base_offset = 0;
988 bool base_offset_set = false;
989 uintptr_t orig_base_offset = 0;
990 bool orig_base_offset_set = false;
991 off_t base_delta = 0;
992 bool base_delta_set = false;
993 std::string patched_image_filename;
994 std::string patched_image_location;
995 bool dump_timings = kIsDebugBuild;
Alex Lightcf4bf382014-07-24 11:29:14 -0700996 bool lock_output = true;
Alex Light53cb16b2014-06-12 11:26:29 -0700997
Ian Rogersd4c4d952014-10-16 20:31:53 -0700998 for (int i = 0; i < argc; ++i) {
Alex Light53cb16b2014-06-12 11:26:29 -0700999 const StringPiece option(argv[i]);
1000 const bool log_options = false;
1001 if (log_options) {
1002 LOG(INFO) << "patchoat: option[" << i << "]=" << argv[i];
1003 }
Alex Light53cb16b2014-06-12 11:26:29 -07001004 if (option.starts_with("--instruction-set=")) {
1005 isa_set = true;
1006 const char* isa_str = option.substr(strlen("--instruction-set=")).data();
Andreas Gampe20c89302014-08-19 17:28:06 -07001007 isa = GetInstructionSetFromString(isa_str);
1008 if (isa == kNone) {
1009 Usage("Unknown or invalid instruction set %s", isa_str);
Alex Light53cb16b2014-06-12 11:26:29 -07001010 }
1011 } else if (option.starts_with("--input-oat-location=")) {
1012 if (have_input_oat) {
1013 Usage("Only one of --input-oat-file, --input-oat-location and --input-oat-fd may be used.");
1014 }
1015 have_input_oat = true;
1016 input_oat_location = option.substr(strlen("--input-oat-location=")).data();
1017 } else if (option.starts_with("--input-oat-file=")) {
1018 if (have_input_oat) {
1019 Usage("Only one of --input-oat-file, --input-oat-location and --input-oat-fd may be used.");
1020 }
1021 have_input_oat = true;
1022 input_oat_filename = option.substr(strlen("--input-oat-file=")).data();
1023 } else if (option.starts_with("--input-oat-fd=")) {
1024 if (have_input_oat) {
1025 Usage("Only one of --input-oat-file, --input-oat-location and --input-oat-fd may be used.");
1026 }
1027 have_input_oat = true;
1028 const char* oat_fd_str = option.substr(strlen("--input-oat-fd=")).data();
1029 if (!ParseInt(oat_fd_str, &input_oat_fd)) {
1030 Usage("Failed to parse --input-oat-fd argument '%s' as an integer", oat_fd_str);
1031 }
1032 if (input_oat_fd < 0) {
1033 Usage("--input-oat-fd pass a negative value %d", input_oat_fd);
1034 }
1035 } else if (option.starts_with("--input-image-location=")) {
1036 input_image_location = option.substr(strlen("--input-image-location=")).data();
Alex Light53cb16b2014-06-12 11:26:29 -07001037 } else if (option.starts_with("--output-oat-file=")) {
1038 if (have_output_oat) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001039 Usage("Only one of --output-oat-file, and --output-oat-fd may be used.");
Alex Light53cb16b2014-06-12 11:26:29 -07001040 }
1041 have_output_oat = true;
1042 output_oat_filename = option.substr(strlen("--output-oat-file=")).data();
1043 } else if (option.starts_with("--output-oat-fd=")) {
1044 if (have_output_oat) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001045 Usage("Only one of --output-oat-file, --output-oat-fd may be used.");
Alex Light53cb16b2014-06-12 11:26:29 -07001046 }
1047 have_output_oat = true;
1048 const char* oat_fd_str = option.substr(strlen("--output-oat-fd=")).data();
1049 if (!ParseInt(oat_fd_str, &output_oat_fd)) {
1050 Usage("Failed to parse --output-oat-fd argument '%s' as an integer", oat_fd_str);
1051 }
1052 if (output_oat_fd < 0) {
1053 Usage("--output-oat-fd pass a negative value %d", output_oat_fd);
1054 }
Alex Light53cb16b2014-06-12 11:26:29 -07001055 } else if (option.starts_with("--output-image-file=")) {
1056 if (have_output_image) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001057 Usage("Only one of --output-image-file, and --output-image-fd may be used.");
Alex Light53cb16b2014-06-12 11:26:29 -07001058 }
1059 have_output_image = true;
1060 output_image_filename = option.substr(strlen("--output-image-file=")).data();
1061 } else if (option.starts_with("--output-image-fd=")) {
1062 if (have_output_image) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001063 Usage("Only one of --output-image-file, and --output-image-fd may be used.");
Alex Light53cb16b2014-06-12 11:26:29 -07001064 }
1065 have_output_image = true;
1066 const char* image_fd_str = option.substr(strlen("--output-image-fd=")).data();
1067 if (!ParseInt(image_fd_str, &output_image_fd)) {
1068 Usage("Failed to parse --output-image-fd argument '%s' as an integer", image_fd_str);
1069 }
1070 if (output_image_fd < 0) {
1071 Usage("--output-image-fd pass a negative value %d", output_image_fd);
1072 }
1073 } else if (option.starts_with("--orig-base-offset=")) {
1074 const char* orig_base_offset_str = option.substr(strlen("--orig-base-offset=")).data();
1075 orig_base_offset_set = true;
1076 if (!ParseUint(orig_base_offset_str, &orig_base_offset)) {
1077 Usage("Failed to parse --orig-base-offset argument '%s' as an uintptr_t",
1078 orig_base_offset_str);
1079 }
1080 } else if (option.starts_with("--base-offset=")) {
1081 const char* base_offset_str = option.substr(strlen("--base-offset=")).data();
1082 base_offset_set = true;
1083 if (!ParseUint(base_offset_str, &base_offset)) {
1084 Usage("Failed to parse --base-offset argument '%s' as an uintptr_t", base_offset_str);
1085 }
1086 } else if (option.starts_with("--base-offset-delta=")) {
1087 const char* base_delta_str = option.substr(strlen("--base-offset-delta=")).data();
1088 base_delta_set = true;
1089 if (!ParseInt(base_delta_str, &base_delta)) {
1090 Usage("Failed to parse --base-offset-delta argument '%s' as an off_t", base_delta_str);
1091 }
1092 } else if (option.starts_with("--patched-image-location=")) {
1093 patched_image_location = option.substr(strlen("--patched-image-location=")).data();
1094 } else if (option.starts_with("--patched-image-file=")) {
1095 patched_image_filename = option.substr(strlen("--patched-image-file=")).data();
Alex Lightcf4bf382014-07-24 11:29:14 -07001096 } else if (option == "--lock-output") {
1097 lock_output = true;
1098 } else if (option == "--no-lock-output") {
1099 lock_output = false;
Alex Light53cb16b2014-06-12 11:26:29 -07001100 } else if (option == "--dump-timings") {
1101 dump_timings = true;
1102 } else if (option == "--no-dump-timings") {
1103 dump_timings = false;
1104 } else {
1105 Usage("Unknown argument %s", option.data());
1106 }
1107 }
1108
1109 {
1110 // Only 1 of these may be set.
1111 uint32_t cnt = 0;
1112 cnt += (base_delta_set) ? 1 : 0;
1113 cnt += (base_offset_set && orig_base_offset_set) ? 1 : 0;
1114 cnt += (!patched_image_filename.empty()) ? 1 : 0;
1115 cnt += (!patched_image_location.empty()) ? 1 : 0;
1116 if (cnt > 1) {
1117 Usage("Only one of --base-offset/--orig-base-offset, --base-offset-delta, "
1118 "--patched-image-filename or --patched-image-location may be used.");
1119 } else if (cnt == 0) {
1120 Usage("Must specify --base-offset-delta, --base-offset and --orig-base-offset, "
1121 "--patched-image-location or --patched-image-file");
1122 }
1123 }
1124
1125 if (have_input_oat != have_output_oat) {
1126 Usage("Either both input and output oat must be supplied or niether must be.");
1127 }
1128
1129 if ((!input_image_location.empty()) != have_output_image) {
1130 Usage("Either both input and output image must be supplied or niether must be.");
1131 }
1132
1133 // We know we have both the input and output so rename for clarity.
1134 bool have_image_files = have_output_image;
1135 bool have_oat_files = have_output_oat;
1136
1137 if (!have_oat_files && !have_image_files) {
1138 Usage("Must be patching either an oat or an image file or both.");
1139 }
1140
1141 if (!have_oat_files && !isa_set) {
1142 Usage("Must include ISA if patching an image file without an oat file.");
1143 }
1144
1145 if (!input_oat_location.empty()) {
1146 if (!isa_set) {
1147 Usage("specifying a location requires specifying an instruction set");
1148 }
Alex Lightcf4bf382014-07-24 11:29:14 -07001149 if (!LocationToFilename(input_oat_location, isa, &input_oat_filename)) {
1150 Usage("Unable to find filename for input oat location %s", input_oat_location.c_str());
1151 }
Alex Light53cb16b2014-06-12 11:26:29 -07001152 if (debug) {
1153 LOG(INFO) << "Using input-oat-file " << input_oat_filename;
1154 }
1155 }
Alex Light53cb16b2014-06-12 11:26:29 -07001156 if (!patched_image_location.empty()) {
1157 if (!isa_set) {
1158 Usage("specifying a location requires specifying an instruction set");
1159 }
Alex Lighta59dd802014-07-02 16:28:08 -07001160 std::string system_filename;
1161 bool has_system = false;
1162 std::string cache_filename;
1163 bool has_cache = false;
1164 bool has_android_data_unused = false;
Andreas Gampe3c13a792014-09-18 20:56:04 -07001165 bool is_global_cache = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001166 if (!gc::space::ImageSpace::FindImageFilename(patched_image_location.c_str(), isa,
1167 &system_filename, &has_system, &cache_filename,
Andreas Gampe3c13a792014-09-18 20:56:04 -07001168 &has_android_data_unused, &has_cache,
1169 &is_global_cache)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001170 Usage("Unable to determine image file for location %s", patched_image_location.c_str());
1171 }
1172 if (has_cache) {
1173 patched_image_filename = cache_filename;
1174 } else if (has_system) {
1175 LOG(WARNING) << "Only image file found was in /system for image location "
1176 << patched_image_location;
1177 patched_image_filename = system_filename;
1178 } else {
1179 Usage("Unable to determine image file for location %s", patched_image_location.c_str());
1180 }
Alex Light53cb16b2014-06-12 11:26:29 -07001181 if (debug) {
1182 LOG(INFO) << "Using patched-image-file " << patched_image_filename;
1183 }
1184 }
1185
1186 if (!base_delta_set) {
1187 if (orig_base_offset_set && base_offset_set) {
1188 base_delta_set = true;
1189 base_delta = base_offset - orig_base_offset;
1190 } else if (!patched_image_filename.empty()) {
1191 base_delta_set = true;
1192 std::string error_msg;
Alex Lighteefbe392014-07-08 09:53:18 -07001193 if (!ReadBaseDelta(patched_image_filename.c_str(), &base_delta, &error_msg)) {
Alex Light53cb16b2014-06-12 11:26:29 -07001194 Usage(error_msg.c_str(), patched_image_filename.c_str());
1195 }
1196 } else {
1197 if (base_offset_set) {
1198 Usage("Unable to determine original base offset.");
1199 } else {
1200 Usage("Must supply a desired new offset or delta.");
1201 }
1202 }
1203 }
1204
1205 if (!IsAligned<kPageSize>(base_delta)) {
1206 Usage("Base offset/delta must be alligned to a pagesize (0x%08x) boundary.", kPageSize);
1207 }
1208
1209 // Do we need to cleanup output files if we fail?
1210 bool new_image_out = false;
1211 bool new_oat_out = false;
1212
1213 std::unique_ptr<File> input_oat;
1214 std::unique_ptr<File> output_oat;
1215 std::unique_ptr<File> output_image;
1216
1217 if (have_image_files) {
1218 CHECK(!input_image_location.empty());
1219
1220 if (output_image_fd != -1) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001221 if (output_image_filename.empty()) {
1222 output_image_filename = "output-image-file";
1223 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001224 output_image.reset(new File(output_image_fd, output_image_filename, true));
Alex Light53cb16b2014-06-12 11:26:29 -07001225 } else {
1226 CHECK(!output_image_filename.empty());
1227 output_image.reset(CreateOrOpen(output_image_filename.c_str(), &new_image_out));
1228 }
1229 } else {
1230 CHECK(output_image_filename.empty() && output_image_fd == -1 && input_image_location.empty());
1231 }
1232
1233 if (have_oat_files) {
1234 if (input_oat_fd != -1) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001235 if (input_oat_filename.empty()) {
1236 input_oat_filename = "input-oat-file";
1237 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001238 input_oat.reset(new File(input_oat_fd, input_oat_filename, false));
Julien Delayena473f512015-03-05 16:37:52 +01001239 if (input_oat_fd == output_oat_fd) {
1240 input_oat.get()->DisableAutoClose();
1241 }
Igor Murashkin46774762014-10-22 11:37:02 -07001242 if (input_oat == nullptr) {
1243 // Unlikely, but ensure exhaustive logging in non-0 exit code case
1244 LOG(ERROR) << "Failed to open input oat file by its FD" << input_oat_fd;
1245 }
Alex Light53cb16b2014-06-12 11:26:29 -07001246 } else {
1247 CHECK(!input_oat_filename.empty());
1248 input_oat.reset(OS::OpenFileForReading(input_oat_filename.c_str()));
Igor Murashkin46774762014-10-22 11:37:02 -07001249 if (input_oat == nullptr) {
1250 int err = errno;
1251 LOG(ERROR) << "Failed to open input oat file " << input_oat_filename
1252 << ": " << strerror(err) << "(" << err << ")";
Andreas Gampe1c83cbc2014-07-22 18:52:29 -07001253 }
Alex Light53cb16b2014-06-12 11:26:29 -07001254 }
1255
1256 if (output_oat_fd != -1) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001257 if (output_oat_filename.empty()) {
1258 output_oat_filename = "output-oat-file";
Alex Lighta59dd802014-07-02 16:28:08 -07001259 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001260 output_oat.reset(new File(output_oat_fd, output_oat_filename, true));
Igor Murashkin46774762014-10-22 11:37:02 -07001261 if (output_oat == nullptr) {
1262 // Unlikely, but ensure exhaustive logging in non-0 exit code case
1263 LOG(ERROR) << "Failed to open output oat file by its FD" << output_oat_fd;
1264 }
Alex Light53cb16b2014-06-12 11:26:29 -07001265 } else {
1266 CHECK(!output_oat_filename.empty());
1267 output_oat.reset(CreateOrOpen(output_oat_filename.c_str(), &new_oat_out));
Igor Murashkin46774762014-10-22 11:37:02 -07001268 if (output_oat == nullptr) {
1269 int err = errno;
1270 LOG(ERROR) << "Failed to open output oat file " << output_oat_filename
1271 << ": " << strerror(err) << "(" << err << ")";
1272 }
Alex Light53cb16b2014-06-12 11:26:29 -07001273 }
1274 }
1275
Igor Murashkin46774762014-10-22 11:37:02 -07001276 // TODO: get rid of this.
Alex Light53cb16b2014-06-12 11:26:29 -07001277 auto cleanup = [&output_image_filename, &output_oat_filename,
1278 &new_oat_out, &new_image_out, &timings, &dump_timings](bool success) {
1279 timings.EndTiming();
1280 if (!success) {
1281 if (new_oat_out) {
1282 CHECK(!output_oat_filename.empty());
Brian Carlstrom8c52a3f2014-09-30 16:18:01 -07001283 TEMP_FAILURE_RETRY(unlink(output_oat_filename.c_str()));
Alex Light53cb16b2014-06-12 11:26:29 -07001284 }
1285 if (new_image_out) {
1286 CHECK(!output_image_filename.empty());
Brian Carlstrom8c52a3f2014-09-30 16:18:01 -07001287 TEMP_FAILURE_RETRY(unlink(output_image_filename.c_str()));
Alex Light53cb16b2014-06-12 11:26:29 -07001288 }
1289 }
1290 if (dump_timings) {
1291 LOG(INFO) << Dumpable<TimingLogger>(timings);
1292 }
Igor Murashkin46774762014-10-22 11:37:02 -07001293
1294 if (kIsDebugBuild) {
1295 LOG(INFO) << "Cleaning up.. success? " << success;
1296 }
Alex Light53cb16b2014-06-12 11:26:29 -07001297 };
1298
Igor Murashkin46774762014-10-22 11:37:02 -07001299 if (have_oat_files && (input_oat.get() == nullptr || output_oat.get() == nullptr)) {
1300 LOG(ERROR) << "Failed to open input/output oat files";
1301 cleanup(false);
1302 return EXIT_FAILURE;
1303 } else if (have_image_files && output_image.get() == nullptr) {
1304 LOG(ERROR) << "Failed to open output image file";
Alex Lightcf4bf382014-07-24 11:29:14 -07001305 cleanup(false);
1306 return EXIT_FAILURE;
1307 }
1308
Igor Murashkin46774762014-10-22 11:37:02 -07001309 if (debug) {
1310 LOG(INFO) << "moving offset by " << base_delta
1311 << " (0x" << std::hex << base_delta << ") bytes or "
1312 << std::dec << (base_delta/kPageSize) << " pages.";
1313 }
1314
1315 // TODO: is it going to be promatic to unlink a file that was flock-ed?
Alex Lightcf4bf382014-07-24 11:29:14 -07001316 ScopedFlock output_oat_lock;
1317 if (lock_output) {
1318 std::string error_msg;
1319 if (have_oat_files && !output_oat_lock.Init(output_oat.get(), &error_msg)) {
1320 LOG(ERROR) << "Unable to lock output oat " << output_image->GetPath() << ": " << error_msg;
1321 cleanup(false);
1322 return EXIT_FAILURE;
1323 }
1324 }
1325
Alex Light53cb16b2014-06-12 11:26:29 -07001326 bool ret;
1327 if (have_image_files && have_oat_files) {
1328 TimingLogger::ScopedTiming pt("patch image and oat", &timings);
1329 ret = PatchOat::Patch(input_oat.get(), input_image_location, base_delta,
Igor Murashkin46774762014-10-22 11:37:02 -07001330 output_oat.get(), output_image.get(), isa, &timings,
1331 output_oat_fd >= 0, // was it opened from FD?
1332 new_oat_out);
Andreas Gampe4303ba92014-11-06 01:00:46 -08001333 // The order here doesn't matter. If the first one is successfully saved and the second one
1334 // erased, ImageSpace will still detect a problem and not use the files.
1335 ret = ret && FinishFile(output_image.get(), ret);
1336 ret = ret && FinishFile(output_oat.get(), ret);
Alex Light53cb16b2014-06-12 11:26:29 -07001337 } else if (have_oat_files) {
1338 TimingLogger::ScopedTiming pt("patch oat", &timings);
Igor Murashkin46774762014-10-22 11:37:02 -07001339 ret = PatchOat::Patch(input_oat.get(), base_delta, output_oat.get(), &timings,
1340 output_oat_fd >= 0, // was it opened from FD?
1341 new_oat_out);
Andreas Gampe4303ba92014-11-06 01:00:46 -08001342 ret = ret && FinishFile(output_oat.get(), ret);
Igor Murashkin46774762014-10-22 11:37:02 -07001343 } else if (have_image_files) {
Alex Light53cb16b2014-06-12 11:26:29 -07001344 TimingLogger::ScopedTiming pt("patch image", &timings);
Alex Lighteefbe392014-07-08 09:53:18 -07001345 ret = PatchOat::Patch(input_image_location, base_delta, output_image.get(), isa, &timings);
Andreas Gampe4303ba92014-11-06 01:00:46 -08001346 ret = ret && FinishFile(output_image.get(), ret);
Igor Murashkin46774762014-10-22 11:37:02 -07001347 } else {
1348 CHECK(false);
1349 ret = true;
1350 }
1351
1352 if (kIsDebugBuild) {
1353 LOG(INFO) << "Exiting with return ... " << ret;
Alex Light53cb16b2014-06-12 11:26:29 -07001354 }
1355 cleanup(ret);
Alex Light53cb16b2014-06-12 11:26:29 -07001356 return (ret) ? EXIT_SUCCESS : EXIT_FAILURE;
1357}
1358
1359} // namespace art
1360
1361int main(int argc, char **argv) {
1362 return art::patchoat(argc, argv);
1363}