blob: a71197a6ce594ec99806e3aac2f505d430655f27 [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 Light0eb76d22015-08-11 18:03:47 -070095static const OatHeader* GetOatHeader(const ElfFile* elf_file) {
96 uint64_t off = 0;
97 if (!elf_file->GetSectionOffsetAndSize(".rodata", &off, nullptr)) {
98 return nullptr;
99 }
100
101 OatHeader* oat_header = reinterpret_cast<OatHeader*>(elf_file->Begin() + off);
102 return oat_header;
103}
104
105// This function takes an elf file and reads the current patch delta value
106// encoded in its oat header value
107static bool ReadOatPatchDelta(const ElfFile* elf_file, off_t* delta, std::string* error_msg) {
108 const OatHeader* oat_header = GetOatHeader(elf_file);
109 if (oat_header == nullptr) {
110 *error_msg = "Unable to get oat header from elf file.";
111 return false;
112 }
113 if (!oat_header->IsValid()) {
114 *error_msg = "Elf file has an invalid oat header";
115 return false;
116 }
117 *delta = oat_header->GetImagePatchDelta();
118 return true;
119}
120
Alex Light53cb16b2014-06-12 11:26:29 -0700121bool PatchOat::Patch(const std::string& image_location, off_t delta,
122 File* output_image, InstructionSet isa,
Alex Lighteefbe392014-07-08 09:53:18 -0700123 TimingLogger* timings) {
Alex Light53cb16b2014-06-12 11:26:29 -0700124 CHECK(Runtime::Current() == nullptr);
125 CHECK(output_image != nullptr);
126 CHECK_GE(output_image->Fd(), 0);
127 CHECK(!image_location.empty()) << "image file must have a filename.";
128 CHECK_NE(isa, kNone);
129
Alex Lighteefbe392014-07-08 09:53:18 -0700130 TimingLogger::ScopedTiming t("Runtime Setup", timings);
Alex Light53cb16b2014-06-12 11:26:29 -0700131 const char *isa_name = GetInstructionSetString(isa);
Alex Lightcf4bf382014-07-24 11:29:14 -0700132 std::string image_filename;
133 if (!LocationToFilename(image_location, isa, &image_filename)) {
134 LOG(ERROR) << "Unable to find image at location " << image_location;
135 return false;
136 }
Alex Light53cb16b2014-06-12 11:26:29 -0700137 std::unique_ptr<File> input_image(OS::OpenFileForReading(image_filename.c_str()));
138 if (input_image.get() == nullptr) {
Alex Lightcf4bf382014-07-24 11:29:14 -0700139 LOG(ERROR) << "unable to open input image file at " << image_filename
140 << " for location " << image_location;
Alex Light53cb16b2014-06-12 11:26:29 -0700141 return false;
142 }
Igor Murashkin46774762014-10-22 11:37:02 -0700143
Alex Light53cb16b2014-06-12 11:26:29 -0700144 int64_t image_len = input_image->GetLength();
145 if (image_len < 0) {
146 LOG(ERROR) << "Error while getting image length";
147 return false;
148 }
149 ImageHeader image_header;
150 if (sizeof(image_header) != input_image->Read(reinterpret_cast<char*>(&image_header),
Mathieu Chartiere401d142015-04-22 13:56:20 -0700151 sizeof(image_header), 0)) {
Alex Light53cb16b2014-06-12 11:26:29 -0700152 LOG(ERROR) << "Unable to read image header from image file " << input_image->GetPath();
153 return false;
154 }
155
Igor Murashkin46774762014-10-22 11:37:02 -0700156 /*bool is_image_pic = */IsImagePic(image_header, input_image->GetPath());
157 // Nothing special to do right now since the image always needs to get patched.
158 // Perhaps in some far-off future we may have images with relative addresses that are true-PIC.
159
Alex Light53cb16b2014-06-12 11:26:29 -0700160 // Set up the runtime
Ian Rogerse63db272014-07-15 15:36:11 -0700161 RuntimeOptions options;
Alex Light53cb16b2014-06-12 11:26:29 -0700162 NoopCompilerCallbacks callbacks;
163 options.push_back(std::make_pair("compilercallbacks", &callbacks));
164 std::string img = "-Ximage:" + image_location;
165 options.push_back(std::make_pair(img.c_str(), nullptr));
166 options.push_back(std::make_pair("imageinstructionset", reinterpret_cast<const void*>(isa_name)));
Calin Juravle01aaf6e2015-06-19 22:05:39 +0100167 options.push_back(std::make_pair("-Xno-sig-chain", nullptr));
Alex Light53cb16b2014-06-12 11:26:29 -0700168 if (!Runtime::Create(options, false)) {
169 LOG(ERROR) << "Unable to initialize runtime";
170 return false;
171 }
172 // Runtime::Create acquired the mutator_lock_ that is normally given away when we Runtime::Start,
173 // give it away now and then switch to a more manageable ScopedObjectAccess.
174 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
175 ScopedObjectAccess soa(Thread::Current());
176
177 t.NewTiming("Image and oat Patching setup");
178 // Create the map where we will write the image patches to.
Alex Lighteefbe392014-07-08 09:53:18 -0700179 std::string error_msg;
Alex Light53cb16b2014-06-12 11:26:29 -0700180 std::unique_ptr<MemMap> image(MemMap::MapFile(image_len, PROT_READ | PROT_WRITE, MAP_PRIVATE,
181 input_image->Fd(), 0,
182 input_image->GetPath().c_str(),
183 &error_msg));
184 if (image.get() == nullptr) {
185 LOG(ERROR) << "unable to map image file " << input_image->GetPath() << " : " << error_msg;
186 return false;
187 }
188 gc::space::ImageSpace* ispc = Runtime::Current()->GetHeap()->GetImageSpace();
189
Mathieu Chartier2d721012014-11-10 11:08:06 -0800190 PatchOat p(isa, image.release(), ispc->GetLiveBitmap(), ispc->GetMemMap(),
Alex Light53cb16b2014-06-12 11:26:29 -0700191 delta, timings);
192 t.NewTiming("Patching files");
193 if (!p.PatchImage()) {
Alex Lighta59dd802014-07-02 16:28:08 -0700194 LOG(ERROR) << "Failed to patch image file " << input_image->GetPath();
Alex Light53cb16b2014-06-12 11:26:29 -0700195 return false;
196 }
197
198 t.NewTiming("Writing files");
199 if (!p.WriteImage(output_image)) {
200 return false;
201 }
202 return true;
203}
204
Igor Murashkin46774762014-10-22 11:37:02 -0700205bool PatchOat::Patch(File* input_oat, const std::string& image_location, off_t delta,
Alex Light53cb16b2014-06-12 11:26:29 -0700206 File* output_oat, File* output_image, InstructionSet isa,
Igor Murashkin46774762014-10-22 11:37:02 -0700207 TimingLogger* timings,
208 bool output_oat_opened_from_fd,
209 bool new_oat_out) {
Alex Light53cb16b2014-06-12 11:26:29 -0700210 CHECK(Runtime::Current() == nullptr);
211 CHECK(output_image != nullptr);
212 CHECK_GE(output_image->Fd(), 0);
213 CHECK(input_oat != nullptr);
214 CHECK(output_oat != nullptr);
215 CHECK_GE(input_oat->Fd(), 0);
216 CHECK_GE(output_oat->Fd(), 0);
217 CHECK(!image_location.empty()) << "image file must have a filename.";
218
Alex Lighteefbe392014-07-08 09:53:18 -0700219 TimingLogger::ScopedTiming t("Runtime Setup", timings);
Alex Light53cb16b2014-06-12 11:26:29 -0700220
221 if (isa == kNone) {
222 Elf32_Ehdr elf_hdr;
223 if (sizeof(elf_hdr) != input_oat->Read(reinterpret_cast<char*>(&elf_hdr), sizeof(elf_hdr), 0)) {
224 LOG(ERROR) << "unable to read elf header";
225 return false;
226 }
Andreas Gampe6f611412015-01-21 22:25:24 -0800227 isa = GetInstructionSetFromELF(elf_hdr.e_machine, elf_hdr.e_flags);
Alex Light53cb16b2014-06-12 11:26:29 -0700228 }
229 const char* isa_name = GetInstructionSetString(isa);
Alex Lightcf4bf382014-07-24 11:29:14 -0700230 std::string image_filename;
231 if (!LocationToFilename(image_location, isa, &image_filename)) {
232 LOG(ERROR) << "Unable to find image at location " << image_location;
233 return false;
234 }
Alex Light53cb16b2014-06-12 11:26:29 -0700235 std::unique_ptr<File> input_image(OS::OpenFileForReading(image_filename.c_str()));
236 if (input_image.get() == nullptr) {
Alex Lightcf4bf382014-07-24 11:29:14 -0700237 LOG(ERROR) << "unable to open input image file at " << image_filename
238 << " for location " << image_location;
Alex Light53cb16b2014-06-12 11:26:29 -0700239 return false;
240 }
241 int64_t image_len = input_image->GetLength();
242 if (image_len < 0) {
243 LOG(ERROR) << "Error while getting image length";
244 return false;
245 }
246 ImageHeader image_header;
247 if (sizeof(image_header) != input_image->Read(reinterpret_cast<char*>(&image_header),
248 sizeof(image_header), 0)) {
249 LOG(ERROR) << "Unable to read image header from image file " << input_image->GetPath();
250 }
251
Igor Murashkin46774762014-10-22 11:37:02 -0700252 /*bool is_image_pic = */IsImagePic(image_header, input_image->GetPath());
253 // Nothing special to do right now since the image always needs to get patched.
254 // Perhaps in some far-off future we may have images with relative addresses that are true-PIC.
255
Alex Light53cb16b2014-06-12 11:26:29 -0700256 // Set up the runtime
Ian Rogerse63db272014-07-15 15:36:11 -0700257 RuntimeOptions options;
Alex Light53cb16b2014-06-12 11:26:29 -0700258 NoopCompilerCallbacks callbacks;
259 options.push_back(std::make_pair("compilercallbacks", &callbacks));
260 std::string img = "-Ximage:" + image_location;
261 options.push_back(std::make_pair(img.c_str(), nullptr));
262 options.push_back(std::make_pair("imageinstructionset", reinterpret_cast<const void*>(isa_name)));
Calin Juravle01aaf6e2015-06-19 22:05:39 +0100263 options.push_back(std::make_pair("-Xno-sig-chain", nullptr));
Alex Light53cb16b2014-06-12 11:26:29 -0700264 if (!Runtime::Create(options, false)) {
265 LOG(ERROR) << "Unable to initialize runtime";
266 return false;
267 }
268 // Runtime::Create acquired the mutator_lock_ that is normally given away when we Runtime::Start,
269 // give it away now and then switch to a more manageable ScopedObjectAccess.
270 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
271 ScopedObjectAccess soa(Thread::Current());
272
273 t.NewTiming("Image and oat Patching setup");
274 // Create the map where we will write the image patches to.
Alex Lighteefbe392014-07-08 09:53:18 -0700275 std::string error_msg;
Alex Light53cb16b2014-06-12 11:26:29 -0700276 std::unique_ptr<MemMap> image(MemMap::MapFile(image_len, PROT_READ | PROT_WRITE, MAP_PRIVATE,
277 input_image->Fd(), 0,
278 input_image->GetPath().c_str(),
279 &error_msg));
280 if (image.get() == nullptr) {
281 LOG(ERROR) << "unable to map image file " << input_image->GetPath() << " : " << error_msg;
282 return false;
283 }
284 gc::space::ImageSpace* ispc = Runtime::Current()->GetHeap()->GetImageSpace();
285
Igor Murashkin46774762014-10-22 11:37:02 -0700286 std::unique_ptr<ElfFile> elf(ElfFile::Open(input_oat,
Alex Light53cb16b2014-06-12 11:26:29 -0700287 PROT_READ | PROT_WRITE, MAP_PRIVATE, &error_msg));
288 if (elf.get() == nullptr) {
289 LOG(ERROR) << "unable to open oat file " << input_oat->GetPath() << " : " << error_msg;
290 return false;
291 }
292
Igor Murashkin46774762014-10-22 11:37:02 -0700293 bool skip_patching_oat = false;
294 MaybePic is_oat_pic = IsOatPic(elf.get());
295 if (is_oat_pic >= ERROR_FIRST) {
296 // Error logged by IsOatPic
297 return false;
298 } else if (is_oat_pic == PIC) {
299 // Do not need to do ELF-file patching. Create a symlink and skip the ELF patching.
300 if (!ReplaceOatFileWithSymlink(input_oat->GetPath(),
301 output_oat->GetPath(),
302 output_oat_opened_from_fd,
303 new_oat_out)) {
304 // Errors already logged by above call.
305 return false;
306 }
307 // Don't patch the OAT, since we just symlinked it. Image still needs patching.
308 skip_patching_oat = true;
309 } else {
310 CHECK(is_oat_pic == NOT_PIC);
311 }
312
Mathieu Chartier2d721012014-11-10 11:08:06 -0800313 PatchOat p(isa, elf.release(), image.release(), ispc->GetLiveBitmap(), ispc->GetMemMap(),
Alex Light53cb16b2014-06-12 11:26:29 -0700314 delta, timings);
315 t.NewTiming("Patching files");
Igor Murashkin46774762014-10-22 11:37:02 -0700316 if (!skip_patching_oat && !p.PatchElf()) {
Alex Lighta59dd802014-07-02 16:28:08 -0700317 LOG(ERROR) << "Failed to patch oat file " << input_oat->GetPath();
Alex Light53cb16b2014-06-12 11:26:29 -0700318 return false;
319 }
320 if (!p.PatchImage()) {
Alex Lighta59dd802014-07-02 16:28:08 -0700321 LOG(ERROR) << "Failed to patch image file " << input_image->GetPath();
Alex Light53cb16b2014-06-12 11:26:29 -0700322 return false;
323 }
324
325 t.NewTiming("Writing files");
Igor Murashkin46774762014-10-22 11:37:02 -0700326 if (!skip_patching_oat && !p.WriteElf(output_oat)) {
327 LOG(ERROR) << "Failed to write oat file " << input_oat->GetPath();
Alex Light53cb16b2014-06-12 11:26:29 -0700328 return false;
329 }
330 if (!p.WriteImage(output_image)) {
Igor Murashkin46774762014-10-22 11:37:02 -0700331 LOG(ERROR) << "Failed to write image file " << input_image->GetPath();
Alex Light53cb16b2014-06-12 11:26:29 -0700332 return false;
333 }
334 return true;
335}
336
337bool PatchOat::WriteElf(File* out) {
Alex Lighteefbe392014-07-08 09:53:18 -0700338 TimingLogger::ScopedTiming t("Writing Elf File", timings_);
Alex Lighta59dd802014-07-02 16:28:08 -0700339
Alex Light53cb16b2014-06-12 11:26:29 -0700340 CHECK(oat_file_.get() != nullptr);
341 CHECK(out != nullptr);
342 size_t expect = oat_file_->Size();
343 if (out->WriteFully(reinterpret_cast<char*>(oat_file_->Begin()), expect) &&
344 out->SetLength(expect) == 0) {
345 return true;
346 } else {
347 LOG(ERROR) << "Writing to oat file " << out->GetPath() << " failed.";
348 return false;
349 }
350}
351
352bool PatchOat::WriteImage(File* out) {
Alex Lighteefbe392014-07-08 09:53:18 -0700353 TimingLogger::ScopedTiming t("Writing image File", timings_);
Alex Lighta59dd802014-07-02 16:28:08 -0700354 std::string error_msg;
355
Alex Lightcf4bf382014-07-24 11:29:14 -0700356 ScopedFlock img_flock;
357 img_flock.Init(out, &error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -0700358
Alex Light53cb16b2014-06-12 11:26:29 -0700359 CHECK(image_ != nullptr);
360 CHECK(out != nullptr);
361 size_t expect = image_->Size();
362 if (out->WriteFully(reinterpret_cast<char*>(image_->Begin()), expect) &&
363 out->SetLength(expect) == 0) {
364 return true;
365 } else {
366 LOG(ERROR) << "Writing to image file " << out->GetPath() << " failed.";
367 return false;
368 }
369}
370
Igor Murashkin46774762014-10-22 11:37:02 -0700371bool PatchOat::IsImagePic(const ImageHeader& image_header, const std::string& image_path) {
372 if (!image_header.CompilePic()) {
373 if (kIsDebugBuild) {
374 LOG(INFO) << "image at location " << image_path << " was *not* compiled pic";
375 }
376 return false;
377 }
378
379 if (kIsDebugBuild) {
380 LOG(INFO) << "image at location " << image_path << " was compiled PIC";
381 }
382
383 return true;
384}
385
386PatchOat::MaybePic PatchOat::IsOatPic(const ElfFile* oat_in) {
387 if (oat_in == nullptr) {
388 LOG(ERROR) << "No ELF input oat fie available";
389 return ERROR_OAT_FILE;
390 }
391
392 const std::string& file_path = oat_in->GetFile().GetPath();
393
394 const OatHeader* oat_header = GetOatHeader(oat_in);
395 if (oat_header == nullptr) {
396 LOG(ERROR) << "Failed to find oat header in oat file " << file_path;
397 return ERROR_OAT_FILE;
398 }
399
400 if (!oat_header->IsValid()) {
401 LOG(ERROR) << "Elf file " << file_path << " has an invalid oat header";
402 return ERROR_OAT_FILE;
403 }
404
405 bool is_pic = oat_header->IsPic();
406 if (kIsDebugBuild) {
407 LOG(INFO) << "Oat file at " << file_path << " is " << (is_pic ? "PIC" : "not pic");
408 }
409
410 return is_pic ? PIC : NOT_PIC;
411}
412
413bool PatchOat::ReplaceOatFileWithSymlink(const std::string& input_oat_filename,
414 const std::string& output_oat_filename,
415 bool output_oat_opened_from_fd,
416 bool new_oat_out) {
417 // Need a file when we are PIC, since we symlink over it. Refusing to symlink into FD.
418 if (output_oat_opened_from_fd) {
419 // TODO: installd uses --output-oat-fd. Should we change class linking logic for PIC?
420 LOG(ERROR) << "No output oat filename specified, needs filename for when we are PIC";
421 return false;
422 }
423
424 // Image was PIC. Create symlink where the oat is supposed to go.
425 if (!new_oat_out) {
426 LOG(ERROR) << "Oat file " << output_oat_filename << " already exists, refusing to overwrite";
427 return false;
428 }
429
430 // Delete the original file, since we won't need it.
431 TEMP_FAILURE_RETRY(unlink(output_oat_filename.c_str()));
432
433 // Create a symlink from the old oat to the new oat
434 if (symlink(input_oat_filename.c_str(), output_oat_filename.c_str()) < 0) {
435 int err = errno;
436 LOG(ERROR) << "Failed to create symlink at " << output_oat_filename
437 << " error(" << err << "): " << strerror(err);
438 return false;
439 }
440
441 if (kIsDebugBuild) {
442 LOG(INFO) << "Created symlink " << output_oat_filename << " -> " << input_oat_filename;
443 }
444
445 return true;
446}
447
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700448class PatchOatArtFieldVisitor : public ArtFieldVisitor {
449 public:
450 explicit PatchOatArtFieldVisitor(PatchOat* patch_oat) : patch_oat_(patch_oat) {}
451
452 void Visit(ArtField* field) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
453 ArtField* const dest = patch_oat_->RelocatedCopyOf(field);
454 dest->SetDeclaringClass(patch_oat_->RelocatedAddressOfPointer(field->GetDeclaringClass()));
Mathieu Chartiere401d142015-04-22 13:56:20 -0700455 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700456
457 private:
458 PatchOat* const patch_oat_;
459};
460
461void PatchOat::PatchArtFields(const ImageHeader* image_header) {
462 PatchOatArtFieldVisitor visitor(this);
463 const auto& section = image_header->GetImageSection(ImageHeader::kSectionArtFields);
464 section.VisitPackedArtFields(&visitor, heap_->Begin());
Mathieu Chartiere401d142015-04-22 13:56:20 -0700465}
466
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700467class PatchOatArtMethodVisitor : public ArtMethodVisitor {
468 public:
469 explicit PatchOatArtMethodVisitor(PatchOat* patch_oat) : patch_oat_(patch_oat) {}
470
471 void Visit(ArtMethod* method) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
472 ArtMethod* const dest = patch_oat_->RelocatedCopyOf(method);
473 patch_oat_->FixupMethod(method, dest);
474 }
475
476 private:
477 PatchOat* const patch_oat_;
478};
479
Mathieu Chartiere401d142015-04-22 13:56:20 -0700480void PatchOat::PatchArtMethods(const ImageHeader* image_header) {
481 const auto& section = image_header->GetMethodsSection();
482 const size_t pointer_size = InstructionSetPointerSize(isa_);
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700483 PatchOatArtMethodVisitor visitor(this);
Vladimir Markocf36d492015-08-12 19:27:26 +0100484 section.VisitPackedArtMethods(&visitor, heap_->Begin(), pointer_size);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700485}
486
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700487class FixupRootVisitor : public RootVisitor {
488 public:
489 explicit FixupRootVisitor(const PatchOat* patch_oat) : patch_oat_(patch_oat) {
490 }
491
492 void VisitRoots(mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -0700493 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700494 for (size_t i = 0; i < count; ++i) {
495 *roots[i] = patch_oat_->RelocatedAddressOfPointer(*roots[i]);
496 }
497 }
498
499 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots, size_t count,
500 const RootInfo& info ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -0700501 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700502 for (size_t i = 0; i < count; ++i) {
503 roots[i]->Assign(patch_oat_->RelocatedAddressOfPointer(roots[i]->AsMirrorPtr()));
504 }
505 }
506
507 private:
508 const PatchOat* const patch_oat_;
509};
510
511void PatchOat::PatchInternedStrings(const ImageHeader* image_header) {
512 const auto& section = image_header->GetImageSection(ImageHeader::kSectionInternedStrings);
513 InternTable temp_table;
514 // Note that we require that ReadFromMemory does not make an internal copy of the elements.
515 // This also relies on visit roots not doing any verification which could fail after we update
516 // the roots to be the image addresses.
517 temp_table.ReadFromMemory(image_->Begin() + section.Offset());
518 FixupRootVisitor visitor(this);
519 temp_table.VisitRoots(&visitor, kVisitRootFlagAllRoots);
520}
521
Mathieu Chartierc7853442015-03-27 14:35:38 -0700522void PatchOat::PatchDexFileArrays(mirror::ObjectArray<mirror::Object>* img_roots) {
523 auto* dex_caches = down_cast<mirror::ObjectArray<mirror::DexCache>*>(
524 img_roots->Get(ImageHeader::kDexCaches));
525 for (size_t i = 0, count = dex_caches->GetLength(); i < count; ++i) {
526 auto* dex_cache = dex_caches->GetWithoutChecks(i);
527 auto* fields = dex_cache->GetResolvedFields();
Mathieu Chartiere401d142015-04-22 13:56:20 -0700528 if (fields != nullptr) {
529 CHECK(!fields->IsObjectArray());
530 CHECK(fields->IsArrayInstance());
531 FixupNativePointerArray(fields);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700532 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700533 auto* methods = dex_cache->GetResolvedMethods();
534 if (methods != nullptr) {
535 CHECK(!methods->IsObjectArray());
536 CHECK(methods->IsArrayInstance());
537 FixupNativePointerArray(methods);
538 }
539 }
540}
541
542void PatchOat::FixupNativePointerArray(mirror::PointerArray* object) {
543 if (object->IsIntArray()) {
544 mirror::IntArray* arr = object->AsIntArray();
545 mirror::IntArray* copy_arr = down_cast<mirror::IntArray*>(RelocatedCopyOf(arr));
546 for (size_t j = 0, count2 = arr->GetLength(); j < count2; ++j) {
547 copy_arr->SetWithoutChecks<false>(
548 j, RelocatedAddressOfIntPointer(arr->GetWithoutChecks(j)));
549 }
550 } else {
551 CHECK(object->IsLongArray());
552 mirror::LongArray* arr = object->AsLongArray();
553 mirror::LongArray* copy_arr = down_cast<mirror::LongArray*>(RelocatedCopyOf(arr));
554 for (size_t j = 0, count2 = arr->GetLength(); j < count2; ++j) {
555 copy_arr->SetWithoutChecks<false>(
556 j, RelocatedAddressOfIntPointer(arr->GetWithoutChecks(j)));
Mathieu Chartierc7853442015-03-27 14:35:38 -0700557 }
558 }
559}
560
Alex Light53cb16b2014-06-12 11:26:29 -0700561bool PatchOat::PatchImage() {
562 ImageHeader* image_header = reinterpret_cast<ImageHeader*>(image_->Begin());
563 CHECK_GT(image_->Size(), sizeof(ImageHeader));
564 // These are the roots from the original file.
Mathieu Chartierc7853442015-03-27 14:35:38 -0700565 auto* img_roots = image_header->GetImageRoots();
Alex Light53cb16b2014-06-12 11:26:29 -0700566 image_header->RelocateImage(delta_);
567
Mathieu Chartierc7853442015-03-27 14:35:38 -0700568 PatchArtFields(image_header);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700569 PatchArtMethods(image_header);
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700570 PatchInternedStrings(image_header);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700571 // Patch dex file int/long arrays which point to ArtFields.
572 PatchDexFileArrays(img_roots);
573
Alex Light53cb16b2014-06-12 11:26:29 -0700574 VisitObject(img_roots);
575 if (!image_header->IsValid()) {
576 LOG(ERROR) << "reloction renders image header invalid";
577 return false;
578 }
579
580 {
Alex Lighteefbe392014-07-08 09:53:18 -0700581 TimingLogger::ScopedTiming t("Walk Bitmap", timings_);
Alex Light53cb16b2014-06-12 11:26:29 -0700582 // Walk the bitmap.
583 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
584 bitmap_->Walk(PatchOat::BitmapCallback, this);
585 }
586 return true;
587}
588
589bool PatchOat::InHeap(mirror::Object* o) {
590 uintptr_t begin = reinterpret_cast<uintptr_t>(heap_->Begin());
591 uintptr_t end = reinterpret_cast<uintptr_t>(heap_->End());
592 uintptr_t obj = reinterpret_cast<uintptr_t>(o);
593 return o == nullptr || (begin <= obj && obj < end);
594}
595
596void PatchOat::PatchVisitor::operator() (mirror::Object* obj, MemberOffset off,
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700597 bool is_static_unused ATTRIBUTE_UNUSED) const {
Alex Light53cb16b2014-06-12 11:26:29 -0700598 mirror::Object* referent = obj->GetFieldObject<mirror::Object, kVerifyNone>(off);
599 DCHECK(patcher_->InHeap(referent)) << "Referent is not in the heap.";
Mathieu Chartierc7853442015-03-27 14:35:38 -0700600 mirror::Object* moved_object = patcher_->RelocatedAddressOfPointer(referent);
Alex Light53cb16b2014-06-12 11:26:29 -0700601 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(off, moved_object);
602}
603
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700604void PatchOat::PatchVisitor::operator() (mirror::Class* cls ATTRIBUTE_UNUSED,
605 mirror::Reference* ref) const {
Alex Light53cb16b2014-06-12 11:26:29 -0700606 MemberOffset off = mirror::Reference::ReferentOffset();
607 mirror::Object* referent = ref->GetReferent();
608 DCHECK(patcher_->InHeap(referent)) << "Referent is not in the heap.";
Mathieu Chartierc7853442015-03-27 14:35:38 -0700609 mirror::Object* moved_object = patcher_->RelocatedAddressOfPointer(referent);
Alex Light53cb16b2014-06-12 11:26:29 -0700610 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(off, moved_object);
611}
612
Alex Light53cb16b2014-06-12 11:26:29 -0700613// Called by BitmapCallback
614void PatchOat::VisitObject(mirror::Object* object) {
615 mirror::Object* copy = RelocatedCopyOf(object);
616 CHECK(copy != nullptr);
617 if (kUseBakerOrBrooksReadBarrier) {
618 object->AssertReadBarrierPointer();
619 if (kUseBrooksReadBarrier) {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700620 mirror::Object* moved_to = RelocatedAddressOfPointer(object);
Alex Light53cb16b2014-06-12 11:26:29 -0700621 copy->SetReadBarrierPointer(moved_to);
622 DCHECK_EQ(copy->GetReadBarrierPointer(), moved_to);
623 }
624 }
625 PatchOat::PatchVisitor visitor(this, copy);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -0700626 object->VisitReferences<kVerifyNone>(visitor, visitor);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700627 if (object->IsClass<kVerifyNone>()) {
628 auto* klass = object->AsClass();
629 auto* copy_klass = down_cast<mirror::Class*>(copy);
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700630 copy_klass->SetSFieldsPtrUnchecked(RelocatedAddressOfPointer(klass->GetSFieldsPtr()));
631 copy_klass->SetIFieldsPtrUnchecked(RelocatedAddressOfPointer(klass->GetIFieldsPtr()));
Mathieu Chartiere401d142015-04-22 13:56:20 -0700632 copy_klass->SetDirectMethodsPtrUnchecked(
633 RelocatedAddressOfPointer(klass->GetDirectMethodsPtr()));
634 copy_klass->SetVirtualMethodsPtr(RelocatedAddressOfPointer(klass->GetVirtualMethodsPtr()));
635 auto* vtable = klass->GetVTable();
636 if (vtable != nullptr) {
637 FixupNativePointerArray(vtable);
638 }
639 auto* iftable = klass->GetIfTable();
640 if (iftable != nullptr) {
641 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
642 if (iftable->GetMethodArrayCount(i) > 0) {
643 auto* method_array = iftable->GetMethodArray(i);
644 CHECK(method_array != nullptr);
645 FixupNativePointerArray(method_array);
646 }
647 }
648 }
649 if (klass->ShouldHaveEmbeddedImtAndVTable()) {
650 const size_t pointer_size = InstructionSetPointerSize(isa_);
651 for (int32_t i = 0; i < klass->GetEmbeddedVTableLength(); ++i) {
652 copy_klass->SetEmbeddedVTableEntryUnchecked(i, RelocatedAddressOfPointer(
653 klass->GetEmbeddedVTableEntry(i, pointer_size)), pointer_size);
654 }
655 for (size_t i = 0; i < mirror::Class::kImtSize; ++i) {
656 copy_klass->SetEmbeddedImTableEntry(i, RelocatedAddressOfPointer(
657 klass->GetEmbeddedImTableEntry(i, pointer_size)), pointer_size);
658 }
659 }
660 }
661 if (object->GetClass() == mirror::Method::StaticClass() ||
662 object->GetClass() == mirror::Constructor::StaticClass()) {
663 // Need to go update the ArtMethod.
664 auto* dest = down_cast<mirror::AbstractMethod*>(copy);
665 auto* src = down_cast<mirror::AbstractMethod*>(object);
666 dest->SetArtMethod(RelocatedAddressOfPointer(src->GetArtMethod()));
Alex Light53cb16b2014-06-12 11:26:29 -0700667 }
668}
669
Mathieu Chartiere401d142015-04-22 13:56:20 -0700670void PatchOat::FixupMethod(ArtMethod* object, ArtMethod* copy) {
Mathieu Chartier2d721012014-11-10 11:08:06 -0800671 const size_t pointer_size = InstructionSetPointerSize(isa_);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700672 copy->CopyFrom(object, pointer_size);
Alex Light53cb16b2014-06-12 11:26:29 -0700673 // Just update the entry points if it looks like we should.
Alex Lighteefbe392014-07-08 09:53:18 -0700674 // TODO: sanity check all the pointers' values
Mathieu Chartiere401d142015-04-22 13:56:20 -0700675 copy->SetDeclaringClass(RelocatedAddressOfPointer(object->GetDeclaringClass()));
676 copy->SetDexCacheResolvedMethods(RelocatedAddressOfPointer(object->GetDexCacheResolvedMethods()));
677 copy->SetDexCacheResolvedTypes(RelocatedAddressOfPointer(object->GetDexCacheResolvedTypes()));
678 copy->SetEntryPointFromQuickCompiledCodePtrSize(RelocatedAddressOfPointer(
679 object->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size)), pointer_size);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700680 copy->SetEntryPointFromJniPtrSize(RelocatedAddressOfPointer(
681 object->GetEntryPointFromJniPtrSize(pointer_size)), pointer_size);
Alex Light53cb16b2014-06-12 11:26:29 -0700682}
683
Igor Murashkin46774762014-10-22 11:37:02 -0700684bool PatchOat::Patch(File* input_oat, off_t delta, File* output_oat, TimingLogger* timings,
685 bool output_oat_opened_from_fd, bool new_oat_out) {
Alex Light53cb16b2014-06-12 11:26:29 -0700686 CHECK(input_oat != nullptr);
687 CHECK(output_oat != nullptr);
688 CHECK_GE(input_oat->Fd(), 0);
689 CHECK_GE(output_oat->Fd(), 0);
Alex Lighteefbe392014-07-08 09:53:18 -0700690 TimingLogger::ScopedTiming t("Setup Oat File Patching", timings);
Alex Light53cb16b2014-06-12 11:26:29 -0700691
692 std::string error_msg;
Igor Murashkin46774762014-10-22 11:37:02 -0700693 std::unique_ptr<ElfFile> elf(ElfFile::Open(input_oat,
Alex Light53cb16b2014-06-12 11:26:29 -0700694 PROT_READ | PROT_WRITE, MAP_PRIVATE, &error_msg));
695 if (elf.get() == nullptr) {
696 LOG(ERROR) << "unable to open oat file " << input_oat->GetPath() << " : " << error_msg;
697 return false;
698 }
699
Igor Murashkin46774762014-10-22 11:37:02 -0700700 MaybePic is_oat_pic = IsOatPic(elf.get());
701 if (is_oat_pic >= ERROR_FIRST) {
702 // Error logged by IsOatPic
703 return false;
704 } else if (is_oat_pic == PIC) {
705 // Do not need to do ELF-file patching. Create a symlink and skip the rest.
706 // Any errors will be logged by the function call.
707 return ReplaceOatFileWithSymlink(input_oat->GetPath(),
708 output_oat->GetPath(),
709 output_oat_opened_from_fd,
710 new_oat_out);
711 } else {
712 CHECK(is_oat_pic == NOT_PIC);
713 }
714
Alex Light53cb16b2014-06-12 11:26:29 -0700715 PatchOat p(elf.release(), delta, timings);
716 t.NewTiming("Patch Oat file");
717 if (!p.PatchElf()) {
718 return false;
719 }
720
721 t.NewTiming("Writing oat file");
722 if (!p.WriteElf(output_oat)) {
723 return false;
724 }
725 return true;
726}
727
Tong Shen62d1ca32014-09-03 17:24:56 -0700728template <typename ElfFileImpl>
729bool PatchOat::PatchOatHeader(ElfFileImpl* oat_file) {
730 auto rodata_sec = oat_file->FindSectionByName(".rodata");
Alex Lighta59dd802014-07-02 16:28:08 -0700731 if (rodata_sec == nullptr) {
732 return false;
733 }
Tong Shen62d1ca32014-09-03 17:24:56 -0700734 OatHeader* oat_header = reinterpret_cast<OatHeader*>(oat_file->Begin() + rodata_sec->sh_offset);
Alex Lighta59dd802014-07-02 16:28:08 -0700735 if (!oat_header->IsValid()) {
Tong Shen62d1ca32014-09-03 17:24:56 -0700736 LOG(ERROR) << "Elf file " << oat_file->GetFile().GetPath() << " has an invalid oat header";
Alex Lighta59dd802014-07-02 16:28:08 -0700737 return false;
738 }
739 oat_header->RelocateOat(delta_);
740 return true;
741}
742
Alex Light53cb16b2014-06-12 11:26:29 -0700743bool PatchOat::PatchElf() {
Ian Rogersd4c4d952014-10-16 20:31:53 -0700744 if (oat_file_->Is64Bit())
Tong Shen62d1ca32014-09-03 17:24:56 -0700745 return PatchElf<ElfFileImpl64>(oat_file_->GetImpl64());
746 else
747 return PatchElf<ElfFileImpl32>(oat_file_->GetImpl32());
748}
749
750template <typename ElfFileImpl>
751bool PatchOat::PatchElf(ElfFileImpl* oat_file) {
Alex Lighta59dd802014-07-02 16:28:08 -0700752 TimingLogger::ScopedTiming t("Fixup Elf Text Section", timings_);
Vladimir Marko3fc99032015-05-13 19:06:30 +0100753
754 // Fix up absolute references to locations within the boot image.
David Srbecky2f6cdb02015-04-11 00:17:53 +0100755 if (!oat_file->ApplyOatPatchesTo(".text", delta_)) {
Alex Lighta59dd802014-07-02 16:28:08 -0700756 return false;
757 }
758
Vladimir Marko3fc99032015-05-13 19:06:30 +0100759 // Update the OatHeader fields referencing the boot image.
Tong Shen62d1ca32014-09-03 17:24:56 -0700760 if (!PatchOatHeader<ElfFileImpl>(oat_file)) {
Alex Lighta59dd802014-07-02 16:28:08 -0700761 return false;
762 }
763
Vladimir Marko3fc99032015-05-13 19:06:30 +0100764 bool need_boot_oat_fixup = true;
Ian Rogersd4c4d952014-10-16 20:31:53 -0700765 for (unsigned int i = 0; i < oat_file->GetProgramHeaderNum(); ++i) {
Tong Shen62d1ca32014-09-03 17:24:56 -0700766 auto hdr = oat_file->GetProgramHeader(i);
Vladimir Marko3fc99032015-05-13 19:06:30 +0100767 if (hdr->p_type == PT_LOAD && hdr->p_vaddr == 0u) {
768 need_boot_oat_fixup = false;
Ian Rogersd4c4d952014-10-16 20:31:53 -0700769 break;
Alex Light53cb16b2014-06-12 11:26:29 -0700770 }
771 }
Vladimir Marko3fc99032015-05-13 19:06:30 +0100772 if (!need_boot_oat_fixup) {
773 // This is an app oat file that can be loaded at an arbitrary address in memory.
774 // Boot image references were patched above and there's nothing else to do.
Alex Lighta59dd802014-07-02 16:28:08 -0700775 return true;
776 }
Tong Shen62d1ca32014-09-03 17:24:56 -0700777
Vladimir Marko3fc99032015-05-13 19:06:30 +0100778 // This is a boot oat file that's loaded at a particular address and we need
779 // to patch all absolute addresses, starting with ELF program headers.
780
Tong Shen62d1ca32014-09-03 17:24:56 -0700781 t.NewTiming("Fixup Elf Headers");
782 // Fixup Phdr's
783 oat_file->FixupProgramHeaders(delta_);
784
Alex Lighta59dd802014-07-02 16:28:08 -0700785 t.NewTiming("Fixup Section Headers");
Tong Shen62d1ca32014-09-03 17:24:56 -0700786 // Fixup Shdr's
787 oat_file->FixupSectionHeaders(delta_);
Alex Light53cb16b2014-06-12 11:26:29 -0700788
Alex Lighta59dd802014-07-02 16:28:08 -0700789 t.NewTiming("Fixup Dynamics");
Tong Shen62d1ca32014-09-03 17:24:56 -0700790 oat_file->FixupDynamic(delta_);
Alex Light53cb16b2014-06-12 11:26:29 -0700791
792 t.NewTiming("Fixup Elf Symbols");
793 // Fixup dynsym
Tong Shen62d1ca32014-09-03 17:24:56 -0700794 if (!oat_file->FixupSymbols(delta_, true)) {
Alex Light53cb16b2014-06-12 11:26:29 -0700795 return false;
796 }
Alex Light53cb16b2014-06-12 11:26:29 -0700797 // Fixup symtab
Tong Shen62d1ca32014-09-03 17:24:56 -0700798 if (!oat_file->FixupSymbols(delta_, false)) {
799 return false;
Alex Light53cb16b2014-06-12 11:26:29 -0700800 }
801
Yevgeny Roubane3ea8382014-08-08 16:29:38 +0700802 t.NewTiming("Fixup Debug Sections");
Tong Shen62d1ca32014-09-03 17:24:56 -0700803 if (!oat_file->FixupDebugSections(delta_)) {
Yevgeny Roubane3ea8382014-08-08 16:29:38 +0700804 return false;
805 }
806
Alex Light53cb16b2014-06-12 11:26:29 -0700807 return true;
808}
809
Alex Light53cb16b2014-06-12 11:26:29 -0700810static int orig_argc;
811static char** orig_argv;
812
813static std::string CommandLine() {
814 std::vector<std::string> command;
815 for (int i = 0; i < orig_argc; ++i) {
816 command.push_back(orig_argv[i]);
817 }
818 return Join(command, ' ');
819}
820
821static void UsageErrorV(const char* fmt, va_list ap) {
822 std::string error;
823 StringAppendV(&error, fmt, ap);
824 LOG(ERROR) << error;
825}
826
827static void UsageError(const char* fmt, ...) {
828 va_list ap;
829 va_start(ap, fmt);
830 UsageErrorV(fmt, ap);
831 va_end(ap);
832}
833
Andreas Gampe794ad762015-02-23 08:12:24 -0800834NO_RETURN static void Usage(const char *fmt, ...) {
Alex Light53cb16b2014-06-12 11:26:29 -0700835 va_list ap;
836 va_start(ap, fmt);
837 UsageErrorV(fmt, ap);
838 va_end(ap);
839
840 UsageError("Command: %s", CommandLine().c_str());
841 UsageError("Usage: patchoat [options]...");
842 UsageError("");
843 UsageError(" --instruction-set=<isa>: Specifies the instruction set the patched code is");
844 UsageError(" compiled for. Required if you use --input-oat-location");
845 UsageError("");
846 UsageError(" --input-oat-file=<file.oat>: Specifies the exact filename of the oat file to be");
847 UsageError(" patched.");
848 UsageError("");
849 UsageError(" --input-oat-fd=<file-descriptor>: Specifies the file-descriptor of the oat file");
850 UsageError(" to be patched.");
851 UsageError("");
852 UsageError(" --input-oat-location=<file.oat>: Specifies the 'location' to read the patched");
853 UsageError(" oat file from. If used one must also supply the --instruction-set");
854 UsageError("");
855 UsageError(" --input-image-location=<file.art>: Specifies the 'location' of the image file to");
856 UsageError(" be patched. If --instruction-set is not given it will use the instruction set");
857 UsageError(" extracted from the --input-oat-file.");
858 UsageError("");
859 UsageError(" --output-oat-file=<file.oat>: Specifies the exact file to write the patched oat");
860 UsageError(" file to.");
861 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700862 UsageError(" --output-oat-fd=<file-descriptor>: Specifies the file-descriptor to write the");
863 UsageError(" the patched oat file to.");
864 UsageError("");
865 UsageError(" --output-image-file=<file.art>: Specifies the exact file to write the patched");
866 UsageError(" image file to.");
867 UsageError("");
868 UsageError(" --output-image-fd=<file-descriptor>: Specifies the file-descriptor to write the");
869 UsageError(" the patched image file to.");
870 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700871 UsageError(" --orig-base-offset=<original-base-offset>: Specify the base offset the input file");
872 UsageError(" was compiled with. This is needed if one is specifying a --base-offset");
873 UsageError("");
874 UsageError(" --base-offset=<new-base-offset>: Specify the base offset we will repatch the");
875 UsageError(" given files to use. This requires that --orig-base-offset is also given.");
876 UsageError("");
877 UsageError(" --base-offset-delta=<delta>: Specify the amount to change the old base-offset by.");
878 UsageError(" This value may be negative.");
879 UsageError("");
Alex Light0eb76d22015-08-11 18:03:47 -0700880 UsageError(" --patched-image-file=<file.art>: Relocate the oat file to be the same as the");
881 UsageError(" given image file.");
Alex Light53cb16b2014-06-12 11:26:29 -0700882 UsageError("");
Alex Light0eb76d22015-08-11 18:03:47 -0700883 UsageError(" --patched-image-location=<file.art>: Relocate the oat file to be the same as the");
884 UsageError(" image at the given location. If used one must also specify the");
Alex Lighta59dd802014-07-02 16:28:08 -0700885 UsageError(" --instruction-set flag. It will search for this image in the same way that");
886 UsageError(" is done when loading one.");
Alex Light53cb16b2014-06-12 11:26:29 -0700887 UsageError("");
Alex Lightcf4bf382014-07-24 11:29:14 -0700888 UsageError(" --lock-output: Obtain a flock on output oat file before starting.");
889 UsageError("");
890 UsageError(" --no-lock-output: Do not attempt to obtain a flock on output oat file.");
891 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700892 UsageError(" --dump-timings: dump out patch timing information");
893 UsageError("");
894 UsageError(" --no-dump-timings: do not dump out patch timing information");
895 UsageError("");
896
897 exit(EXIT_FAILURE);
898}
899
Alex Lighteefbe392014-07-08 09:53:18 -0700900static bool ReadBaseDelta(const char* name, off_t* delta, std::string* error_msg) {
Alex Light53cb16b2014-06-12 11:26:29 -0700901 CHECK(name != nullptr);
902 CHECK(delta != nullptr);
903 std::unique_ptr<File> file;
904 if (OS::FileExists(name)) {
905 file.reset(OS::OpenFileForReading(name));
906 if (file.get() == nullptr) {
Alex Lighteefbe392014-07-08 09:53:18 -0700907 *error_msg = "Failed to open file %s for reading";
Alex Light53cb16b2014-06-12 11:26:29 -0700908 return false;
909 }
910 } else {
Alex Lighteefbe392014-07-08 09:53:18 -0700911 *error_msg = "File %s does not exist";
Alex Light53cb16b2014-06-12 11:26:29 -0700912 return false;
913 }
914 CHECK(file.get() != nullptr);
915 ImageHeader hdr;
916 if (sizeof(hdr) != file->Read(reinterpret_cast<char*>(&hdr), sizeof(hdr), 0)) {
Alex Lighteefbe392014-07-08 09:53:18 -0700917 *error_msg = "Failed to read file %s";
Alex Light53cb16b2014-06-12 11:26:29 -0700918 return false;
919 }
920 if (!hdr.IsValid()) {
Alex Lighteefbe392014-07-08 09:53:18 -0700921 *error_msg = "%s does not contain a valid image header.";
Alex Light53cb16b2014-06-12 11:26:29 -0700922 return false;
923 }
924 *delta = hdr.GetPatchDelta();
925 return true;
926}
927
928static File* CreateOrOpen(const char* name, bool* created) {
929 if (OS::FileExists(name)) {
930 *created = false;
931 return OS::OpenFileReadWrite(name);
932 } else {
933 *created = true;
Alex Lightcf4bf382014-07-24 11:29:14 -0700934 std::unique_ptr<File> f(OS::CreateEmptyFile(name));
935 if (f.get() != nullptr) {
936 if (fchmod(f->Fd(), 0644) != 0) {
937 PLOG(ERROR) << "Unable to make " << name << " world readable";
Brian Carlstrom8c52a3f2014-09-30 16:18:01 -0700938 TEMP_FAILURE_RETRY(unlink(name));
Alex Lightcf4bf382014-07-24 11:29:14 -0700939 return nullptr;
940 }
941 }
942 return f.release();
Alex Light53cb16b2014-06-12 11:26:29 -0700943 }
944}
945
Andreas Gampe4303ba92014-11-06 01:00:46 -0800946// Either try to close the file (close=true), or erase it.
947static bool FinishFile(File* file, bool close) {
948 if (close) {
949 if (file->FlushCloseOrErase() != 0) {
950 PLOG(ERROR) << "Failed to flush and close file.";
951 return false;
952 }
953 return true;
954 } else {
955 file->Erase();
956 return false;
957 }
958}
959
Alex Lighteefbe392014-07-08 09:53:18 -0700960static int patchoat(int argc, char **argv) {
Alex Light53cb16b2014-06-12 11:26:29 -0700961 InitLogging(argv);
Mathieu Chartier6e88ef62014-10-14 15:01:24 -0700962 MemMap::Init();
Alex Light53cb16b2014-06-12 11:26:29 -0700963 const bool debug = kIsDebugBuild;
964 orig_argc = argc;
965 orig_argv = argv;
966 TimingLogger timings("patcher", false, false);
967
968 InitLogging(argv);
969
970 // Skip over the command name.
971 argv++;
972 argc--;
973
974 if (argc == 0) {
975 Usage("No arguments specified");
976 }
977
978 timings.StartTiming("Patchoat");
979
980 // cmd line args
981 bool isa_set = false;
982 InstructionSet isa = kNone;
983 std::string input_oat_filename;
984 std::string input_oat_location;
985 int input_oat_fd = -1;
986 bool have_input_oat = false;
987 std::string input_image_location;
988 std::string output_oat_filename;
Alex Light53cb16b2014-06-12 11:26:29 -0700989 int output_oat_fd = -1;
990 bool have_output_oat = false;
991 std::string output_image_filename;
Alex Light53cb16b2014-06-12 11:26:29 -0700992 int output_image_fd = -1;
993 bool have_output_image = false;
994 uintptr_t base_offset = 0;
995 bool base_offset_set = false;
996 uintptr_t orig_base_offset = 0;
997 bool orig_base_offset_set = false;
998 off_t base_delta = 0;
999 bool base_delta_set = false;
Alex Light0eb76d22015-08-11 18:03:47 -07001000 bool match_delta = false;
Alex Light53cb16b2014-06-12 11:26:29 -07001001 std::string patched_image_filename;
1002 std::string patched_image_location;
1003 bool dump_timings = kIsDebugBuild;
Alex Lightcf4bf382014-07-24 11:29:14 -07001004 bool lock_output = true;
Alex Light53cb16b2014-06-12 11:26:29 -07001005
Ian Rogersd4c4d952014-10-16 20:31:53 -07001006 for (int i = 0; i < argc; ++i) {
Alex Light53cb16b2014-06-12 11:26:29 -07001007 const StringPiece option(argv[i]);
1008 const bool log_options = false;
1009 if (log_options) {
1010 LOG(INFO) << "patchoat: option[" << i << "]=" << argv[i];
1011 }
Alex Light53cb16b2014-06-12 11:26:29 -07001012 if (option.starts_with("--instruction-set=")) {
1013 isa_set = true;
1014 const char* isa_str = option.substr(strlen("--instruction-set=")).data();
Andreas Gampe20c89302014-08-19 17:28:06 -07001015 isa = GetInstructionSetFromString(isa_str);
1016 if (isa == kNone) {
1017 Usage("Unknown or invalid instruction set %s", isa_str);
Alex Light53cb16b2014-06-12 11:26:29 -07001018 }
1019 } else if (option.starts_with("--input-oat-location=")) {
1020 if (have_input_oat) {
1021 Usage("Only one of --input-oat-file, --input-oat-location and --input-oat-fd may be used.");
1022 }
1023 have_input_oat = true;
1024 input_oat_location = option.substr(strlen("--input-oat-location=")).data();
1025 } else if (option.starts_with("--input-oat-file=")) {
1026 if (have_input_oat) {
1027 Usage("Only one of --input-oat-file, --input-oat-location and --input-oat-fd may be used.");
1028 }
1029 have_input_oat = true;
1030 input_oat_filename = option.substr(strlen("--input-oat-file=")).data();
1031 } else if (option.starts_with("--input-oat-fd=")) {
1032 if (have_input_oat) {
1033 Usage("Only one of --input-oat-file, --input-oat-location and --input-oat-fd may be used.");
1034 }
1035 have_input_oat = true;
1036 const char* oat_fd_str = option.substr(strlen("--input-oat-fd=")).data();
1037 if (!ParseInt(oat_fd_str, &input_oat_fd)) {
1038 Usage("Failed to parse --input-oat-fd argument '%s' as an integer", oat_fd_str);
1039 }
1040 if (input_oat_fd < 0) {
1041 Usage("--input-oat-fd pass a negative value %d", input_oat_fd);
1042 }
1043 } else if (option.starts_with("--input-image-location=")) {
1044 input_image_location = option.substr(strlen("--input-image-location=")).data();
Alex Light53cb16b2014-06-12 11:26:29 -07001045 } else if (option.starts_with("--output-oat-file=")) {
1046 if (have_output_oat) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001047 Usage("Only one of --output-oat-file, and --output-oat-fd may be used.");
Alex Light53cb16b2014-06-12 11:26:29 -07001048 }
1049 have_output_oat = true;
1050 output_oat_filename = option.substr(strlen("--output-oat-file=")).data();
1051 } else if (option.starts_with("--output-oat-fd=")) {
1052 if (have_output_oat) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001053 Usage("Only one of --output-oat-file, --output-oat-fd may be used.");
Alex Light53cb16b2014-06-12 11:26:29 -07001054 }
1055 have_output_oat = true;
1056 const char* oat_fd_str = option.substr(strlen("--output-oat-fd=")).data();
1057 if (!ParseInt(oat_fd_str, &output_oat_fd)) {
1058 Usage("Failed to parse --output-oat-fd argument '%s' as an integer", oat_fd_str);
1059 }
1060 if (output_oat_fd < 0) {
1061 Usage("--output-oat-fd pass a negative value %d", output_oat_fd);
1062 }
Alex Light53cb16b2014-06-12 11:26:29 -07001063 } else if (option.starts_with("--output-image-file=")) {
1064 if (have_output_image) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001065 Usage("Only one of --output-image-file, and --output-image-fd may be used.");
Alex Light53cb16b2014-06-12 11:26:29 -07001066 }
1067 have_output_image = true;
1068 output_image_filename = option.substr(strlen("--output-image-file=")).data();
1069 } else if (option.starts_with("--output-image-fd=")) {
1070 if (have_output_image) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001071 Usage("Only one of --output-image-file, and --output-image-fd may be used.");
Alex Light53cb16b2014-06-12 11:26:29 -07001072 }
1073 have_output_image = true;
1074 const char* image_fd_str = option.substr(strlen("--output-image-fd=")).data();
1075 if (!ParseInt(image_fd_str, &output_image_fd)) {
1076 Usage("Failed to parse --output-image-fd argument '%s' as an integer", image_fd_str);
1077 }
1078 if (output_image_fd < 0) {
1079 Usage("--output-image-fd pass a negative value %d", output_image_fd);
1080 }
1081 } else if (option.starts_with("--orig-base-offset=")) {
1082 const char* orig_base_offset_str = option.substr(strlen("--orig-base-offset=")).data();
1083 orig_base_offset_set = true;
1084 if (!ParseUint(orig_base_offset_str, &orig_base_offset)) {
1085 Usage("Failed to parse --orig-base-offset argument '%s' as an uintptr_t",
1086 orig_base_offset_str);
1087 }
1088 } else if (option.starts_with("--base-offset=")) {
1089 const char* base_offset_str = option.substr(strlen("--base-offset=")).data();
1090 base_offset_set = true;
1091 if (!ParseUint(base_offset_str, &base_offset)) {
1092 Usage("Failed to parse --base-offset argument '%s' as an uintptr_t", base_offset_str);
1093 }
1094 } else if (option.starts_with("--base-offset-delta=")) {
1095 const char* base_delta_str = option.substr(strlen("--base-offset-delta=")).data();
1096 base_delta_set = true;
1097 if (!ParseInt(base_delta_str, &base_delta)) {
1098 Usage("Failed to parse --base-offset-delta argument '%s' as an off_t", base_delta_str);
1099 }
1100 } else if (option.starts_with("--patched-image-location=")) {
1101 patched_image_location = option.substr(strlen("--patched-image-location=")).data();
1102 } else if (option.starts_with("--patched-image-file=")) {
1103 patched_image_filename = option.substr(strlen("--patched-image-file=")).data();
Alex Lightcf4bf382014-07-24 11:29:14 -07001104 } else if (option == "--lock-output") {
1105 lock_output = true;
1106 } else if (option == "--no-lock-output") {
1107 lock_output = false;
Alex Light53cb16b2014-06-12 11:26:29 -07001108 } else if (option == "--dump-timings") {
1109 dump_timings = true;
1110 } else if (option == "--no-dump-timings") {
1111 dump_timings = false;
1112 } else {
1113 Usage("Unknown argument %s", option.data());
1114 }
1115 }
1116
1117 {
1118 // Only 1 of these may be set.
1119 uint32_t cnt = 0;
1120 cnt += (base_delta_set) ? 1 : 0;
1121 cnt += (base_offset_set && orig_base_offset_set) ? 1 : 0;
1122 cnt += (!patched_image_filename.empty()) ? 1 : 0;
1123 cnt += (!patched_image_location.empty()) ? 1 : 0;
1124 if (cnt > 1) {
1125 Usage("Only one of --base-offset/--orig-base-offset, --base-offset-delta, "
1126 "--patched-image-filename or --patched-image-location may be used.");
1127 } else if (cnt == 0) {
1128 Usage("Must specify --base-offset-delta, --base-offset and --orig-base-offset, "
1129 "--patched-image-location or --patched-image-file");
1130 }
1131 }
1132
1133 if (have_input_oat != have_output_oat) {
1134 Usage("Either both input and output oat must be supplied or niether must be.");
1135 }
1136
1137 if ((!input_image_location.empty()) != have_output_image) {
1138 Usage("Either both input and output image must be supplied or niether must be.");
1139 }
1140
1141 // We know we have both the input and output so rename for clarity.
1142 bool have_image_files = have_output_image;
1143 bool have_oat_files = have_output_oat;
1144
1145 if (!have_oat_files && !have_image_files) {
1146 Usage("Must be patching either an oat or an image file or both.");
1147 }
1148
1149 if (!have_oat_files && !isa_set) {
1150 Usage("Must include ISA if patching an image file without an oat file.");
1151 }
1152
1153 if (!input_oat_location.empty()) {
1154 if (!isa_set) {
1155 Usage("specifying a location requires specifying an instruction set");
1156 }
Alex Lightcf4bf382014-07-24 11:29:14 -07001157 if (!LocationToFilename(input_oat_location, isa, &input_oat_filename)) {
1158 Usage("Unable to find filename for input oat location %s", input_oat_location.c_str());
1159 }
Alex Light53cb16b2014-06-12 11:26:29 -07001160 if (debug) {
1161 LOG(INFO) << "Using input-oat-file " << input_oat_filename;
1162 }
1163 }
Alex Light53cb16b2014-06-12 11:26:29 -07001164 if (!patched_image_location.empty()) {
1165 if (!isa_set) {
1166 Usage("specifying a location requires specifying an instruction set");
1167 }
Alex Lighta59dd802014-07-02 16:28:08 -07001168 std::string system_filename;
1169 bool has_system = false;
1170 std::string cache_filename;
1171 bool has_cache = false;
1172 bool has_android_data_unused = false;
Andreas Gampe3c13a792014-09-18 20:56:04 -07001173 bool is_global_cache = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001174 if (!gc::space::ImageSpace::FindImageFilename(patched_image_location.c_str(), isa,
1175 &system_filename, &has_system, &cache_filename,
Andreas Gampe3c13a792014-09-18 20:56:04 -07001176 &has_android_data_unused, &has_cache,
1177 &is_global_cache)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001178 Usage("Unable to determine image file for location %s", patched_image_location.c_str());
1179 }
1180 if (has_cache) {
1181 patched_image_filename = cache_filename;
1182 } else if (has_system) {
1183 LOG(WARNING) << "Only image file found was in /system for image location "
1184 << patched_image_location;
1185 patched_image_filename = system_filename;
1186 } else {
1187 Usage("Unable to determine image file for location %s", patched_image_location.c_str());
1188 }
Alex Light53cb16b2014-06-12 11:26:29 -07001189 if (debug) {
1190 LOG(INFO) << "Using patched-image-file " << patched_image_filename;
1191 }
1192 }
1193
1194 if (!base_delta_set) {
1195 if (orig_base_offset_set && base_offset_set) {
1196 base_delta_set = true;
1197 base_delta = base_offset - orig_base_offset;
1198 } else if (!patched_image_filename.empty()) {
Alex Light0eb76d22015-08-11 18:03:47 -07001199 if (have_image_files) {
1200 Usage("--patched-image-location should not be used when patching other images");
1201 }
Alex Light53cb16b2014-06-12 11:26:29 -07001202 base_delta_set = true;
Alex Light0eb76d22015-08-11 18:03:47 -07001203 match_delta = true;
Alex Light53cb16b2014-06-12 11:26:29 -07001204 std::string error_msg;
Alex Lighteefbe392014-07-08 09:53:18 -07001205 if (!ReadBaseDelta(patched_image_filename.c_str(), &base_delta, &error_msg)) {
Alex Light53cb16b2014-06-12 11:26:29 -07001206 Usage(error_msg.c_str(), patched_image_filename.c_str());
1207 }
1208 } else {
1209 if (base_offset_set) {
1210 Usage("Unable to determine original base offset.");
1211 } else {
1212 Usage("Must supply a desired new offset or delta.");
1213 }
1214 }
1215 }
1216
1217 if (!IsAligned<kPageSize>(base_delta)) {
1218 Usage("Base offset/delta must be alligned to a pagesize (0x%08x) boundary.", kPageSize);
1219 }
1220
1221 // Do we need to cleanup output files if we fail?
1222 bool new_image_out = false;
1223 bool new_oat_out = false;
1224
1225 std::unique_ptr<File> input_oat;
1226 std::unique_ptr<File> output_oat;
1227 std::unique_ptr<File> output_image;
1228
1229 if (have_image_files) {
1230 CHECK(!input_image_location.empty());
1231
1232 if (output_image_fd != -1) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001233 if (output_image_filename.empty()) {
1234 output_image_filename = "output-image-file";
1235 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001236 output_image.reset(new File(output_image_fd, output_image_filename, true));
Alex Light53cb16b2014-06-12 11:26:29 -07001237 } else {
1238 CHECK(!output_image_filename.empty());
1239 output_image.reset(CreateOrOpen(output_image_filename.c_str(), &new_image_out));
1240 }
1241 } else {
1242 CHECK(output_image_filename.empty() && output_image_fd == -1 && input_image_location.empty());
1243 }
1244
1245 if (have_oat_files) {
1246 if (input_oat_fd != -1) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001247 if (input_oat_filename.empty()) {
1248 input_oat_filename = "input-oat-file";
1249 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001250 input_oat.reset(new File(input_oat_fd, input_oat_filename, false));
Julien Delayena473f512015-03-05 16:37:52 +01001251 if (input_oat_fd == output_oat_fd) {
1252 input_oat.get()->DisableAutoClose();
1253 }
Igor Murashkin46774762014-10-22 11:37:02 -07001254 if (input_oat == nullptr) {
1255 // Unlikely, but ensure exhaustive logging in non-0 exit code case
1256 LOG(ERROR) << "Failed to open input oat file by its FD" << input_oat_fd;
1257 }
Alex Light53cb16b2014-06-12 11:26:29 -07001258 } else {
1259 CHECK(!input_oat_filename.empty());
1260 input_oat.reset(OS::OpenFileForReading(input_oat_filename.c_str()));
Igor Murashkin46774762014-10-22 11:37:02 -07001261 if (input_oat == nullptr) {
1262 int err = errno;
1263 LOG(ERROR) << "Failed to open input oat file " << input_oat_filename
1264 << ": " << strerror(err) << "(" << err << ")";
Andreas Gampe1c83cbc2014-07-22 18:52:29 -07001265 }
Alex Light53cb16b2014-06-12 11:26:29 -07001266 }
1267
1268 if (output_oat_fd != -1) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001269 if (output_oat_filename.empty()) {
1270 output_oat_filename = "output-oat-file";
Alex Lighta59dd802014-07-02 16:28:08 -07001271 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001272 output_oat.reset(new File(output_oat_fd, output_oat_filename, true));
Igor Murashkin46774762014-10-22 11:37:02 -07001273 if (output_oat == nullptr) {
1274 // Unlikely, but ensure exhaustive logging in non-0 exit code case
1275 LOG(ERROR) << "Failed to open output oat file by its FD" << output_oat_fd;
1276 }
Alex Light53cb16b2014-06-12 11:26:29 -07001277 } else {
1278 CHECK(!output_oat_filename.empty());
1279 output_oat.reset(CreateOrOpen(output_oat_filename.c_str(), &new_oat_out));
Igor Murashkin46774762014-10-22 11:37:02 -07001280 if (output_oat == nullptr) {
1281 int err = errno;
1282 LOG(ERROR) << "Failed to open output oat file " << output_oat_filename
1283 << ": " << strerror(err) << "(" << err << ")";
1284 }
Alex Light53cb16b2014-06-12 11:26:29 -07001285 }
1286 }
1287
Igor Murashkin46774762014-10-22 11:37:02 -07001288 // TODO: get rid of this.
Alex Light53cb16b2014-06-12 11:26:29 -07001289 auto cleanup = [&output_image_filename, &output_oat_filename,
1290 &new_oat_out, &new_image_out, &timings, &dump_timings](bool success) {
1291 timings.EndTiming();
1292 if (!success) {
1293 if (new_oat_out) {
1294 CHECK(!output_oat_filename.empty());
Brian Carlstrom8c52a3f2014-09-30 16:18:01 -07001295 TEMP_FAILURE_RETRY(unlink(output_oat_filename.c_str()));
Alex Light53cb16b2014-06-12 11:26:29 -07001296 }
1297 if (new_image_out) {
1298 CHECK(!output_image_filename.empty());
Brian Carlstrom8c52a3f2014-09-30 16:18:01 -07001299 TEMP_FAILURE_RETRY(unlink(output_image_filename.c_str()));
Alex Light53cb16b2014-06-12 11:26:29 -07001300 }
1301 }
1302 if (dump_timings) {
1303 LOG(INFO) << Dumpable<TimingLogger>(timings);
1304 }
Igor Murashkin46774762014-10-22 11:37:02 -07001305
1306 if (kIsDebugBuild) {
1307 LOG(INFO) << "Cleaning up.. success? " << success;
1308 }
Alex Light53cb16b2014-06-12 11:26:29 -07001309 };
1310
Igor Murashkin46774762014-10-22 11:37:02 -07001311 if (have_oat_files && (input_oat.get() == nullptr || output_oat.get() == nullptr)) {
1312 LOG(ERROR) << "Failed to open input/output oat files";
1313 cleanup(false);
1314 return EXIT_FAILURE;
1315 } else if (have_image_files && output_image.get() == nullptr) {
1316 LOG(ERROR) << "Failed to open output image file";
Alex Lightcf4bf382014-07-24 11:29:14 -07001317 cleanup(false);
1318 return EXIT_FAILURE;
1319 }
1320
Alex Light0eb76d22015-08-11 18:03:47 -07001321 if (match_delta) {
1322 CHECK(!have_image_files); // We will not do this with images.
1323 std::string error_msg;
1324 // Figure out what the current delta is so we can match it to the desired delta.
1325 std::unique_ptr<ElfFile> elf(ElfFile::Open(input_oat.get(), PROT_READ, MAP_PRIVATE,
1326 &error_msg));
1327 off_t current_delta = 0;
1328 if (elf.get() == nullptr) {
1329 LOG(ERROR) << "unable to open oat file " << input_oat->GetPath() << " : " << error_msg;
1330 cleanup(false);
1331 return EXIT_FAILURE;
1332 } else if (!ReadOatPatchDelta(elf.get(), &current_delta, &error_msg)) {
1333 LOG(ERROR) << "Unable to get current delta: " << error_msg;
1334 cleanup(false);
1335 return EXIT_FAILURE;
1336 }
1337 // Before this line base_delta is the desired final delta. We need it to be the actual amount to
1338 // change everything by. We subtract the current delta from it to make it this.
1339 base_delta -= current_delta;
1340 if (!IsAligned<kPageSize>(base_delta)) {
1341 LOG(ERROR) << "Given image file was relocated by an illegal delta";
1342 cleanup(false);
1343 return false;
1344 }
1345 }
1346
Igor Murashkin46774762014-10-22 11:37:02 -07001347 if (debug) {
1348 LOG(INFO) << "moving offset by " << base_delta
1349 << " (0x" << std::hex << base_delta << ") bytes or "
1350 << std::dec << (base_delta/kPageSize) << " pages.";
1351 }
1352
1353 // TODO: is it going to be promatic to unlink a file that was flock-ed?
Alex Lightcf4bf382014-07-24 11:29:14 -07001354 ScopedFlock output_oat_lock;
1355 if (lock_output) {
1356 std::string error_msg;
1357 if (have_oat_files && !output_oat_lock.Init(output_oat.get(), &error_msg)) {
1358 LOG(ERROR) << "Unable to lock output oat " << output_image->GetPath() << ": " << error_msg;
1359 cleanup(false);
1360 return EXIT_FAILURE;
1361 }
1362 }
1363
Alex Light53cb16b2014-06-12 11:26:29 -07001364 bool ret;
1365 if (have_image_files && have_oat_files) {
1366 TimingLogger::ScopedTiming pt("patch image and oat", &timings);
1367 ret = PatchOat::Patch(input_oat.get(), input_image_location, base_delta,
Igor Murashkin46774762014-10-22 11:37:02 -07001368 output_oat.get(), output_image.get(), isa, &timings,
1369 output_oat_fd >= 0, // was it opened from FD?
1370 new_oat_out);
Andreas Gampe4303ba92014-11-06 01:00:46 -08001371 // The order here doesn't matter. If the first one is successfully saved and the second one
1372 // erased, ImageSpace will still detect a problem and not use the files.
Alex Light0eb76d22015-08-11 18:03:47 -07001373 ret = FinishFile(output_image.get(), ret);
1374 ret = FinishFile(output_oat.get(), ret);
Alex Light53cb16b2014-06-12 11:26:29 -07001375 } else if (have_oat_files) {
1376 TimingLogger::ScopedTiming pt("patch oat", &timings);
Igor Murashkin46774762014-10-22 11:37:02 -07001377 ret = PatchOat::Patch(input_oat.get(), base_delta, output_oat.get(), &timings,
1378 output_oat_fd >= 0, // was it opened from FD?
1379 new_oat_out);
Alex Light0eb76d22015-08-11 18:03:47 -07001380 ret = FinishFile(output_oat.get(), ret);
Igor Murashkin46774762014-10-22 11:37:02 -07001381 } else if (have_image_files) {
Alex Light53cb16b2014-06-12 11:26:29 -07001382 TimingLogger::ScopedTiming pt("patch image", &timings);
Alex Lighteefbe392014-07-08 09:53:18 -07001383 ret = PatchOat::Patch(input_image_location, base_delta, output_image.get(), isa, &timings);
Alex Light0eb76d22015-08-11 18:03:47 -07001384 ret = FinishFile(output_image.get(), ret);
Igor Murashkin46774762014-10-22 11:37:02 -07001385 } else {
1386 CHECK(false);
1387 ret = true;
1388 }
1389
1390 if (kIsDebugBuild) {
1391 LOG(INFO) << "Exiting with return ... " << ret;
Alex Light53cb16b2014-06-12 11:26:29 -07001392 }
1393 cleanup(ret);
Alex Light53cb16b2014-06-12 11:26:29 -07001394 return (ret) ? EXIT_SUCCESS : EXIT_FAILURE;
1395}
1396
1397} // namespace art
1398
1399int main(int argc, char **argv) {
1400 return art::patchoat(argc, argv);
1401}