blob: 6cd391fcad60a8e2f0f5b64cff63d21261700989 [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 const size_t method_size = ArtMethod::ObjectSize(pointer_size);
484 PatchOatArtMethodVisitor visitor(this);
485 section.VisitPackedArtMethods(&visitor, heap_->Begin(), method_size);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700486}
487
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700488class FixupRootVisitor : public RootVisitor {
489 public:
490 explicit FixupRootVisitor(const PatchOat* patch_oat) : patch_oat_(patch_oat) {
491 }
492
493 void VisitRoots(mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -0700494 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700495 for (size_t i = 0; i < count; ++i) {
496 *roots[i] = patch_oat_->RelocatedAddressOfPointer(*roots[i]);
497 }
498 }
499
500 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots, size_t count,
501 const RootInfo& info ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -0700502 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700503 for (size_t i = 0; i < count; ++i) {
504 roots[i]->Assign(patch_oat_->RelocatedAddressOfPointer(roots[i]->AsMirrorPtr()));
505 }
506 }
507
508 private:
509 const PatchOat* const patch_oat_;
510};
511
512void PatchOat::PatchInternedStrings(const ImageHeader* image_header) {
513 const auto& section = image_header->GetImageSection(ImageHeader::kSectionInternedStrings);
514 InternTable temp_table;
515 // Note that we require that ReadFromMemory does not make an internal copy of the elements.
516 // This also relies on visit roots not doing any verification which could fail after we update
517 // the roots to be the image addresses.
518 temp_table.ReadFromMemory(image_->Begin() + section.Offset());
519 FixupRootVisitor visitor(this);
520 temp_table.VisitRoots(&visitor, kVisitRootFlagAllRoots);
521}
522
Mathieu Chartierc7853442015-03-27 14:35:38 -0700523void PatchOat::PatchDexFileArrays(mirror::ObjectArray<mirror::Object>* img_roots) {
524 auto* dex_caches = down_cast<mirror::ObjectArray<mirror::DexCache>*>(
525 img_roots->Get(ImageHeader::kDexCaches));
526 for (size_t i = 0, count = dex_caches->GetLength(); i < count; ++i) {
527 auto* dex_cache = dex_caches->GetWithoutChecks(i);
528 auto* fields = dex_cache->GetResolvedFields();
Mathieu Chartiere401d142015-04-22 13:56:20 -0700529 if (fields != nullptr) {
530 CHECK(!fields->IsObjectArray());
531 CHECK(fields->IsArrayInstance());
532 FixupNativePointerArray(fields);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700533 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700534 auto* methods = dex_cache->GetResolvedMethods();
535 if (methods != nullptr) {
536 CHECK(!methods->IsObjectArray());
537 CHECK(methods->IsArrayInstance());
538 FixupNativePointerArray(methods);
539 }
540 }
541}
542
543void PatchOat::FixupNativePointerArray(mirror::PointerArray* object) {
544 if (object->IsIntArray()) {
545 mirror::IntArray* arr = object->AsIntArray();
546 mirror::IntArray* copy_arr = down_cast<mirror::IntArray*>(RelocatedCopyOf(arr));
547 for (size_t j = 0, count2 = arr->GetLength(); j < count2; ++j) {
548 copy_arr->SetWithoutChecks<false>(
549 j, RelocatedAddressOfIntPointer(arr->GetWithoutChecks(j)));
550 }
551 } else {
552 CHECK(object->IsLongArray());
553 mirror::LongArray* arr = object->AsLongArray();
554 mirror::LongArray* copy_arr = down_cast<mirror::LongArray*>(RelocatedCopyOf(arr));
555 for (size_t j = 0, count2 = arr->GetLength(); j < count2; ++j) {
556 copy_arr->SetWithoutChecks<false>(
557 j, RelocatedAddressOfIntPointer(arr->GetWithoutChecks(j)));
Mathieu Chartierc7853442015-03-27 14:35:38 -0700558 }
559 }
560}
561
Alex Light53cb16b2014-06-12 11:26:29 -0700562bool PatchOat::PatchImage() {
563 ImageHeader* image_header = reinterpret_cast<ImageHeader*>(image_->Begin());
564 CHECK_GT(image_->Size(), sizeof(ImageHeader));
565 // These are the roots from the original file.
Mathieu Chartierc7853442015-03-27 14:35:38 -0700566 auto* img_roots = image_header->GetImageRoots();
Alex Light53cb16b2014-06-12 11:26:29 -0700567 image_header->RelocateImage(delta_);
568
Mathieu Chartierc7853442015-03-27 14:35:38 -0700569 PatchArtFields(image_header);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700570 PatchArtMethods(image_header);
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700571 PatchInternedStrings(image_header);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700572 // Patch dex file int/long arrays which point to ArtFields.
573 PatchDexFileArrays(img_roots);
574
Alex Light53cb16b2014-06-12 11:26:29 -0700575 VisitObject(img_roots);
576 if (!image_header->IsValid()) {
577 LOG(ERROR) << "reloction renders image header invalid";
578 return false;
579 }
580
581 {
Alex Lighteefbe392014-07-08 09:53:18 -0700582 TimingLogger::ScopedTiming t("Walk Bitmap", timings_);
Alex Light53cb16b2014-06-12 11:26:29 -0700583 // Walk the bitmap.
584 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
585 bitmap_->Walk(PatchOat::BitmapCallback, this);
586 }
587 return true;
588}
589
590bool PatchOat::InHeap(mirror::Object* o) {
591 uintptr_t begin = reinterpret_cast<uintptr_t>(heap_->Begin());
592 uintptr_t end = reinterpret_cast<uintptr_t>(heap_->End());
593 uintptr_t obj = reinterpret_cast<uintptr_t>(o);
594 return o == nullptr || (begin <= obj && obj < end);
595}
596
597void PatchOat::PatchVisitor::operator() (mirror::Object* obj, MemberOffset off,
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700598 bool is_static_unused ATTRIBUTE_UNUSED) const {
Alex Light53cb16b2014-06-12 11:26:29 -0700599 mirror::Object* referent = obj->GetFieldObject<mirror::Object, kVerifyNone>(off);
600 DCHECK(patcher_->InHeap(referent)) << "Referent is not in the heap.";
Mathieu Chartierc7853442015-03-27 14:35:38 -0700601 mirror::Object* moved_object = patcher_->RelocatedAddressOfPointer(referent);
Alex Light53cb16b2014-06-12 11:26:29 -0700602 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(off, moved_object);
603}
604
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700605void PatchOat::PatchVisitor::operator() (mirror::Class* cls ATTRIBUTE_UNUSED,
606 mirror::Reference* ref) const {
Alex Light53cb16b2014-06-12 11:26:29 -0700607 MemberOffset off = mirror::Reference::ReferentOffset();
608 mirror::Object* referent = ref->GetReferent();
609 DCHECK(patcher_->InHeap(referent)) << "Referent is not in the heap.";
Mathieu Chartierc7853442015-03-27 14:35:38 -0700610 mirror::Object* moved_object = patcher_->RelocatedAddressOfPointer(referent);
Alex Light53cb16b2014-06-12 11:26:29 -0700611 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(off, moved_object);
612}
613
Alex Light53cb16b2014-06-12 11:26:29 -0700614// Called by BitmapCallback
615void PatchOat::VisitObject(mirror::Object* object) {
616 mirror::Object* copy = RelocatedCopyOf(object);
617 CHECK(copy != nullptr);
618 if (kUseBakerOrBrooksReadBarrier) {
619 object->AssertReadBarrierPointer();
620 if (kUseBrooksReadBarrier) {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700621 mirror::Object* moved_to = RelocatedAddressOfPointer(object);
Alex Light53cb16b2014-06-12 11:26:29 -0700622 copy->SetReadBarrierPointer(moved_to);
623 DCHECK_EQ(copy->GetReadBarrierPointer(), moved_to);
624 }
625 }
626 PatchOat::PatchVisitor visitor(this, copy);
627 object->VisitReferences<true, kVerifyNone>(visitor, visitor);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700628 if (object->IsClass<kVerifyNone>()) {
629 auto* klass = object->AsClass();
630 auto* copy_klass = down_cast<mirror::Class*>(copy);
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700631 copy_klass->SetSFieldsPtrUnchecked(RelocatedAddressOfPointer(klass->GetSFieldsPtr()));
632 copy_klass->SetIFieldsPtrUnchecked(RelocatedAddressOfPointer(klass->GetIFieldsPtr()));
Mathieu Chartiere401d142015-04-22 13:56:20 -0700633 copy_klass->SetDirectMethodsPtrUnchecked(
634 RelocatedAddressOfPointer(klass->GetDirectMethodsPtr()));
635 copy_klass->SetVirtualMethodsPtr(RelocatedAddressOfPointer(klass->GetVirtualMethodsPtr()));
636 auto* vtable = klass->GetVTable();
637 if (vtable != nullptr) {
638 FixupNativePointerArray(vtable);
639 }
640 auto* iftable = klass->GetIfTable();
641 if (iftable != nullptr) {
642 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
643 if (iftable->GetMethodArrayCount(i) > 0) {
644 auto* method_array = iftable->GetMethodArray(i);
645 CHECK(method_array != nullptr);
646 FixupNativePointerArray(method_array);
647 }
648 }
649 }
650 if (klass->ShouldHaveEmbeddedImtAndVTable()) {
651 const size_t pointer_size = InstructionSetPointerSize(isa_);
652 for (int32_t i = 0; i < klass->GetEmbeddedVTableLength(); ++i) {
653 copy_klass->SetEmbeddedVTableEntryUnchecked(i, RelocatedAddressOfPointer(
654 klass->GetEmbeddedVTableEntry(i, pointer_size)), pointer_size);
655 }
656 for (size_t i = 0; i < mirror::Class::kImtSize; ++i) {
657 copy_klass->SetEmbeddedImTableEntry(i, RelocatedAddressOfPointer(
658 klass->GetEmbeddedImTableEntry(i, pointer_size)), pointer_size);
659 }
660 }
661 }
662 if (object->GetClass() == mirror::Method::StaticClass() ||
663 object->GetClass() == mirror::Constructor::StaticClass()) {
664 // Need to go update the ArtMethod.
665 auto* dest = down_cast<mirror::AbstractMethod*>(copy);
666 auto* src = down_cast<mirror::AbstractMethod*>(object);
667 dest->SetArtMethod(RelocatedAddressOfPointer(src->GetArtMethod()));
Alex Light53cb16b2014-06-12 11:26:29 -0700668 }
669}
670
Mathieu Chartiere401d142015-04-22 13:56:20 -0700671void PatchOat::FixupMethod(ArtMethod* object, ArtMethod* copy) {
Mathieu Chartier2d721012014-11-10 11:08:06 -0800672 const size_t pointer_size = InstructionSetPointerSize(isa_);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700673 copy->CopyFrom(object, pointer_size);
Alex Light53cb16b2014-06-12 11:26:29 -0700674 // Just update the entry points if it looks like we should.
Alex Lighteefbe392014-07-08 09:53:18 -0700675 // TODO: sanity check all the pointers' values
Mathieu Chartiere401d142015-04-22 13:56:20 -0700676 copy->SetDeclaringClass(RelocatedAddressOfPointer(object->GetDeclaringClass()));
677 copy->SetDexCacheResolvedMethods(RelocatedAddressOfPointer(object->GetDexCacheResolvedMethods()));
678 copy->SetDexCacheResolvedTypes(RelocatedAddressOfPointer(object->GetDexCacheResolvedTypes()));
679 copy->SetEntryPointFromQuickCompiledCodePtrSize(RelocatedAddressOfPointer(
680 object->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size)), pointer_size);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700681 copy->SetEntryPointFromJniPtrSize(RelocatedAddressOfPointer(
682 object->GetEntryPointFromJniPtrSize(pointer_size)), pointer_size);
Alex Light53cb16b2014-06-12 11:26:29 -0700683}
684
Igor Murashkin46774762014-10-22 11:37:02 -0700685bool PatchOat::Patch(File* input_oat, off_t delta, File* output_oat, TimingLogger* timings,
686 bool output_oat_opened_from_fd, bool new_oat_out) {
Alex Light53cb16b2014-06-12 11:26:29 -0700687 CHECK(input_oat != nullptr);
688 CHECK(output_oat != nullptr);
689 CHECK_GE(input_oat->Fd(), 0);
690 CHECK_GE(output_oat->Fd(), 0);
Alex Lighteefbe392014-07-08 09:53:18 -0700691 TimingLogger::ScopedTiming t("Setup Oat File Patching", timings);
Alex Light53cb16b2014-06-12 11:26:29 -0700692
693 std::string error_msg;
Igor Murashkin46774762014-10-22 11:37:02 -0700694 std::unique_ptr<ElfFile> elf(ElfFile::Open(input_oat,
Alex Light53cb16b2014-06-12 11:26:29 -0700695 PROT_READ | PROT_WRITE, MAP_PRIVATE, &error_msg));
696 if (elf.get() == nullptr) {
697 LOG(ERROR) << "unable to open oat file " << input_oat->GetPath() << " : " << error_msg;
698 return false;
699 }
700
Igor Murashkin46774762014-10-22 11:37:02 -0700701 MaybePic is_oat_pic = IsOatPic(elf.get());
702 if (is_oat_pic >= ERROR_FIRST) {
703 // Error logged by IsOatPic
704 return false;
705 } else if (is_oat_pic == PIC) {
706 // Do not need to do ELF-file patching. Create a symlink and skip the rest.
707 // Any errors will be logged by the function call.
708 return ReplaceOatFileWithSymlink(input_oat->GetPath(),
709 output_oat->GetPath(),
710 output_oat_opened_from_fd,
711 new_oat_out);
712 } else {
713 CHECK(is_oat_pic == NOT_PIC);
714 }
715
Alex Light53cb16b2014-06-12 11:26:29 -0700716 PatchOat p(elf.release(), delta, timings);
717 t.NewTiming("Patch Oat file");
718 if (!p.PatchElf()) {
719 return false;
720 }
721
722 t.NewTiming("Writing oat file");
723 if (!p.WriteElf(output_oat)) {
724 return false;
725 }
726 return true;
727}
728
Tong Shen62d1ca32014-09-03 17:24:56 -0700729template <typename ElfFileImpl>
730bool PatchOat::PatchOatHeader(ElfFileImpl* oat_file) {
731 auto rodata_sec = oat_file->FindSectionByName(".rodata");
Alex Lighta59dd802014-07-02 16:28:08 -0700732 if (rodata_sec == nullptr) {
733 return false;
734 }
Tong Shen62d1ca32014-09-03 17:24:56 -0700735 OatHeader* oat_header = reinterpret_cast<OatHeader*>(oat_file->Begin() + rodata_sec->sh_offset);
Alex Lighta59dd802014-07-02 16:28:08 -0700736 if (!oat_header->IsValid()) {
Tong Shen62d1ca32014-09-03 17:24:56 -0700737 LOG(ERROR) << "Elf file " << oat_file->GetFile().GetPath() << " has an invalid oat header";
Alex Lighta59dd802014-07-02 16:28:08 -0700738 return false;
739 }
740 oat_header->RelocateOat(delta_);
741 return true;
742}
743
Alex Light53cb16b2014-06-12 11:26:29 -0700744bool PatchOat::PatchElf() {
Ian Rogersd4c4d952014-10-16 20:31:53 -0700745 if (oat_file_->Is64Bit())
Tong Shen62d1ca32014-09-03 17:24:56 -0700746 return PatchElf<ElfFileImpl64>(oat_file_->GetImpl64());
747 else
748 return PatchElf<ElfFileImpl32>(oat_file_->GetImpl32());
749}
750
751template <typename ElfFileImpl>
752bool PatchOat::PatchElf(ElfFileImpl* oat_file) {
Alex Lighta59dd802014-07-02 16:28:08 -0700753 TimingLogger::ScopedTiming t("Fixup Elf Text Section", timings_);
Vladimir Marko3fc99032015-05-13 19:06:30 +0100754
755 // Fix up absolute references to locations within the boot image.
David Srbecky2f6cdb02015-04-11 00:17:53 +0100756 if (!oat_file->ApplyOatPatchesTo(".text", delta_)) {
Alex Lighta59dd802014-07-02 16:28:08 -0700757 return false;
758 }
759
Vladimir Marko3fc99032015-05-13 19:06:30 +0100760 // Update the OatHeader fields referencing the boot image.
Tong Shen62d1ca32014-09-03 17:24:56 -0700761 if (!PatchOatHeader<ElfFileImpl>(oat_file)) {
Alex Lighta59dd802014-07-02 16:28:08 -0700762 return false;
763 }
764
Vladimir Marko3fc99032015-05-13 19:06:30 +0100765 bool need_boot_oat_fixup = true;
Ian Rogersd4c4d952014-10-16 20:31:53 -0700766 for (unsigned int i = 0; i < oat_file->GetProgramHeaderNum(); ++i) {
Tong Shen62d1ca32014-09-03 17:24:56 -0700767 auto hdr = oat_file->GetProgramHeader(i);
Vladimir Marko3fc99032015-05-13 19:06:30 +0100768 if (hdr->p_type == PT_LOAD && hdr->p_vaddr == 0u) {
769 need_boot_oat_fixup = false;
Ian Rogersd4c4d952014-10-16 20:31:53 -0700770 break;
Alex Light53cb16b2014-06-12 11:26:29 -0700771 }
772 }
Vladimir Marko3fc99032015-05-13 19:06:30 +0100773 if (!need_boot_oat_fixup) {
774 // This is an app oat file that can be loaded at an arbitrary address in memory.
775 // Boot image references were patched above and there's nothing else to do.
Alex Lighta59dd802014-07-02 16:28:08 -0700776 return true;
777 }
Tong Shen62d1ca32014-09-03 17:24:56 -0700778
Vladimir Marko3fc99032015-05-13 19:06:30 +0100779 // This is a boot oat file that's loaded at a particular address and we need
780 // to patch all absolute addresses, starting with ELF program headers.
781
Tong Shen62d1ca32014-09-03 17:24:56 -0700782 t.NewTiming("Fixup Elf Headers");
783 // Fixup Phdr's
784 oat_file->FixupProgramHeaders(delta_);
785
Alex Lighta59dd802014-07-02 16:28:08 -0700786 t.NewTiming("Fixup Section Headers");
Tong Shen62d1ca32014-09-03 17:24:56 -0700787 // Fixup Shdr's
788 oat_file->FixupSectionHeaders(delta_);
Alex Light53cb16b2014-06-12 11:26:29 -0700789
Alex Lighta59dd802014-07-02 16:28:08 -0700790 t.NewTiming("Fixup Dynamics");
Tong Shen62d1ca32014-09-03 17:24:56 -0700791 oat_file->FixupDynamic(delta_);
Alex Light53cb16b2014-06-12 11:26:29 -0700792
793 t.NewTiming("Fixup Elf Symbols");
794 // Fixup dynsym
Tong Shen62d1ca32014-09-03 17:24:56 -0700795 if (!oat_file->FixupSymbols(delta_, true)) {
Alex Light53cb16b2014-06-12 11:26:29 -0700796 return false;
797 }
Alex Light53cb16b2014-06-12 11:26:29 -0700798 // Fixup symtab
Tong Shen62d1ca32014-09-03 17:24:56 -0700799 if (!oat_file->FixupSymbols(delta_, false)) {
800 return false;
Alex Light53cb16b2014-06-12 11:26:29 -0700801 }
802
Yevgeny Roubane3ea8382014-08-08 16:29:38 +0700803 t.NewTiming("Fixup Debug Sections");
Tong Shen62d1ca32014-09-03 17:24:56 -0700804 if (!oat_file->FixupDebugSections(delta_)) {
Yevgeny Roubane3ea8382014-08-08 16:29:38 +0700805 return false;
806 }
807
Alex Light53cb16b2014-06-12 11:26:29 -0700808 return true;
809}
810
Alex Light53cb16b2014-06-12 11:26:29 -0700811static int orig_argc;
812static char** orig_argv;
813
814static std::string CommandLine() {
815 std::vector<std::string> command;
816 for (int i = 0; i < orig_argc; ++i) {
817 command.push_back(orig_argv[i]);
818 }
819 return Join(command, ' ');
820}
821
822static void UsageErrorV(const char* fmt, va_list ap) {
823 std::string error;
824 StringAppendV(&error, fmt, ap);
825 LOG(ERROR) << error;
826}
827
828static void UsageError(const char* fmt, ...) {
829 va_list ap;
830 va_start(ap, fmt);
831 UsageErrorV(fmt, ap);
832 va_end(ap);
833}
834
Andreas Gampe794ad762015-02-23 08:12:24 -0800835NO_RETURN static void Usage(const char *fmt, ...) {
Alex Light53cb16b2014-06-12 11:26:29 -0700836 va_list ap;
837 va_start(ap, fmt);
838 UsageErrorV(fmt, ap);
839 va_end(ap);
840
841 UsageError("Command: %s", CommandLine().c_str());
842 UsageError("Usage: patchoat [options]...");
843 UsageError("");
844 UsageError(" --instruction-set=<isa>: Specifies the instruction set the patched code is");
845 UsageError(" compiled for. Required if you use --input-oat-location");
846 UsageError("");
847 UsageError(" --input-oat-file=<file.oat>: Specifies the exact filename of the oat file to be");
848 UsageError(" patched.");
849 UsageError("");
850 UsageError(" --input-oat-fd=<file-descriptor>: Specifies the file-descriptor of the oat file");
851 UsageError(" to be patched.");
852 UsageError("");
853 UsageError(" --input-oat-location=<file.oat>: Specifies the 'location' to read the patched");
854 UsageError(" oat file from. If used one must also supply the --instruction-set");
855 UsageError("");
856 UsageError(" --input-image-location=<file.art>: Specifies the 'location' of the image file to");
857 UsageError(" be patched. If --instruction-set is not given it will use the instruction set");
858 UsageError(" extracted from the --input-oat-file.");
859 UsageError("");
860 UsageError(" --output-oat-file=<file.oat>: Specifies the exact file to write the patched oat");
861 UsageError(" file to.");
862 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700863 UsageError(" --output-oat-fd=<file-descriptor>: Specifies the file-descriptor to write the");
864 UsageError(" the patched oat file to.");
865 UsageError("");
866 UsageError(" --output-image-file=<file.art>: Specifies the exact file to write the patched");
867 UsageError(" image file to.");
868 UsageError("");
869 UsageError(" --output-image-fd=<file-descriptor>: Specifies the file-descriptor to write the");
870 UsageError(" the patched image file to.");
871 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700872 UsageError(" --orig-base-offset=<original-base-offset>: Specify the base offset the input file");
873 UsageError(" was compiled with. This is needed if one is specifying a --base-offset");
874 UsageError("");
875 UsageError(" --base-offset=<new-base-offset>: Specify the base offset we will repatch the");
876 UsageError(" given files to use. This requires that --orig-base-offset is also given.");
877 UsageError("");
878 UsageError(" --base-offset-delta=<delta>: Specify the amount to change the old base-offset by.");
879 UsageError(" This value may be negative.");
880 UsageError("");
Alex Light0eb76d22015-08-11 18:03:47 -0700881 UsageError(" --patched-image-file=<file.art>: Relocate the oat file to be the same as the");
882 UsageError(" given image file.");
Alex Light53cb16b2014-06-12 11:26:29 -0700883 UsageError("");
Alex Light0eb76d22015-08-11 18:03:47 -0700884 UsageError(" --patched-image-location=<file.art>: Relocate the oat file to be the same as the");
885 UsageError(" image at the given location. If used one must also specify the");
Alex Lighta59dd802014-07-02 16:28:08 -0700886 UsageError(" --instruction-set flag. It will search for this image in the same way that");
887 UsageError(" is done when loading one.");
Alex Light53cb16b2014-06-12 11:26:29 -0700888 UsageError("");
Alex Lightcf4bf382014-07-24 11:29:14 -0700889 UsageError(" --lock-output: Obtain a flock on output oat file before starting.");
890 UsageError("");
891 UsageError(" --no-lock-output: Do not attempt to obtain a flock on output oat file.");
892 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700893 UsageError(" --dump-timings: dump out patch timing information");
894 UsageError("");
895 UsageError(" --no-dump-timings: do not dump out patch timing information");
896 UsageError("");
897
898 exit(EXIT_FAILURE);
899}
900
Alex Lighteefbe392014-07-08 09:53:18 -0700901static bool ReadBaseDelta(const char* name, off_t* delta, std::string* error_msg) {
Alex Light53cb16b2014-06-12 11:26:29 -0700902 CHECK(name != nullptr);
903 CHECK(delta != nullptr);
904 std::unique_ptr<File> file;
905 if (OS::FileExists(name)) {
906 file.reset(OS::OpenFileForReading(name));
907 if (file.get() == nullptr) {
Alex Lighteefbe392014-07-08 09:53:18 -0700908 *error_msg = "Failed to open file %s for reading";
Alex Light53cb16b2014-06-12 11:26:29 -0700909 return false;
910 }
911 } else {
Alex Lighteefbe392014-07-08 09:53:18 -0700912 *error_msg = "File %s does not exist";
Alex Light53cb16b2014-06-12 11:26:29 -0700913 return false;
914 }
915 CHECK(file.get() != nullptr);
916 ImageHeader hdr;
917 if (sizeof(hdr) != file->Read(reinterpret_cast<char*>(&hdr), sizeof(hdr), 0)) {
Alex Lighteefbe392014-07-08 09:53:18 -0700918 *error_msg = "Failed to read file %s";
Alex Light53cb16b2014-06-12 11:26:29 -0700919 return false;
920 }
921 if (!hdr.IsValid()) {
Alex Lighteefbe392014-07-08 09:53:18 -0700922 *error_msg = "%s does not contain a valid image header.";
Alex Light53cb16b2014-06-12 11:26:29 -0700923 return false;
924 }
925 *delta = hdr.GetPatchDelta();
926 return true;
927}
928
929static File* CreateOrOpen(const char* name, bool* created) {
930 if (OS::FileExists(name)) {
931 *created = false;
932 return OS::OpenFileReadWrite(name);
933 } else {
934 *created = true;
Alex Lightcf4bf382014-07-24 11:29:14 -0700935 std::unique_ptr<File> f(OS::CreateEmptyFile(name));
936 if (f.get() != nullptr) {
937 if (fchmod(f->Fd(), 0644) != 0) {
938 PLOG(ERROR) << "Unable to make " << name << " world readable";
Brian Carlstrom8c52a3f2014-09-30 16:18:01 -0700939 TEMP_FAILURE_RETRY(unlink(name));
Alex Lightcf4bf382014-07-24 11:29:14 -0700940 return nullptr;
941 }
942 }
943 return f.release();
Alex Light53cb16b2014-06-12 11:26:29 -0700944 }
945}
946
Andreas Gampe4303ba92014-11-06 01:00:46 -0800947// Either try to close the file (close=true), or erase it.
948static bool FinishFile(File* file, bool close) {
949 if (close) {
950 if (file->FlushCloseOrErase() != 0) {
951 PLOG(ERROR) << "Failed to flush and close file.";
952 return false;
953 }
954 return true;
955 } else {
956 file->Erase();
957 return false;
958 }
959}
960
Alex Lighteefbe392014-07-08 09:53:18 -0700961static int patchoat(int argc, char **argv) {
Alex Light53cb16b2014-06-12 11:26:29 -0700962 InitLogging(argv);
Mathieu Chartier6e88ef62014-10-14 15:01:24 -0700963 MemMap::Init();
Alex Light53cb16b2014-06-12 11:26:29 -0700964 const bool debug = kIsDebugBuild;
965 orig_argc = argc;
966 orig_argv = argv;
967 TimingLogger timings("patcher", false, false);
968
969 InitLogging(argv);
970
971 // Skip over the command name.
972 argv++;
973 argc--;
974
975 if (argc == 0) {
976 Usage("No arguments specified");
977 }
978
979 timings.StartTiming("Patchoat");
980
981 // cmd line args
982 bool isa_set = false;
983 InstructionSet isa = kNone;
984 std::string input_oat_filename;
985 std::string input_oat_location;
986 int input_oat_fd = -1;
987 bool have_input_oat = false;
988 std::string input_image_location;
989 std::string output_oat_filename;
Alex Light53cb16b2014-06-12 11:26:29 -0700990 int output_oat_fd = -1;
991 bool have_output_oat = false;
992 std::string output_image_filename;
Alex Light53cb16b2014-06-12 11:26:29 -0700993 int output_image_fd = -1;
994 bool have_output_image = false;
995 uintptr_t base_offset = 0;
996 bool base_offset_set = false;
997 uintptr_t orig_base_offset = 0;
998 bool orig_base_offset_set = false;
999 off_t base_delta = 0;
1000 bool base_delta_set = false;
Alex Light0eb76d22015-08-11 18:03:47 -07001001 bool match_delta = false;
Alex Light53cb16b2014-06-12 11:26:29 -07001002 std::string patched_image_filename;
1003 std::string patched_image_location;
1004 bool dump_timings = kIsDebugBuild;
Alex Lightcf4bf382014-07-24 11:29:14 -07001005 bool lock_output = true;
Alex Light53cb16b2014-06-12 11:26:29 -07001006
Ian Rogersd4c4d952014-10-16 20:31:53 -07001007 for (int i = 0; i < argc; ++i) {
Alex Light53cb16b2014-06-12 11:26:29 -07001008 const StringPiece option(argv[i]);
1009 const bool log_options = false;
1010 if (log_options) {
1011 LOG(INFO) << "patchoat: option[" << i << "]=" << argv[i];
1012 }
Alex Light53cb16b2014-06-12 11:26:29 -07001013 if (option.starts_with("--instruction-set=")) {
1014 isa_set = true;
1015 const char* isa_str = option.substr(strlen("--instruction-set=")).data();
Andreas Gampe20c89302014-08-19 17:28:06 -07001016 isa = GetInstructionSetFromString(isa_str);
1017 if (isa == kNone) {
1018 Usage("Unknown or invalid instruction set %s", isa_str);
Alex Light53cb16b2014-06-12 11:26:29 -07001019 }
1020 } else if (option.starts_with("--input-oat-location=")) {
1021 if (have_input_oat) {
1022 Usage("Only one of --input-oat-file, --input-oat-location and --input-oat-fd may be used.");
1023 }
1024 have_input_oat = true;
1025 input_oat_location = option.substr(strlen("--input-oat-location=")).data();
1026 } else if (option.starts_with("--input-oat-file=")) {
1027 if (have_input_oat) {
1028 Usage("Only one of --input-oat-file, --input-oat-location and --input-oat-fd may be used.");
1029 }
1030 have_input_oat = true;
1031 input_oat_filename = option.substr(strlen("--input-oat-file=")).data();
1032 } else if (option.starts_with("--input-oat-fd=")) {
1033 if (have_input_oat) {
1034 Usage("Only one of --input-oat-file, --input-oat-location and --input-oat-fd may be used.");
1035 }
1036 have_input_oat = true;
1037 const char* oat_fd_str = option.substr(strlen("--input-oat-fd=")).data();
1038 if (!ParseInt(oat_fd_str, &input_oat_fd)) {
1039 Usage("Failed to parse --input-oat-fd argument '%s' as an integer", oat_fd_str);
1040 }
1041 if (input_oat_fd < 0) {
1042 Usage("--input-oat-fd pass a negative value %d", input_oat_fd);
1043 }
1044 } else if (option.starts_with("--input-image-location=")) {
1045 input_image_location = option.substr(strlen("--input-image-location=")).data();
Alex Light53cb16b2014-06-12 11:26:29 -07001046 } else if (option.starts_with("--output-oat-file=")) {
1047 if (have_output_oat) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001048 Usage("Only one of --output-oat-file, and --output-oat-fd may be used.");
Alex Light53cb16b2014-06-12 11:26:29 -07001049 }
1050 have_output_oat = true;
1051 output_oat_filename = option.substr(strlen("--output-oat-file=")).data();
1052 } else if (option.starts_with("--output-oat-fd=")) {
1053 if (have_output_oat) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001054 Usage("Only one of --output-oat-file, --output-oat-fd may be used.");
Alex Light53cb16b2014-06-12 11:26:29 -07001055 }
1056 have_output_oat = true;
1057 const char* oat_fd_str = option.substr(strlen("--output-oat-fd=")).data();
1058 if (!ParseInt(oat_fd_str, &output_oat_fd)) {
1059 Usage("Failed to parse --output-oat-fd argument '%s' as an integer", oat_fd_str);
1060 }
1061 if (output_oat_fd < 0) {
1062 Usage("--output-oat-fd pass a negative value %d", output_oat_fd);
1063 }
Alex Light53cb16b2014-06-12 11:26:29 -07001064 } else if (option.starts_with("--output-image-file=")) {
1065 if (have_output_image) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001066 Usage("Only one of --output-image-file, and --output-image-fd may be used.");
Alex Light53cb16b2014-06-12 11:26:29 -07001067 }
1068 have_output_image = true;
1069 output_image_filename = option.substr(strlen("--output-image-file=")).data();
1070 } else if (option.starts_with("--output-image-fd=")) {
1071 if (have_output_image) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001072 Usage("Only one of --output-image-file, and --output-image-fd may be used.");
Alex Light53cb16b2014-06-12 11:26:29 -07001073 }
1074 have_output_image = true;
1075 const char* image_fd_str = option.substr(strlen("--output-image-fd=")).data();
1076 if (!ParseInt(image_fd_str, &output_image_fd)) {
1077 Usage("Failed to parse --output-image-fd argument '%s' as an integer", image_fd_str);
1078 }
1079 if (output_image_fd < 0) {
1080 Usage("--output-image-fd pass a negative value %d", output_image_fd);
1081 }
1082 } else if (option.starts_with("--orig-base-offset=")) {
1083 const char* orig_base_offset_str = option.substr(strlen("--orig-base-offset=")).data();
1084 orig_base_offset_set = true;
1085 if (!ParseUint(orig_base_offset_str, &orig_base_offset)) {
1086 Usage("Failed to parse --orig-base-offset argument '%s' as an uintptr_t",
1087 orig_base_offset_str);
1088 }
1089 } else if (option.starts_with("--base-offset=")) {
1090 const char* base_offset_str = option.substr(strlen("--base-offset=")).data();
1091 base_offset_set = true;
1092 if (!ParseUint(base_offset_str, &base_offset)) {
1093 Usage("Failed to parse --base-offset argument '%s' as an uintptr_t", base_offset_str);
1094 }
1095 } else if (option.starts_with("--base-offset-delta=")) {
1096 const char* base_delta_str = option.substr(strlen("--base-offset-delta=")).data();
1097 base_delta_set = true;
1098 if (!ParseInt(base_delta_str, &base_delta)) {
1099 Usage("Failed to parse --base-offset-delta argument '%s' as an off_t", base_delta_str);
1100 }
1101 } else if (option.starts_with("--patched-image-location=")) {
1102 patched_image_location = option.substr(strlen("--patched-image-location=")).data();
1103 } else if (option.starts_with("--patched-image-file=")) {
1104 patched_image_filename = option.substr(strlen("--patched-image-file=")).data();
Alex Lightcf4bf382014-07-24 11:29:14 -07001105 } else if (option == "--lock-output") {
1106 lock_output = true;
1107 } else if (option == "--no-lock-output") {
1108 lock_output = false;
Alex Light53cb16b2014-06-12 11:26:29 -07001109 } else if (option == "--dump-timings") {
1110 dump_timings = true;
1111 } else if (option == "--no-dump-timings") {
1112 dump_timings = false;
1113 } else {
1114 Usage("Unknown argument %s", option.data());
1115 }
1116 }
1117
1118 {
1119 // Only 1 of these may be set.
1120 uint32_t cnt = 0;
1121 cnt += (base_delta_set) ? 1 : 0;
1122 cnt += (base_offset_set && orig_base_offset_set) ? 1 : 0;
1123 cnt += (!patched_image_filename.empty()) ? 1 : 0;
1124 cnt += (!patched_image_location.empty()) ? 1 : 0;
1125 if (cnt > 1) {
1126 Usage("Only one of --base-offset/--orig-base-offset, --base-offset-delta, "
1127 "--patched-image-filename or --patched-image-location may be used.");
1128 } else if (cnt == 0) {
1129 Usage("Must specify --base-offset-delta, --base-offset and --orig-base-offset, "
1130 "--patched-image-location or --patched-image-file");
1131 }
1132 }
1133
1134 if (have_input_oat != have_output_oat) {
1135 Usage("Either both input and output oat must be supplied or niether must be.");
1136 }
1137
1138 if ((!input_image_location.empty()) != have_output_image) {
1139 Usage("Either both input and output image must be supplied or niether must be.");
1140 }
1141
1142 // We know we have both the input and output so rename for clarity.
1143 bool have_image_files = have_output_image;
1144 bool have_oat_files = have_output_oat;
1145
1146 if (!have_oat_files && !have_image_files) {
1147 Usage("Must be patching either an oat or an image file or both.");
1148 }
1149
1150 if (!have_oat_files && !isa_set) {
1151 Usage("Must include ISA if patching an image file without an oat file.");
1152 }
1153
1154 if (!input_oat_location.empty()) {
1155 if (!isa_set) {
1156 Usage("specifying a location requires specifying an instruction set");
1157 }
Alex Lightcf4bf382014-07-24 11:29:14 -07001158 if (!LocationToFilename(input_oat_location, isa, &input_oat_filename)) {
1159 Usage("Unable to find filename for input oat location %s", input_oat_location.c_str());
1160 }
Alex Light53cb16b2014-06-12 11:26:29 -07001161 if (debug) {
1162 LOG(INFO) << "Using input-oat-file " << input_oat_filename;
1163 }
1164 }
Alex Light53cb16b2014-06-12 11:26:29 -07001165 if (!patched_image_location.empty()) {
1166 if (!isa_set) {
1167 Usage("specifying a location requires specifying an instruction set");
1168 }
Alex Lighta59dd802014-07-02 16:28:08 -07001169 std::string system_filename;
1170 bool has_system = false;
1171 std::string cache_filename;
1172 bool has_cache = false;
1173 bool has_android_data_unused = false;
Andreas Gampe3c13a792014-09-18 20:56:04 -07001174 bool is_global_cache = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001175 if (!gc::space::ImageSpace::FindImageFilename(patched_image_location.c_str(), isa,
1176 &system_filename, &has_system, &cache_filename,
Andreas Gampe3c13a792014-09-18 20:56:04 -07001177 &has_android_data_unused, &has_cache,
1178 &is_global_cache)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001179 Usage("Unable to determine image file for location %s", patched_image_location.c_str());
1180 }
1181 if (has_cache) {
1182 patched_image_filename = cache_filename;
1183 } else if (has_system) {
1184 LOG(WARNING) << "Only image file found was in /system for image location "
1185 << patched_image_location;
1186 patched_image_filename = system_filename;
1187 } else {
1188 Usage("Unable to determine image file for location %s", patched_image_location.c_str());
1189 }
Alex Light53cb16b2014-06-12 11:26:29 -07001190 if (debug) {
1191 LOG(INFO) << "Using patched-image-file " << patched_image_filename;
1192 }
1193 }
1194
1195 if (!base_delta_set) {
1196 if (orig_base_offset_set && base_offset_set) {
1197 base_delta_set = true;
1198 base_delta = base_offset - orig_base_offset;
1199 } else if (!patched_image_filename.empty()) {
Alex Light0eb76d22015-08-11 18:03:47 -07001200 if (have_image_files) {
1201 Usage("--patched-image-location should not be used when patching other images");
1202 }
Alex Light53cb16b2014-06-12 11:26:29 -07001203 base_delta_set = true;
Alex Light0eb76d22015-08-11 18:03:47 -07001204 match_delta = true;
Alex Light53cb16b2014-06-12 11:26:29 -07001205 std::string error_msg;
Alex Lighteefbe392014-07-08 09:53:18 -07001206 if (!ReadBaseDelta(patched_image_filename.c_str(), &base_delta, &error_msg)) {
Alex Light53cb16b2014-06-12 11:26:29 -07001207 Usage(error_msg.c_str(), patched_image_filename.c_str());
1208 }
1209 } else {
1210 if (base_offset_set) {
1211 Usage("Unable to determine original base offset.");
1212 } else {
1213 Usage("Must supply a desired new offset or delta.");
1214 }
1215 }
1216 }
1217
1218 if (!IsAligned<kPageSize>(base_delta)) {
1219 Usage("Base offset/delta must be alligned to a pagesize (0x%08x) boundary.", kPageSize);
1220 }
1221
1222 // Do we need to cleanup output files if we fail?
1223 bool new_image_out = false;
1224 bool new_oat_out = false;
1225
1226 std::unique_ptr<File> input_oat;
1227 std::unique_ptr<File> output_oat;
1228 std::unique_ptr<File> output_image;
1229
1230 if (have_image_files) {
1231 CHECK(!input_image_location.empty());
1232
1233 if (output_image_fd != -1) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001234 if (output_image_filename.empty()) {
1235 output_image_filename = "output-image-file";
1236 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001237 output_image.reset(new File(output_image_fd, output_image_filename, true));
Alex Light53cb16b2014-06-12 11:26:29 -07001238 } else {
1239 CHECK(!output_image_filename.empty());
1240 output_image.reset(CreateOrOpen(output_image_filename.c_str(), &new_image_out));
1241 }
1242 } else {
1243 CHECK(output_image_filename.empty() && output_image_fd == -1 && input_image_location.empty());
1244 }
1245
1246 if (have_oat_files) {
1247 if (input_oat_fd != -1) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001248 if (input_oat_filename.empty()) {
1249 input_oat_filename = "input-oat-file";
1250 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001251 input_oat.reset(new File(input_oat_fd, input_oat_filename, false));
Julien Delayena473f512015-03-05 16:37:52 +01001252 if (input_oat_fd == output_oat_fd) {
1253 input_oat.get()->DisableAutoClose();
1254 }
Igor Murashkin46774762014-10-22 11:37:02 -07001255 if (input_oat == nullptr) {
1256 // Unlikely, but ensure exhaustive logging in non-0 exit code case
1257 LOG(ERROR) << "Failed to open input oat file by its FD" << input_oat_fd;
1258 }
Alex Light53cb16b2014-06-12 11:26:29 -07001259 } else {
1260 CHECK(!input_oat_filename.empty());
1261 input_oat.reset(OS::OpenFileForReading(input_oat_filename.c_str()));
Igor Murashkin46774762014-10-22 11:37:02 -07001262 if (input_oat == nullptr) {
1263 int err = errno;
1264 LOG(ERROR) << "Failed to open input oat file " << input_oat_filename
1265 << ": " << strerror(err) << "(" << err << ")";
Andreas Gampe1c83cbc2014-07-22 18:52:29 -07001266 }
Alex Light53cb16b2014-06-12 11:26:29 -07001267 }
1268
1269 if (output_oat_fd != -1) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001270 if (output_oat_filename.empty()) {
1271 output_oat_filename = "output-oat-file";
Alex Lighta59dd802014-07-02 16:28:08 -07001272 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001273 output_oat.reset(new File(output_oat_fd, output_oat_filename, true));
Igor Murashkin46774762014-10-22 11:37:02 -07001274 if (output_oat == nullptr) {
1275 // Unlikely, but ensure exhaustive logging in non-0 exit code case
1276 LOG(ERROR) << "Failed to open output oat file by its FD" << output_oat_fd;
1277 }
Alex Light53cb16b2014-06-12 11:26:29 -07001278 } else {
1279 CHECK(!output_oat_filename.empty());
1280 output_oat.reset(CreateOrOpen(output_oat_filename.c_str(), &new_oat_out));
Igor Murashkin46774762014-10-22 11:37:02 -07001281 if (output_oat == nullptr) {
1282 int err = errno;
1283 LOG(ERROR) << "Failed to open output oat file " << output_oat_filename
1284 << ": " << strerror(err) << "(" << err << ")";
1285 }
Alex Light53cb16b2014-06-12 11:26:29 -07001286 }
1287 }
1288
Igor Murashkin46774762014-10-22 11:37:02 -07001289 // TODO: get rid of this.
Alex Light53cb16b2014-06-12 11:26:29 -07001290 auto cleanup = [&output_image_filename, &output_oat_filename,
1291 &new_oat_out, &new_image_out, &timings, &dump_timings](bool success) {
1292 timings.EndTiming();
1293 if (!success) {
1294 if (new_oat_out) {
1295 CHECK(!output_oat_filename.empty());
Brian Carlstrom8c52a3f2014-09-30 16:18:01 -07001296 TEMP_FAILURE_RETRY(unlink(output_oat_filename.c_str()));
Alex Light53cb16b2014-06-12 11:26:29 -07001297 }
1298 if (new_image_out) {
1299 CHECK(!output_image_filename.empty());
Brian Carlstrom8c52a3f2014-09-30 16:18:01 -07001300 TEMP_FAILURE_RETRY(unlink(output_image_filename.c_str()));
Alex Light53cb16b2014-06-12 11:26:29 -07001301 }
1302 }
1303 if (dump_timings) {
1304 LOG(INFO) << Dumpable<TimingLogger>(timings);
1305 }
Igor Murashkin46774762014-10-22 11:37:02 -07001306
1307 if (kIsDebugBuild) {
1308 LOG(INFO) << "Cleaning up.. success? " << success;
1309 }
Alex Light53cb16b2014-06-12 11:26:29 -07001310 };
1311
Igor Murashkin46774762014-10-22 11:37:02 -07001312 if (have_oat_files && (input_oat.get() == nullptr || output_oat.get() == nullptr)) {
1313 LOG(ERROR) << "Failed to open input/output oat files";
1314 cleanup(false);
1315 return EXIT_FAILURE;
1316 } else if (have_image_files && output_image.get() == nullptr) {
1317 LOG(ERROR) << "Failed to open output image file";
Alex Lightcf4bf382014-07-24 11:29:14 -07001318 cleanup(false);
1319 return EXIT_FAILURE;
1320 }
1321
Alex Light0eb76d22015-08-11 18:03:47 -07001322 if (match_delta) {
1323 CHECK(!have_image_files); // We will not do this with images.
1324 std::string error_msg;
1325 // Figure out what the current delta is so we can match it to the desired delta.
1326 std::unique_ptr<ElfFile> elf(ElfFile::Open(input_oat.get(), PROT_READ, MAP_PRIVATE,
1327 &error_msg));
1328 off_t current_delta = 0;
1329 if (elf.get() == nullptr) {
1330 LOG(ERROR) << "unable to open oat file " << input_oat->GetPath() << " : " << error_msg;
1331 cleanup(false);
1332 return EXIT_FAILURE;
1333 } else if (!ReadOatPatchDelta(elf.get(), &current_delta, &error_msg)) {
1334 LOG(ERROR) << "Unable to get current delta: " << error_msg;
1335 cleanup(false);
1336 return EXIT_FAILURE;
1337 }
1338 // Before this line base_delta is the desired final delta. We need it to be the actual amount to
1339 // change everything by. We subtract the current delta from it to make it this.
1340 base_delta -= current_delta;
1341 if (!IsAligned<kPageSize>(base_delta)) {
1342 LOG(ERROR) << "Given image file was relocated by an illegal delta";
1343 cleanup(false);
1344 return false;
1345 }
1346 }
1347
Igor Murashkin46774762014-10-22 11:37:02 -07001348 if (debug) {
1349 LOG(INFO) << "moving offset by " << base_delta
1350 << " (0x" << std::hex << base_delta << ") bytes or "
1351 << std::dec << (base_delta/kPageSize) << " pages.";
1352 }
1353
1354 // TODO: is it going to be promatic to unlink a file that was flock-ed?
Alex Lightcf4bf382014-07-24 11:29:14 -07001355 ScopedFlock output_oat_lock;
1356 if (lock_output) {
1357 std::string error_msg;
1358 if (have_oat_files && !output_oat_lock.Init(output_oat.get(), &error_msg)) {
1359 LOG(ERROR) << "Unable to lock output oat " << output_image->GetPath() << ": " << error_msg;
1360 cleanup(false);
1361 return EXIT_FAILURE;
1362 }
1363 }
1364
Alex Light53cb16b2014-06-12 11:26:29 -07001365 bool ret;
1366 if (have_image_files && have_oat_files) {
1367 TimingLogger::ScopedTiming pt("patch image and oat", &timings);
1368 ret = PatchOat::Patch(input_oat.get(), input_image_location, base_delta,
Igor Murashkin46774762014-10-22 11:37:02 -07001369 output_oat.get(), output_image.get(), isa, &timings,
1370 output_oat_fd >= 0, // was it opened from FD?
1371 new_oat_out);
Andreas Gampe4303ba92014-11-06 01:00:46 -08001372 // The order here doesn't matter. If the first one is successfully saved and the second one
1373 // erased, ImageSpace will still detect a problem and not use the files.
Alex Light0eb76d22015-08-11 18:03:47 -07001374 ret = FinishFile(output_image.get(), ret);
1375 ret = FinishFile(output_oat.get(), ret);
Alex Light53cb16b2014-06-12 11:26:29 -07001376 } else if (have_oat_files) {
1377 TimingLogger::ScopedTiming pt("patch oat", &timings);
Igor Murashkin46774762014-10-22 11:37:02 -07001378 ret = PatchOat::Patch(input_oat.get(), base_delta, output_oat.get(), &timings,
1379 output_oat_fd >= 0, // was it opened from FD?
1380 new_oat_out);
Alex Light0eb76d22015-08-11 18:03:47 -07001381 ret = FinishFile(output_oat.get(), ret);
Igor Murashkin46774762014-10-22 11:37:02 -07001382 } else if (have_image_files) {
Alex Light53cb16b2014-06-12 11:26:29 -07001383 TimingLogger::ScopedTiming pt("patch image", &timings);
Alex Lighteefbe392014-07-08 09:53:18 -07001384 ret = PatchOat::Patch(input_image_location, base_delta, output_image.get(), isa, &timings);
Alex Light0eb76d22015-08-11 18:03:47 -07001385 ret = FinishFile(output_image.get(), ret);
Igor Murashkin46774762014-10-22 11:37:02 -07001386 } else {
1387 CHECK(false);
1388 ret = true;
1389 }
1390
1391 if (kIsDebugBuild) {
1392 LOG(INFO) << "Exiting with return ... " << ret;
Alex Light53cb16b2014-06-12 11:26:29 -07001393 }
1394 cleanup(ret);
Alex Light53cb16b2014-06-12 11:26:29 -07001395 return (ret) ? EXIT_SUCCESS : EXIT_FAILURE;
1396}
1397
1398} // namespace art
1399
1400int main(int argc, char **argv) {
1401 return art::patchoat(argc, argv);
1402}