blob: 88622ccc9b6c53f8d50729addf3019f1973a74d6 [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) {
Vladimir Marko05792b92015-08-03 11:56:49 +0100526 auto* orig_dex_cache = dex_caches->GetWithoutChecks(i);
527 auto* copy_dex_cache = RelocatedCopyOf(orig_dex_cache);
528 const size_t pointer_size = InstructionSetPointerSize(isa_);
529 // Though the DexCache array fields are usually treated as native pointers, we set the full
530 // 64-bit values here, clearing the top 32 bits for 32-bit targets. The zero-extension is
531 // done by casting to the unsigned type uintptr_t before casting to int64_t, i.e.
532 // static_cast<int64_t>(reinterpret_cast<uintptr_t>(image_begin_ + offset))).
533 GcRoot<mirror::String>* orig_strings = orig_dex_cache->GetStrings();
534 GcRoot<mirror::String>* relocated_strings = RelocatedAddressOfPointer(orig_strings);
535 copy_dex_cache->SetField64<false>(
536 mirror::DexCache::StringsOffset(),
537 static_cast<int64_t>(reinterpret_cast<uintptr_t>(relocated_strings)));
538 if (orig_strings != nullptr) {
539 GcRoot<mirror::String>* copy_strings = RelocatedCopyOf(orig_strings);
540 for (size_t j = 0, num = orig_dex_cache->NumStrings(); j != num; ++j) {
541 copy_strings[j] = GcRoot<mirror::String>(RelocatedAddressOfPointer(orig_strings[j].Read()));
542 }
Mathieu Chartierc7853442015-03-27 14:35:38 -0700543 }
Vladimir Marko05792b92015-08-03 11:56:49 +0100544 GcRoot<mirror::Class>* orig_types = orig_dex_cache->GetResolvedTypes();
545 GcRoot<mirror::Class>* relocated_types = RelocatedAddressOfPointer(orig_types);
546 copy_dex_cache->SetField64<false>(
547 mirror::DexCache::ResolvedTypesOffset(),
548 static_cast<int64_t>(reinterpret_cast<uintptr_t>(relocated_types)));
549 if (orig_types != nullptr) {
550 GcRoot<mirror::Class>* copy_types = RelocatedCopyOf(orig_types);
551 for (size_t j = 0, num = orig_dex_cache->NumResolvedTypes(); j != num; ++j) {
552 copy_types[j] = GcRoot<mirror::Class>(RelocatedAddressOfPointer(orig_types[j].Read()));
553 }
554 }
555 ArtMethod** orig_methods = orig_dex_cache->GetResolvedMethods();
556 ArtMethod** relocated_methods = RelocatedAddressOfPointer(orig_methods);
557 copy_dex_cache->SetField64<false>(
558 mirror::DexCache::ResolvedMethodsOffset(),
559 static_cast<int64_t>(reinterpret_cast<uintptr_t>(relocated_methods)));
560 if (orig_methods != nullptr) {
561 ArtMethod** copy_methods = RelocatedCopyOf(orig_methods);
562 for (size_t j = 0, num = orig_dex_cache->NumResolvedMethods(); j != num; ++j) {
563 ArtMethod* orig = mirror::DexCache::GetElementPtrSize(orig_methods, j, pointer_size);
564 ArtMethod* copy = RelocatedAddressOfPointer(orig);
565 mirror::DexCache::SetElementPtrSize(copy_methods, j, copy, pointer_size);
566 }
567 }
568 ArtField** orig_fields = orig_dex_cache->GetResolvedFields();
569 ArtField** relocated_fields = RelocatedAddressOfPointer(orig_fields);
570 copy_dex_cache->SetField64<false>(
571 mirror::DexCache::ResolvedFieldsOffset(),
572 static_cast<int64_t>(reinterpret_cast<uintptr_t>(relocated_fields)));
573 if (orig_fields != nullptr) {
574 ArtField** copy_fields = RelocatedCopyOf(orig_fields);
575 for (size_t j = 0, num = orig_dex_cache->NumResolvedFields(); j != num; ++j) {
576 ArtField* orig = mirror::DexCache::GetElementPtrSize(orig_fields, j, pointer_size);
577 ArtField* copy = RelocatedAddressOfPointer(orig);
578 mirror::DexCache::SetElementPtrSize(copy_fields, j, copy, pointer_size);
579 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700580 }
581 }
582}
583
584void PatchOat::FixupNativePointerArray(mirror::PointerArray* object) {
585 if (object->IsIntArray()) {
586 mirror::IntArray* arr = object->AsIntArray();
587 mirror::IntArray* copy_arr = down_cast<mirror::IntArray*>(RelocatedCopyOf(arr));
588 for (size_t j = 0, count2 = arr->GetLength(); j < count2; ++j) {
589 copy_arr->SetWithoutChecks<false>(
590 j, RelocatedAddressOfIntPointer(arr->GetWithoutChecks(j)));
591 }
592 } else {
593 CHECK(object->IsLongArray());
594 mirror::LongArray* arr = object->AsLongArray();
595 mirror::LongArray* copy_arr = down_cast<mirror::LongArray*>(RelocatedCopyOf(arr));
596 for (size_t j = 0, count2 = arr->GetLength(); j < count2; ++j) {
597 copy_arr->SetWithoutChecks<false>(
598 j, RelocatedAddressOfIntPointer(arr->GetWithoutChecks(j)));
Mathieu Chartierc7853442015-03-27 14:35:38 -0700599 }
600 }
601}
602
Alex Light53cb16b2014-06-12 11:26:29 -0700603bool PatchOat::PatchImage() {
604 ImageHeader* image_header = reinterpret_cast<ImageHeader*>(image_->Begin());
605 CHECK_GT(image_->Size(), sizeof(ImageHeader));
606 // These are the roots from the original file.
Mathieu Chartierc7853442015-03-27 14:35:38 -0700607 auto* img_roots = image_header->GetImageRoots();
Alex Light53cb16b2014-06-12 11:26:29 -0700608 image_header->RelocateImage(delta_);
609
Mathieu Chartierc7853442015-03-27 14:35:38 -0700610 PatchArtFields(image_header);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700611 PatchArtMethods(image_header);
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700612 PatchInternedStrings(image_header);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700613 // Patch dex file int/long arrays which point to ArtFields.
614 PatchDexFileArrays(img_roots);
615
Alex Light53cb16b2014-06-12 11:26:29 -0700616 VisitObject(img_roots);
617 if (!image_header->IsValid()) {
618 LOG(ERROR) << "reloction renders image header invalid";
619 return false;
620 }
621
622 {
Alex Lighteefbe392014-07-08 09:53:18 -0700623 TimingLogger::ScopedTiming t("Walk Bitmap", timings_);
Alex Light53cb16b2014-06-12 11:26:29 -0700624 // Walk the bitmap.
625 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
626 bitmap_->Walk(PatchOat::BitmapCallback, this);
627 }
628 return true;
629}
630
631bool PatchOat::InHeap(mirror::Object* o) {
632 uintptr_t begin = reinterpret_cast<uintptr_t>(heap_->Begin());
633 uintptr_t end = reinterpret_cast<uintptr_t>(heap_->End());
634 uintptr_t obj = reinterpret_cast<uintptr_t>(o);
635 return o == nullptr || (begin <= obj && obj < end);
636}
637
638void PatchOat::PatchVisitor::operator() (mirror::Object* obj, MemberOffset off,
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700639 bool is_static_unused ATTRIBUTE_UNUSED) const {
Alex Light53cb16b2014-06-12 11:26:29 -0700640 mirror::Object* referent = obj->GetFieldObject<mirror::Object, kVerifyNone>(off);
641 DCHECK(patcher_->InHeap(referent)) << "Referent is not in the heap.";
Mathieu Chartierc7853442015-03-27 14:35:38 -0700642 mirror::Object* moved_object = patcher_->RelocatedAddressOfPointer(referent);
Alex Light53cb16b2014-06-12 11:26:29 -0700643 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(off, moved_object);
644}
645
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700646void PatchOat::PatchVisitor::operator() (mirror::Class* cls ATTRIBUTE_UNUSED,
647 mirror::Reference* ref) const {
Alex Light53cb16b2014-06-12 11:26:29 -0700648 MemberOffset off = mirror::Reference::ReferentOffset();
649 mirror::Object* referent = ref->GetReferent();
650 DCHECK(patcher_->InHeap(referent)) << "Referent is not in the heap.";
Mathieu Chartierc7853442015-03-27 14:35:38 -0700651 mirror::Object* moved_object = patcher_->RelocatedAddressOfPointer(referent);
Alex Light53cb16b2014-06-12 11:26:29 -0700652 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(off, moved_object);
653}
654
Alex Light53cb16b2014-06-12 11:26:29 -0700655// Called by BitmapCallback
656void PatchOat::VisitObject(mirror::Object* object) {
657 mirror::Object* copy = RelocatedCopyOf(object);
658 CHECK(copy != nullptr);
659 if (kUseBakerOrBrooksReadBarrier) {
660 object->AssertReadBarrierPointer();
661 if (kUseBrooksReadBarrier) {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700662 mirror::Object* moved_to = RelocatedAddressOfPointer(object);
Alex Light53cb16b2014-06-12 11:26:29 -0700663 copy->SetReadBarrierPointer(moved_to);
664 DCHECK_EQ(copy->GetReadBarrierPointer(), moved_to);
665 }
666 }
667 PatchOat::PatchVisitor visitor(this, copy);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -0700668 object->VisitReferences<kVerifyNone>(visitor, visitor);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700669 if (object->IsClass<kVerifyNone>()) {
670 auto* klass = object->AsClass();
671 auto* copy_klass = down_cast<mirror::Class*>(copy);
Vladimir Marko05792b92015-08-03 11:56:49 +0100672 copy_klass->SetDexCacheStrings(RelocatedAddressOfPointer(klass->GetDexCacheStrings()));
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700673 copy_klass->SetSFieldsPtrUnchecked(RelocatedAddressOfPointer(klass->GetSFieldsPtr()));
674 copy_klass->SetIFieldsPtrUnchecked(RelocatedAddressOfPointer(klass->GetIFieldsPtr()));
Mathieu Chartiere401d142015-04-22 13:56:20 -0700675 copy_klass->SetDirectMethodsPtrUnchecked(
676 RelocatedAddressOfPointer(klass->GetDirectMethodsPtr()));
677 copy_klass->SetVirtualMethodsPtr(RelocatedAddressOfPointer(klass->GetVirtualMethodsPtr()));
678 auto* vtable = klass->GetVTable();
679 if (vtable != nullptr) {
680 FixupNativePointerArray(vtable);
681 }
682 auto* iftable = klass->GetIfTable();
683 if (iftable != nullptr) {
684 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
685 if (iftable->GetMethodArrayCount(i) > 0) {
686 auto* method_array = iftable->GetMethodArray(i);
687 CHECK(method_array != nullptr);
688 FixupNativePointerArray(method_array);
689 }
690 }
691 }
692 if (klass->ShouldHaveEmbeddedImtAndVTable()) {
693 const size_t pointer_size = InstructionSetPointerSize(isa_);
694 for (int32_t i = 0; i < klass->GetEmbeddedVTableLength(); ++i) {
695 copy_klass->SetEmbeddedVTableEntryUnchecked(i, RelocatedAddressOfPointer(
696 klass->GetEmbeddedVTableEntry(i, pointer_size)), pointer_size);
697 }
698 for (size_t i = 0; i < mirror::Class::kImtSize; ++i) {
699 copy_klass->SetEmbeddedImTableEntry(i, RelocatedAddressOfPointer(
700 klass->GetEmbeddedImTableEntry(i, pointer_size)), pointer_size);
701 }
702 }
703 }
704 if (object->GetClass() == mirror::Method::StaticClass() ||
705 object->GetClass() == mirror::Constructor::StaticClass()) {
706 // Need to go update the ArtMethod.
707 auto* dest = down_cast<mirror::AbstractMethod*>(copy);
708 auto* src = down_cast<mirror::AbstractMethod*>(object);
709 dest->SetArtMethod(RelocatedAddressOfPointer(src->GetArtMethod()));
Alex Light53cb16b2014-06-12 11:26:29 -0700710 }
711}
712
Mathieu Chartiere401d142015-04-22 13:56:20 -0700713void PatchOat::FixupMethod(ArtMethod* object, ArtMethod* copy) {
Mathieu Chartier2d721012014-11-10 11:08:06 -0800714 const size_t pointer_size = InstructionSetPointerSize(isa_);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700715 copy->CopyFrom(object, pointer_size);
Alex Light53cb16b2014-06-12 11:26:29 -0700716 // Just update the entry points if it looks like we should.
Alex Lighteefbe392014-07-08 09:53:18 -0700717 // TODO: sanity check all the pointers' values
Mathieu Chartiere401d142015-04-22 13:56:20 -0700718 copy->SetDeclaringClass(RelocatedAddressOfPointer(object->GetDeclaringClass()));
Vladimir Marko05792b92015-08-03 11:56:49 +0100719 copy->SetDexCacheResolvedMethods(
720 RelocatedAddressOfPointer(object->GetDexCacheResolvedMethods(pointer_size)), pointer_size);
721 copy->SetDexCacheResolvedTypes(
722 RelocatedAddressOfPointer(object->GetDexCacheResolvedTypes(pointer_size)), pointer_size);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700723 copy->SetEntryPointFromQuickCompiledCodePtrSize(RelocatedAddressOfPointer(
724 object->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size)), pointer_size);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700725 copy->SetEntryPointFromJniPtrSize(RelocatedAddressOfPointer(
726 object->GetEntryPointFromJniPtrSize(pointer_size)), pointer_size);
Alex Light53cb16b2014-06-12 11:26:29 -0700727}
728
Igor Murashkin46774762014-10-22 11:37:02 -0700729bool PatchOat::Patch(File* input_oat, off_t delta, File* output_oat, TimingLogger* timings,
730 bool output_oat_opened_from_fd, bool new_oat_out) {
Alex Light53cb16b2014-06-12 11:26:29 -0700731 CHECK(input_oat != nullptr);
732 CHECK(output_oat != nullptr);
733 CHECK_GE(input_oat->Fd(), 0);
734 CHECK_GE(output_oat->Fd(), 0);
Alex Lighteefbe392014-07-08 09:53:18 -0700735 TimingLogger::ScopedTiming t("Setup Oat File Patching", timings);
Alex Light53cb16b2014-06-12 11:26:29 -0700736
737 std::string error_msg;
Igor Murashkin46774762014-10-22 11:37:02 -0700738 std::unique_ptr<ElfFile> elf(ElfFile::Open(input_oat,
Alex Light53cb16b2014-06-12 11:26:29 -0700739 PROT_READ | PROT_WRITE, MAP_PRIVATE, &error_msg));
740 if (elf.get() == nullptr) {
741 LOG(ERROR) << "unable to open oat file " << input_oat->GetPath() << " : " << error_msg;
742 return false;
743 }
744
Igor Murashkin46774762014-10-22 11:37:02 -0700745 MaybePic is_oat_pic = IsOatPic(elf.get());
746 if (is_oat_pic >= ERROR_FIRST) {
747 // Error logged by IsOatPic
748 return false;
749 } else if (is_oat_pic == PIC) {
750 // Do not need to do ELF-file patching. Create a symlink and skip the rest.
751 // Any errors will be logged by the function call.
752 return ReplaceOatFileWithSymlink(input_oat->GetPath(),
753 output_oat->GetPath(),
754 output_oat_opened_from_fd,
755 new_oat_out);
756 } else {
757 CHECK(is_oat_pic == NOT_PIC);
758 }
759
Alex Light53cb16b2014-06-12 11:26:29 -0700760 PatchOat p(elf.release(), delta, timings);
761 t.NewTiming("Patch Oat file");
762 if (!p.PatchElf()) {
763 return false;
764 }
765
766 t.NewTiming("Writing oat file");
767 if (!p.WriteElf(output_oat)) {
768 return false;
769 }
770 return true;
771}
772
Tong Shen62d1ca32014-09-03 17:24:56 -0700773template <typename ElfFileImpl>
774bool PatchOat::PatchOatHeader(ElfFileImpl* oat_file) {
775 auto rodata_sec = oat_file->FindSectionByName(".rodata");
Alex Lighta59dd802014-07-02 16:28:08 -0700776 if (rodata_sec == nullptr) {
777 return false;
778 }
Tong Shen62d1ca32014-09-03 17:24:56 -0700779 OatHeader* oat_header = reinterpret_cast<OatHeader*>(oat_file->Begin() + rodata_sec->sh_offset);
Alex Lighta59dd802014-07-02 16:28:08 -0700780 if (!oat_header->IsValid()) {
Tong Shen62d1ca32014-09-03 17:24:56 -0700781 LOG(ERROR) << "Elf file " << oat_file->GetFile().GetPath() << " has an invalid oat header";
Alex Lighta59dd802014-07-02 16:28:08 -0700782 return false;
783 }
784 oat_header->RelocateOat(delta_);
785 return true;
786}
787
Alex Light53cb16b2014-06-12 11:26:29 -0700788bool PatchOat::PatchElf() {
Ian Rogersd4c4d952014-10-16 20:31:53 -0700789 if (oat_file_->Is64Bit())
Tong Shen62d1ca32014-09-03 17:24:56 -0700790 return PatchElf<ElfFileImpl64>(oat_file_->GetImpl64());
791 else
792 return PatchElf<ElfFileImpl32>(oat_file_->GetImpl32());
793}
794
795template <typename ElfFileImpl>
796bool PatchOat::PatchElf(ElfFileImpl* oat_file) {
Alex Lighta59dd802014-07-02 16:28:08 -0700797 TimingLogger::ScopedTiming t("Fixup Elf Text Section", timings_);
Vladimir Marko3fc99032015-05-13 19:06:30 +0100798
799 // Fix up absolute references to locations within the boot image.
David Srbecky2f6cdb02015-04-11 00:17:53 +0100800 if (!oat_file->ApplyOatPatchesTo(".text", delta_)) {
Alex Lighta59dd802014-07-02 16:28:08 -0700801 return false;
802 }
803
Vladimir Marko3fc99032015-05-13 19:06:30 +0100804 // Update the OatHeader fields referencing the boot image.
Tong Shen62d1ca32014-09-03 17:24:56 -0700805 if (!PatchOatHeader<ElfFileImpl>(oat_file)) {
Alex Lighta59dd802014-07-02 16:28:08 -0700806 return false;
807 }
808
Vladimir Marko3fc99032015-05-13 19:06:30 +0100809 bool need_boot_oat_fixup = true;
Ian Rogersd4c4d952014-10-16 20:31:53 -0700810 for (unsigned int i = 0; i < oat_file->GetProgramHeaderNum(); ++i) {
Tong Shen62d1ca32014-09-03 17:24:56 -0700811 auto hdr = oat_file->GetProgramHeader(i);
Vladimir Marko3fc99032015-05-13 19:06:30 +0100812 if (hdr->p_type == PT_LOAD && hdr->p_vaddr == 0u) {
813 need_boot_oat_fixup = false;
Ian Rogersd4c4d952014-10-16 20:31:53 -0700814 break;
Alex Light53cb16b2014-06-12 11:26:29 -0700815 }
816 }
Vladimir Marko3fc99032015-05-13 19:06:30 +0100817 if (!need_boot_oat_fixup) {
818 // This is an app oat file that can be loaded at an arbitrary address in memory.
819 // Boot image references were patched above and there's nothing else to do.
Alex Lighta59dd802014-07-02 16:28:08 -0700820 return true;
821 }
Tong Shen62d1ca32014-09-03 17:24:56 -0700822
Vladimir Marko3fc99032015-05-13 19:06:30 +0100823 // This is a boot oat file that's loaded at a particular address and we need
824 // to patch all absolute addresses, starting with ELF program headers.
825
Tong Shen62d1ca32014-09-03 17:24:56 -0700826 t.NewTiming("Fixup Elf Headers");
827 // Fixup Phdr's
828 oat_file->FixupProgramHeaders(delta_);
829
Alex Lighta59dd802014-07-02 16:28:08 -0700830 t.NewTiming("Fixup Section Headers");
Tong Shen62d1ca32014-09-03 17:24:56 -0700831 // Fixup Shdr's
832 oat_file->FixupSectionHeaders(delta_);
Alex Light53cb16b2014-06-12 11:26:29 -0700833
Alex Lighta59dd802014-07-02 16:28:08 -0700834 t.NewTiming("Fixup Dynamics");
Tong Shen62d1ca32014-09-03 17:24:56 -0700835 oat_file->FixupDynamic(delta_);
Alex Light53cb16b2014-06-12 11:26:29 -0700836
837 t.NewTiming("Fixup Elf Symbols");
838 // Fixup dynsym
Tong Shen62d1ca32014-09-03 17:24:56 -0700839 if (!oat_file->FixupSymbols(delta_, true)) {
Alex Light53cb16b2014-06-12 11:26:29 -0700840 return false;
841 }
Alex Light53cb16b2014-06-12 11:26:29 -0700842 // Fixup symtab
Tong Shen62d1ca32014-09-03 17:24:56 -0700843 if (!oat_file->FixupSymbols(delta_, false)) {
844 return false;
Alex Light53cb16b2014-06-12 11:26:29 -0700845 }
846
Yevgeny Roubane3ea8382014-08-08 16:29:38 +0700847 t.NewTiming("Fixup Debug Sections");
Tong Shen62d1ca32014-09-03 17:24:56 -0700848 if (!oat_file->FixupDebugSections(delta_)) {
Yevgeny Roubane3ea8382014-08-08 16:29:38 +0700849 return false;
850 }
851
Alex Light53cb16b2014-06-12 11:26:29 -0700852 return true;
853}
854
Alex Light53cb16b2014-06-12 11:26:29 -0700855static int orig_argc;
856static char** orig_argv;
857
858static std::string CommandLine() {
859 std::vector<std::string> command;
860 for (int i = 0; i < orig_argc; ++i) {
861 command.push_back(orig_argv[i]);
862 }
863 return Join(command, ' ');
864}
865
866static void UsageErrorV(const char* fmt, va_list ap) {
867 std::string error;
868 StringAppendV(&error, fmt, ap);
869 LOG(ERROR) << error;
870}
871
872static void UsageError(const char* fmt, ...) {
873 va_list ap;
874 va_start(ap, fmt);
875 UsageErrorV(fmt, ap);
876 va_end(ap);
877}
878
Andreas Gampe794ad762015-02-23 08:12:24 -0800879NO_RETURN static void Usage(const char *fmt, ...) {
Alex Light53cb16b2014-06-12 11:26:29 -0700880 va_list ap;
881 va_start(ap, fmt);
882 UsageErrorV(fmt, ap);
883 va_end(ap);
884
885 UsageError("Command: %s", CommandLine().c_str());
886 UsageError("Usage: patchoat [options]...");
887 UsageError("");
888 UsageError(" --instruction-set=<isa>: Specifies the instruction set the patched code is");
889 UsageError(" compiled for. Required if you use --input-oat-location");
890 UsageError("");
891 UsageError(" --input-oat-file=<file.oat>: Specifies the exact filename of the oat file to be");
892 UsageError(" patched.");
893 UsageError("");
894 UsageError(" --input-oat-fd=<file-descriptor>: Specifies the file-descriptor of the oat file");
895 UsageError(" to be patched.");
896 UsageError("");
897 UsageError(" --input-oat-location=<file.oat>: Specifies the 'location' to read the patched");
898 UsageError(" oat file from. If used one must also supply the --instruction-set");
899 UsageError("");
900 UsageError(" --input-image-location=<file.art>: Specifies the 'location' of the image file to");
901 UsageError(" be patched. If --instruction-set is not given it will use the instruction set");
902 UsageError(" extracted from the --input-oat-file.");
903 UsageError("");
904 UsageError(" --output-oat-file=<file.oat>: Specifies the exact file to write the patched oat");
905 UsageError(" file to.");
906 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700907 UsageError(" --output-oat-fd=<file-descriptor>: Specifies the file-descriptor to write the");
908 UsageError(" the patched oat file to.");
909 UsageError("");
910 UsageError(" --output-image-file=<file.art>: Specifies the exact file to write the patched");
911 UsageError(" image file to.");
912 UsageError("");
913 UsageError(" --output-image-fd=<file-descriptor>: Specifies the file-descriptor to write the");
914 UsageError(" the patched image file to.");
915 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700916 UsageError(" --orig-base-offset=<original-base-offset>: Specify the base offset the input file");
917 UsageError(" was compiled with. This is needed if one is specifying a --base-offset");
918 UsageError("");
919 UsageError(" --base-offset=<new-base-offset>: Specify the base offset we will repatch the");
920 UsageError(" given files to use. This requires that --orig-base-offset is also given.");
921 UsageError("");
922 UsageError(" --base-offset-delta=<delta>: Specify the amount to change the old base-offset by.");
923 UsageError(" This value may be negative.");
924 UsageError("");
Alex Light0eb76d22015-08-11 18:03:47 -0700925 UsageError(" --patched-image-file=<file.art>: Relocate the oat file to be the same as the");
926 UsageError(" given image file.");
Alex Light53cb16b2014-06-12 11:26:29 -0700927 UsageError("");
Alex Light0eb76d22015-08-11 18:03:47 -0700928 UsageError(" --patched-image-location=<file.art>: Relocate the oat file to be the same as the");
929 UsageError(" image at the given location. If used one must also specify the");
Alex Lighta59dd802014-07-02 16:28:08 -0700930 UsageError(" --instruction-set flag. It will search for this image in the same way that");
931 UsageError(" is done when loading one.");
Alex Light53cb16b2014-06-12 11:26:29 -0700932 UsageError("");
Alex Lightcf4bf382014-07-24 11:29:14 -0700933 UsageError(" --lock-output: Obtain a flock on output oat file before starting.");
934 UsageError("");
935 UsageError(" --no-lock-output: Do not attempt to obtain a flock on output oat file.");
936 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700937 UsageError(" --dump-timings: dump out patch timing information");
938 UsageError("");
939 UsageError(" --no-dump-timings: do not dump out patch timing information");
940 UsageError("");
941
942 exit(EXIT_FAILURE);
943}
944
Alex Lighteefbe392014-07-08 09:53:18 -0700945static bool ReadBaseDelta(const char* name, off_t* delta, std::string* error_msg) {
Alex Light53cb16b2014-06-12 11:26:29 -0700946 CHECK(name != nullptr);
947 CHECK(delta != nullptr);
948 std::unique_ptr<File> file;
949 if (OS::FileExists(name)) {
950 file.reset(OS::OpenFileForReading(name));
951 if (file.get() == nullptr) {
Alex Lighteefbe392014-07-08 09:53:18 -0700952 *error_msg = "Failed to open file %s for reading";
Alex Light53cb16b2014-06-12 11:26:29 -0700953 return false;
954 }
955 } else {
Alex Lighteefbe392014-07-08 09:53:18 -0700956 *error_msg = "File %s does not exist";
Alex Light53cb16b2014-06-12 11:26:29 -0700957 return false;
958 }
959 CHECK(file.get() != nullptr);
960 ImageHeader hdr;
961 if (sizeof(hdr) != file->Read(reinterpret_cast<char*>(&hdr), sizeof(hdr), 0)) {
Alex Lighteefbe392014-07-08 09:53:18 -0700962 *error_msg = "Failed to read file %s";
Alex Light53cb16b2014-06-12 11:26:29 -0700963 return false;
964 }
965 if (!hdr.IsValid()) {
Alex Lighteefbe392014-07-08 09:53:18 -0700966 *error_msg = "%s does not contain a valid image header.";
Alex Light53cb16b2014-06-12 11:26:29 -0700967 return false;
968 }
969 *delta = hdr.GetPatchDelta();
970 return true;
971}
972
973static File* CreateOrOpen(const char* name, bool* created) {
974 if (OS::FileExists(name)) {
975 *created = false;
976 return OS::OpenFileReadWrite(name);
977 } else {
978 *created = true;
Alex Lightcf4bf382014-07-24 11:29:14 -0700979 std::unique_ptr<File> f(OS::CreateEmptyFile(name));
980 if (f.get() != nullptr) {
981 if (fchmod(f->Fd(), 0644) != 0) {
982 PLOG(ERROR) << "Unable to make " << name << " world readable";
Brian Carlstrom8c52a3f2014-09-30 16:18:01 -0700983 TEMP_FAILURE_RETRY(unlink(name));
Alex Lightcf4bf382014-07-24 11:29:14 -0700984 return nullptr;
985 }
986 }
987 return f.release();
Alex Light53cb16b2014-06-12 11:26:29 -0700988 }
989}
990
Andreas Gampe4303ba92014-11-06 01:00:46 -0800991// Either try to close the file (close=true), or erase it.
992static bool FinishFile(File* file, bool close) {
993 if (close) {
994 if (file->FlushCloseOrErase() != 0) {
995 PLOG(ERROR) << "Failed to flush and close file.";
996 return false;
997 }
998 return true;
999 } else {
1000 file->Erase();
1001 return false;
1002 }
1003}
1004
Alex Lighteefbe392014-07-08 09:53:18 -07001005static int patchoat(int argc, char **argv) {
Alex Light53cb16b2014-06-12 11:26:29 -07001006 InitLogging(argv);
Mathieu Chartier6e88ef62014-10-14 15:01:24 -07001007 MemMap::Init();
Alex Light53cb16b2014-06-12 11:26:29 -07001008 const bool debug = kIsDebugBuild;
1009 orig_argc = argc;
1010 orig_argv = argv;
1011 TimingLogger timings("patcher", false, false);
1012
1013 InitLogging(argv);
1014
1015 // Skip over the command name.
1016 argv++;
1017 argc--;
1018
1019 if (argc == 0) {
1020 Usage("No arguments specified");
1021 }
1022
1023 timings.StartTiming("Patchoat");
1024
1025 // cmd line args
1026 bool isa_set = false;
1027 InstructionSet isa = kNone;
1028 std::string input_oat_filename;
1029 std::string input_oat_location;
1030 int input_oat_fd = -1;
1031 bool have_input_oat = false;
1032 std::string input_image_location;
1033 std::string output_oat_filename;
Alex Light53cb16b2014-06-12 11:26:29 -07001034 int output_oat_fd = -1;
1035 bool have_output_oat = false;
1036 std::string output_image_filename;
Alex Light53cb16b2014-06-12 11:26:29 -07001037 int output_image_fd = -1;
1038 bool have_output_image = false;
1039 uintptr_t base_offset = 0;
1040 bool base_offset_set = false;
1041 uintptr_t orig_base_offset = 0;
1042 bool orig_base_offset_set = false;
1043 off_t base_delta = 0;
1044 bool base_delta_set = false;
Alex Light0eb76d22015-08-11 18:03:47 -07001045 bool match_delta = false;
Alex Light53cb16b2014-06-12 11:26:29 -07001046 std::string patched_image_filename;
1047 std::string patched_image_location;
1048 bool dump_timings = kIsDebugBuild;
Alex Lightcf4bf382014-07-24 11:29:14 -07001049 bool lock_output = true;
Alex Light53cb16b2014-06-12 11:26:29 -07001050
Ian Rogersd4c4d952014-10-16 20:31:53 -07001051 for (int i = 0; i < argc; ++i) {
Alex Light53cb16b2014-06-12 11:26:29 -07001052 const StringPiece option(argv[i]);
1053 const bool log_options = false;
1054 if (log_options) {
1055 LOG(INFO) << "patchoat: option[" << i << "]=" << argv[i];
1056 }
Alex Light53cb16b2014-06-12 11:26:29 -07001057 if (option.starts_with("--instruction-set=")) {
1058 isa_set = true;
1059 const char* isa_str = option.substr(strlen("--instruction-set=")).data();
Andreas Gampe20c89302014-08-19 17:28:06 -07001060 isa = GetInstructionSetFromString(isa_str);
1061 if (isa == kNone) {
1062 Usage("Unknown or invalid instruction set %s", isa_str);
Alex Light53cb16b2014-06-12 11:26:29 -07001063 }
1064 } else if (option.starts_with("--input-oat-location=")) {
1065 if (have_input_oat) {
1066 Usage("Only one of --input-oat-file, --input-oat-location and --input-oat-fd may be used.");
1067 }
1068 have_input_oat = true;
1069 input_oat_location = option.substr(strlen("--input-oat-location=")).data();
1070 } else if (option.starts_with("--input-oat-file=")) {
1071 if (have_input_oat) {
1072 Usage("Only one of --input-oat-file, --input-oat-location and --input-oat-fd may be used.");
1073 }
1074 have_input_oat = true;
1075 input_oat_filename = option.substr(strlen("--input-oat-file=")).data();
1076 } else if (option.starts_with("--input-oat-fd=")) {
1077 if (have_input_oat) {
1078 Usage("Only one of --input-oat-file, --input-oat-location and --input-oat-fd may be used.");
1079 }
1080 have_input_oat = true;
1081 const char* oat_fd_str = option.substr(strlen("--input-oat-fd=")).data();
1082 if (!ParseInt(oat_fd_str, &input_oat_fd)) {
1083 Usage("Failed to parse --input-oat-fd argument '%s' as an integer", oat_fd_str);
1084 }
1085 if (input_oat_fd < 0) {
1086 Usage("--input-oat-fd pass a negative value %d", input_oat_fd);
1087 }
1088 } else if (option.starts_with("--input-image-location=")) {
1089 input_image_location = option.substr(strlen("--input-image-location=")).data();
Alex Light53cb16b2014-06-12 11:26:29 -07001090 } else if (option.starts_with("--output-oat-file=")) {
1091 if (have_output_oat) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001092 Usage("Only one of --output-oat-file, and --output-oat-fd may be used.");
Alex Light53cb16b2014-06-12 11:26:29 -07001093 }
1094 have_output_oat = true;
1095 output_oat_filename = option.substr(strlen("--output-oat-file=")).data();
1096 } else if (option.starts_with("--output-oat-fd=")) {
1097 if (have_output_oat) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001098 Usage("Only one of --output-oat-file, --output-oat-fd may be used.");
Alex Light53cb16b2014-06-12 11:26:29 -07001099 }
1100 have_output_oat = true;
1101 const char* oat_fd_str = option.substr(strlen("--output-oat-fd=")).data();
1102 if (!ParseInt(oat_fd_str, &output_oat_fd)) {
1103 Usage("Failed to parse --output-oat-fd argument '%s' as an integer", oat_fd_str);
1104 }
1105 if (output_oat_fd < 0) {
1106 Usage("--output-oat-fd pass a negative value %d", output_oat_fd);
1107 }
Alex Light53cb16b2014-06-12 11:26:29 -07001108 } else if (option.starts_with("--output-image-file=")) {
1109 if (have_output_image) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001110 Usage("Only one of --output-image-file, and --output-image-fd may be used.");
Alex Light53cb16b2014-06-12 11:26:29 -07001111 }
1112 have_output_image = true;
1113 output_image_filename = option.substr(strlen("--output-image-file=")).data();
1114 } else if (option.starts_with("--output-image-fd=")) {
1115 if (have_output_image) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001116 Usage("Only one of --output-image-file, and --output-image-fd may be used.");
Alex Light53cb16b2014-06-12 11:26:29 -07001117 }
1118 have_output_image = true;
1119 const char* image_fd_str = option.substr(strlen("--output-image-fd=")).data();
1120 if (!ParseInt(image_fd_str, &output_image_fd)) {
1121 Usage("Failed to parse --output-image-fd argument '%s' as an integer", image_fd_str);
1122 }
1123 if (output_image_fd < 0) {
1124 Usage("--output-image-fd pass a negative value %d", output_image_fd);
1125 }
1126 } else if (option.starts_with("--orig-base-offset=")) {
1127 const char* orig_base_offset_str = option.substr(strlen("--orig-base-offset=")).data();
1128 orig_base_offset_set = true;
1129 if (!ParseUint(orig_base_offset_str, &orig_base_offset)) {
1130 Usage("Failed to parse --orig-base-offset argument '%s' as an uintptr_t",
1131 orig_base_offset_str);
1132 }
1133 } else if (option.starts_with("--base-offset=")) {
1134 const char* base_offset_str = option.substr(strlen("--base-offset=")).data();
1135 base_offset_set = true;
1136 if (!ParseUint(base_offset_str, &base_offset)) {
1137 Usage("Failed to parse --base-offset argument '%s' as an uintptr_t", base_offset_str);
1138 }
1139 } else if (option.starts_with("--base-offset-delta=")) {
1140 const char* base_delta_str = option.substr(strlen("--base-offset-delta=")).data();
1141 base_delta_set = true;
1142 if (!ParseInt(base_delta_str, &base_delta)) {
1143 Usage("Failed to parse --base-offset-delta argument '%s' as an off_t", base_delta_str);
1144 }
1145 } else if (option.starts_with("--patched-image-location=")) {
1146 patched_image_location = option.substr(strlen("--patched-image-location=")).data();
1147 } else if (option.starts_with("--patched-image-file=")) {
1148 patched_image_filename = option.substr(strlen("--patched-image-file=")).data();
Alex Lightcf4bf382014-07-24 11:29:14 -07001149 } else if (option == "--lock-output") {
1150 lock_output = true;
1151 } else if (option == "--no-lock-output") {
1152 lock_output = false;
Alex Light53cb16b2014-06-12 11:26:29 -07001153 } else if (option == "--dump-timings") {
1154 dump_timings = true;
1155 } else if (option == "--no-dump-timings") {
1156 dump_timings = false;
1157 } else {
1158 Usage("Unknown argument %s", option.data());
1159 }
1160 }
1161
1162 {
1163 // Only 1 of these may be set.
1164 uint32_t cnt = 0;
1165 cnt += (base_delta_set) ? 1 : 0;
1166 cnt += (base_offset_set && orig_base_offset_set) ? 1 : 0;
1167 cnt += (!patched_image_filename.empty()) ? 1 : 0;
1168 cnt += (!patched_image_location.empty()) ? 1 : 0;
1169 if (cnt > 1) {
1170 Usage("Only one of --base-offset/--orig-base-offset, --base-offset-delta, "
1171 "--patched-image-filename or --patched-image-location may be used.");
1172 } else if (cnt == 0) {
1173 Usage("Must specify --base-offset-delta, --base-offset and --orig-base-offset, "
1174 "--patched-image-location or --patched-image-file");
1175 }
1176 }
1177
1178 if (have_input_oat != have_output_oat) {
1179 Usage("Either both input and output oat must be supplied or niether must be.");
1180 }
1181
1182 if ((!input_image_location.empty()) != have_output_image) {
1183 Usage("Either both input and output image must be supplied or niether must be.");
1184 }
1185
1186 // We know we have both the input and output so rename for clarity.
1187 bool have_image_files = have_output_image;
1188 bool have_oat_files = have_output_oat;
1189
1190 if (!have_oat_files && !have_image_files) {
1191 Usage("Must be patching either an oat or an image file or both.");
1192 }
1193
1194 if (!have_oat_files && !isa_set) {
1195 Usage("Must include ISA if patching an image file without an oat file.");
1196 }
1197
1198 if (!input_oat_location.empty()) {
1199 if (!isa_set) {
1200 Usage("specifying a location requires specifying an instruction set");
1201 }
Alex Lightcf4bf382014-07-24 11:29:14 -07001202 if (!LocationToFilename(input_oat_location, isa, &input_oat_filename)) {
1203 Usage("Unable to find filename for input oat location %s", input_oat_location.c_str());
1204 }
Alex Light53cb16b2014-06-12 11:26:29 -07001205 if (debug) {
1206 LOG(INFO) << "Using input-oat-file " << input_oat_filename;
1207 }
1208 }
Alex Light53cb16b2014-06-12 11:26:29 -07001209 if (!patched_image_location.empty()) {
1210 if (!isa_set) {
1211 Usage("specifying a location requires specifying an instruction set");
1212 }
Alex Lighta59dd802014-07-02 16:28:08 -07001213 std::string system_filename;
1214 bool has_system = false;
1215 std::string cache_filename;
1216 bool has_cache = false;
1217 bool has_android_data_unused = false;
Andreas Gampe3c13a792014-09-18 20:56:04 -07001218 bool is_global_cache = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001219 if (!gc::space::ImageSpace::FindImageFilename(patched_image_location.c_str(), isa,
1220 &system_filename, &has_system, &cache_filename,
Andreas Gampe3c13a792014-09-18 20:56:04 -07001221 &has_android_data_unused, &has_cache,
1222 &is_global_cache)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001223 Usage("Unable to determine image file for location %s", patched_image_location.c_str());
1224 }
1225 if (has_cache) {
1226 patched_image_filename = cache_filename;
1227 } else if (has_system) {
1228 LOG(WARNING) << "Only image file found was in /system for image location "
1229 << patched_image_location;
1230 patched_image_filename = system_filename;
1231 } else {
1232 Usage("Unable to determine image file for location %s", patched_image_location.c_str());
1233 }
Alex Light53cb16b2014-06-12 11:26:29 -07001234 if (debug) {
1235 LOG(INFO) << "Using patched-image-file " << patched_image_filename;
1236 }
1237 }
1238
1239 if (!base_delta_set) {
1240 if (orig_base_offset_set && base_offset_set) {
1241 base_delta_set = true;
1242 base_delta = base_offset - orig_base_offset;
1243 } else if (!patched_image_filename.empty()) {
Alex Light0eb76d22015-08-11 18:03:47 -07001244 if (have_image_files) {
1245 Usage("--patched-image-location should not be used when patching other images");
1246 }
Alex Light53cb16b2014-06-12 11:26:29 -07001247 base_delta_set = true;
Alex Light0eb76d22015-08-11 18:03:47 -07001248 match_delta = true;
Alex Light53cb16b2014-06-12 11:26:29 -07001249 std::string error_msg;
Alex Lighteefbe392014-07-08 09:53:18 -07001250 if (!ReadBaseDelta(patched_image_filename.c_str(), &base_delta, &error_msg)) {
Alex Light53cb16b2014-06-12 11:26:29 -07001251 Usage(error_msg.c_str(), patched_image_filename.c_str());
1252 }
1253 } else {
1254 if (base_offset_set) {
1255 Usage("Unable to determine original base offset.");
1256 } else {
1257 Usage("Must supply a desired new offset or delta.");
1258 }
1259 }
1260 }
1261
1262 if (!IsAligned<kPageSize>(base_delta)) {
1263 Usage("Base offset/delta must be alligned to a pagesize (0x%08x) boundary.", kPageSize);
1264 }
1265
1266 // Do we need to cleanup output files if we fail?
1267 bool new_image_out = false;
1268 bool new_oat_out = false;
1269
1270 std::unique_ptr<File> input_oat;
1271 std::unique_ptr<File> output_oat;
1272 std::unique_ptr<File> output_image;
1273
1274 if (have_image_files) {
1275 CHECK(!input_image_location.empty());
1276
1277 if (output_image_fd != -1) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001278 if (output_image_filename.empty()) {
1279 output_image_filename = "output-image-file";
1280 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001281 output_image.reset(new File(output_image_fd, output_image_filename, true));
Alex Light53cb16b2014-06-12 11:26:29 -07001282 } else {
1283 CHECK(!output_image_filename.empty());
1284 output_image.reset(CreateOrOpen(output_image_filename.c_str(), &new_image_out));
1285 }
1286 } else {
1287 CHECK(output_image_filename.empty() && output_image_fd == -1 && input_image_location.empty());
1288 }
1289
1290 if (have_oat_files) {
1291 if (input_oat_fd != -1) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001292 if (input_oat_filename.empty()) {
1293 input_oat_filename = "input-oat-file";
1294 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001295 input_oat.reset(new File(input_oat_fd, input_oat_filename, false));
Julien Delayena473f512015-03-05 16:37:52 +01001296 if (input_oat_fd == output_oat_fd) {
1297 input_oat.get()->DisableAutoClose();
1298 }
Igor Murashkin46774762014-10-22 11:37:02 -07001299 if (input_oat == nullptr) {
1300 // Unlikely, but ensure exhaustive logging in non-0 exit code case
1301 LOG(ERROR) << "Failed to open input oat file by its FD" << input_oat_fd;
1302 }
Alex Light53cb16b2014-06-12 11:26:29 -07001303 } else {
1304 CHECK(!input_oat_filename.empty());
1305 input_oat.reset(OS::OpenFileForReading(input_oat_filename.c_str()));
Igor Murashkin46774762014-10-22 11:37:02 -07001306 if (input_oat == nullptr) {
1307 int err = errno;
1308 LOG(ERROR) << "Failed to open input oat file " << input_oat_filename
1309 << ": " << strerror(err) << "(" << err << ")";
Andreas Gampe1c83cbc2014-07-22 18:52:29 -07001310 }
Alex Light53cb16b2014-06-12 11:26:29 -07001311 }
1312
1313 if (output_oat_fd != -1) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001314 if (output_oat_filename.empty()) {
1315 output_oat_filename = "output-oat-file";
Alex Lighta59dd802014-07-02 16:28:08 -07001316 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001317 output_oat.reset(new File(output_oat_fd, output_oat_filename, true));
Igor Murashkin46774762014-10-22 11:37:02 -07001318 if (output_oat == nullptr) {
1319 // Unlikely, but ensure exhaustive logging in non-0 exit code case
1320 LOG(ERROR) << "Failed to open output oat file by its FD" << output_oat_fd;
1321 }
Alex Light53cb16b2014-06-12 11:26:29 -07001322 } else {
1323 CHECK(!output_oat_filename.empty());
1324 output_oat.reset(CreateOrOpen(output_oat_filename.c_str(), &new_oat_out));
Igor Murashkin46774762014-10-22 11:37:02 -07001325 if (output_oat == nullptr) {
1326 int err = errno;
1327 LOG(ERROR) << "Failed to open output oat file " << output_oat_filename
1328 << ": " << strerror(err) << "(" << err << ")";
1329 }
Alex Light53cb16b2014-06-12 11:26:29 -07001330 }
1331 }
1332
Igor Murashkin46774762014-10-22 11:37:02 -07001333 // TODO: get rid of this.
Alex Light53cb16b2014-06-12 11:26:29 -07001334 auto cleanup = [&output_image_filename, &output_oat_filename,
1335 &new_oat_out, &new_image_out, &timings, &dump_timings](bool success) {
1336 timings.EndTiming();
1337 if (!success) {
1338 if (new_oat_out) {
1339 CHECK(!output_oat_filename.empty());
Brian Carlstrom8c52a3f2014-09-30 16:18:01 -07001340 TEMP_FAILURE_RETRY(unlink(output_oat_filename.c_str()));
Alex Light53cb16b2014-06-12 11:26:29 -07001341 }
1342 if (new_image_out) {
1343 CHECK(!output_image_filename.empty());
Brian Carlstrom8c52a3f2014-09-30 16:18:01 -07001344 TEMP_FAILURE_RETRY(unlink(output_image_filename.c_str()));
Alex Light53cb16b2014-06-12 11:26:29 -07001345 }
1346 }
1347 if (dump_timings) {
1348 LOG(INFO) << Dumpable<TimingLogger>(timings);
1349 }
Igor Murashkin46774762014-10-22 11:37:02 -07001350
1351 if (kIsDebugBuild) {
1352 LOG(INFO) << "Cleaning up.. success? " << success;
1353 }
Alex Light53cb16b2014-06-12 11:26:29 -07001354 };
1355
Igor Murashkin46774762014-10-22 11:37:02 -07001356 if (have_oat_files && (input_oat.get() == nullptr || output_oat.get() == nullptr)) {
1357 LOG(ERROR) << "Failed to open input/output oat files";
1358 cleanup(false);
1359 return EXIT_FAILURE;
1360 } else if (have_image_files && output_image.get() == nullptr) {
1361 LOG(ERROR) << "Failed to open output image file";
Alex Lightcf4bf382014-07-24 11:29:14 -07001362 cleanup(false);
1363 return EXIT_FAILURE;
1364 }
1365
Alex Light0eb76d22015-08-11 18:03:47 -07001366 if (match_delta) {
1367 CHECK(!have_image_files); // We will not do this with images.
1368 std::string error_msg;
1369 // Figure out what the current delta is so we can match it to the desired delta.
1370 std::unique_ptr<ElfFile> elf(ElfFile::Open(input_oat.get(), PROT_READ, MAP_PRIVATE,
1371 &error_msg));
1372 off_t current_delta = 0;
1373 if (elf.get() == nullptr) {
1374 LOG(ERROR) << "unable to open oat file " << input_oat->GetPath() << " : " << error_msg;
1375 cleanup(false);
1376 return EXIT_FAILURE;
1377 } else if (!ReadOatPatchDelta(elf.get(), &current_delta, &error_msg)) {
1378 LOG(ERROR) << "Unable to get current delta: " << error_msg;
1379 cleanup(false);
1380 return EXIT_FAILURE;
1381 }
1382 // Before this line base_delta is the desired final delta. We need it to be the actual amount to
1383 // change everything by. We subtract the current delta from it to make it this.
1384 base_delta -= current_delta;
1385 if (!IsAligned<kPageSize>(base_delta)) {
1386 LOG(ERROR) << "Given image file was relocated by an illegal delta";
1387 cleanup(false);
1388 return false;
1389 }
1390 }
1391
Igor Murashkin46774762014-10-22 11:37:02 -07001392 if (debug) {
1393 LOG(INFO) << "moving offset by " << base_delta
1394 << " (0x" << std::hex << base_delta << ") bytes or "
1395 << std::dec << (base_delta/kPageSize) << " pages.";
1396 }
1397
1398 // TODO: is it going to be promatic to unlink a file that was flock-ed?
Alex Lightcf4bf382014-07-24 11:29:14 -07001399 ScopedFlock output_oat_lock;
1400 if (lock_output) {
1401 std::string error_msg;
1402 if (have_oat_files && !output_oat_lock.Init(output_oat.get(), &error_msg)) {
1403 LOG(ERROR) << "Unable to lock output oat " << output_image->GetPath() << ": " << error_msg;
1404 cleanup(false);
1405 return EXIT_FAILURE;
1406 }
1407 }
1408
Alex Light53cb16b2014-06-12 11:26:29 -07001409 bool ret;
1410 if (have_image_files && have_oat_files) {
1411 TimingLogger::ScopedTiming pt("patch image and oat", &timings);
1412 ret = PatchOat::Patch(input_oat.get(), input_image_location, base_delta,
Igor Murashkin46774762014-10-22 11:37:02 -07001413 output_oat.get(), output_image.get(), isa, &timings,
1414 output_oat_fd >= 0, // was it opened from FD?
1415 new_oat_out);
Andreas Gampe4303ba92014-11-06 01:00:46 -08001416 // The order here doesn't matter. If the first one is successfully saved and the second one
1417 // erased, ImageSpace will still detect a problem and not use the files.
Alex Light0eb76d22015-08-11 18:03:47 -07001418 ret = FinishFile(output_image.get(), ret);
1419 ret = FinishFile(output_oat.get(), ret);
Alex Light53cb16b2014-06-12 11:26:29 -07001420 } else if (have_oat_files) {
1421 TimingLogger::ScopedTiming pt("patch oat", &timings);
Igor Murashkin46774762014-10-22 11:37:02 -07001422 ret = PatchOat::Patch(input_oat.get(), base_delta, output_oat.get(), &timings,
1423 output_oat_fd >= 0, // was it opened from FD?
1424 new_oat_out);
Alex Light0eb76d22015-08-11 18:03:47 -07001425 ret = FinishFile(output_oat.get(), ret);
Igor Murashkin46774762014-10-22 11:37:02 -07001426 } else if (have_image_files) {
Alex Light53cb16b2014-06-12 11:26:29 -07001427 TimingLogger::ScopedTiming pt("patch image", &timings);
Alex Lighteefbe392014-07-08 09:53:18 -07001428 ret = PatchOat::Patch(input_image_location, base_delta, output_image.get(), isa, &timings);
Alex Light0eb76d22015-08-11 18:03:47 -07001429 ret = FinishFile(output_image.get(), ret);
Igor Murashkin46774762014-10-22 11:37:02 -07001430 } else {
1431 CHECK(false);
1432 ret = true;
1433 }
1434
1435 if (kIsDebugBuild) {
1436 LOG(INFO) << "Exiting with return ... " << ret;
Alex Light53cb16b2014-06-12 11:26:29 -07001437 }
1438 cleanup(ret);
Alex Light53cb16b2014-06-12 11:26:29 -07001439 return (ret) ? EXIT_SUCCESS : EXIT_FAILURE;
1440}
1441
1442} // namespace art
1443
1444int main(int argc, char **argv) {
1445 return art::patchoat(argc, argv);
1446}