blob: 723bb1762db27102dc609ddec0e100504cc7b78b [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;
Mathieu Chartier42bddce2015-11-09 15:16:56 -0800180 std::unique_ptr<MemMap> image(MemMap::MapFile(image_len,
181 PROT_READ | PROT_WRITE,
182 MAP_PRIVATE,
183 input_image->Fd(),
184 0,
185 /*low_4gb*/false,
Alex Light53cb16b2014-06-12 11:26:29 -0700186 input_image->GetPath().c_str(),
187 &error_msg));
188 if (image.get() == nullptr) {
189 LOG(ERROR) << "unable to map image file " << input_image->GetPath() << " : " << error_msg;
190 return false;
191 }
Mathieu Chartier073b16c2015-11-10 14:13:23 -0800192 gc::space::ImageSpace* ispc = Runtime::Current()->GetHeap()->GetBootImageSpace();
Alex Light53cb16b2014-06-12 11:26:29 -0700193
Mathieu Chartier42bddce2015-11-09 15:16:56 -0800194 PatchOat p(isa, image.release(), ispc->GetLiveBitmap(), ispc->GetMemMap(), delta, timings);
Alex Light53cb16b2014-06-12 11:26:29 -0700195 t.NewTiming("Patching files");
196 if (!p.PatchImage()) {
Alex Lighta59dd802014-07-02 16:28:08 -0700197 LOG(ERROR) << "Failed to patch image file " << input_image->GetPath();
Alex Light53cb16b2014-06-12 11:26:29 -0700198 return false;
199 }
200
201 t.NewTiming("Writing files");
202 if (!p.WriteImage(output_image)) {
203 return false;
204 }
205 return true;
206}
207
Igor Murashkin46774762014-10-22 11:37:02 -0700208bool PatchOat::Patch(File* input_oat, const std::string& image_location, off_t delta,
Alex Light53cb16b2014-06-12 11:26:29 -0700209 File* output_oat, File* output_image, InstructionSet isa,
Igor Murashkin46774762014-10-22 11:37:02 -0700210 TimingLogger* timings,
211 bool output_oat_opened_from_fd,
212 bool new_oat_out) {
Alex Light53cb16b2014-06-12 11:26:29 -0700213 CHECK(Runtime::Current() == nullptr);
214 CHECK(output_image != nullptr);
215 CHECK_GE(output_image->Fd(), 0);
216 CHECK(input_oat != nullptr);
217 CHECK(output_oat != nullptr);
218 CHECK_GE(input_oat->Fd(), 0);
219 CHECK_GE(output_oat->Fd(), 0);
220 CHECK(!image_location.empty()) << "image file must have a filename.";
221
Alex Lighteefbe392014-07-08 09:53:18 -0700222 TimingLogger::ScopedTiming t("Runtime Setup", timings);
Alex Light53cb16b2014-06-12 11:26:29 -0700223
224 if (isa == kNone) {
225 Elf32_Ehdr elf_hdr;
226 if (sizeof(elf_hdr) != input_oat->Read(reinterpret_cast<char*>(&elf_hdr), sizeof(elf_hdr), 0)) {
227 LOG(ERROR) << "unable to read elf header";
228 return false;
229 }
Andreas Gampe6f611412015-01-21 22:25:24 -0800230 isa = GetInstructionSetFromELF(elf_hdr.e_machine, elf_hdr.e_flags);
Alex Light53cb16b2014-06-12 11:26:29 -0700231 }
232 const char* isa_name = GetInstructionSetString(isa);
Alex Lightcf4bf382014-07-24 11:29:14 -0700233 std::string image_filename;
234 if (!LocationToFilename(image_location, isa, &image_filename)) {
235 LOG(ERROR) << "Unable to find image at location " << image_location;
236 return false;
237 }
Alex Light53cb16b2014-06-12 11:26:29 -0700238 std::unique_ptr<File> input_image(OS::OpenFileForReading(image_filename.c_str()));
239 if (input_image.get() == nullptr) {
Alex Lightcf4bf382014-07-24 11:29:14 -0700240 LOG(ERROR) << "unable to open input image file at " << image_filename
241 << " for location " << image_location;
Alex Light53cb16b2014-06-12 11:26:29 -0700242 return false;
243 }
244 int64_t image_len = input_image->GetLength();
245 if (image_len < 0) {
246 LOG(ERROR) << "Error while getting image length";
247 return false;
248 }
249 ImageHeader image_header;
250 if (sizeof(image_header) != input_image->Read(reinterpret_cast<char*>(&image_header),
251 sizeof(image_header), 0)) {
252 LOG(ERROR) << "Unable to read image header from image file " << input_image->GetPath();
253 }
254
Igor Murashkin46774762014-10-22 11:37:02 -0700255 /*bool is_image_pic = */IsImagePic(image_header, input_image->GetPath());
256 // Nothing special to do right now since the image always needs to get patched.
257 // Perhaps in some far-off future we may have images with relative addresses that are true-PIC.
258
Alex Light53cb16b2014-06-12 11:26:29 -0700259 // Set up the runtime
Ian Rogerse63db272014-07-15 15:36:11 -0700260 RuntimeOptions options;
Alex Light53cb16b2014-06-12 11:26:29 -0700261 NoopCompilerCallbacks callbacks;
262 options.push_back(std::make_pair("compilercallbacks", &callbacks));
263 std::string img = "-Ximage:" + image_location;
264 options.push_back(std::make_pair(img.c_str(), nullptr));
265 options.push_back(std::make_pair("imageinstructionset", reinterpret_cast<const void*>(isa_name)));
Calin Juravle01aaf6e2015-06-19 22:05:39 +0100266 options.push_back(std::make_pair("-Xno-sig-chain", nullptr));
Alex Light53cb16b2014-06-12 11:26:29 -0700267 if (!Runtime::Create(options, false)) {
268 LOG(ERROR) << "Unable to initialize runtime";
269 return false;
270 }
271 // Runtime::Create acquired the mutator_lock_ that is normally given away when we Runtime::Start,
272 // give it away now and then switch to a more manageable ScopedObjectAccess.
273 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
274 ScopedObjectAccess soa(Thread::Current());
275
276 t.NewTiming("Image and oat Patching setup");
277 // Create the map where we will write the image patches to.
Alex Lighteefbe392014-07-08 09:53:18 -0700278 std::string error_msg;
Mathieu Chartier42bddce2015-11-09 15:16:56 -0800279 std::unique_ptr<MemMap> image(MemMap::MapFile(image_len,
280 PROT_READ | PROT_WRITE,
281 MAP_PRIVATE,
282 input_image->Fd(),
283 0,
284 /*low_4gb*/false,
Alex Light53cb16b2014-06-12 11:26:29 -0700285 input_image->GetPath().c_str(),
286 &error_msg));
287 if (image.get() == nullptr) {
288 LOG(ERROR) << "unable to map image file " << input_image->GetPath() << " : " << error_msg;
289 return false;
290 }
Mathieu Chartier073b16c2015-11-10 14:13:23 -0800291 gc::space::ImageSpace* ispc = Runtime::Current()->GetHeap()->GetBootImageSpace();
Alex Light53cb16b2014-06-12 11:26:29 -0700292
Igor Murashkin46774762014-10-22 11:37:02 -0700293 std::unique_ptr<ElfFile> elf(ElfFile::Open(input_oat,
Alex Light53cb16b2014-06-12 11:26:29 -0700294 PROT_READ | PROT_WRITE, MAP_PRIVATE, &error_msg));
295 if (elf.get() == nullptr) {
296 LOG(ERROR) << "unable to open oat file " << input_oat->GetPath() << " : " << error_msg;
297 return false;
298 }
299
Igor Murashkin46774762014-10-22 11:37:02 -0700300 bool skip_patching_oat = false;
301 MaybePic is_oat_pic = IsOatPic(elf.get());
302 if (is_oat_pic >= ERROR_FIRST) {
303 // Error logged by IsOatPic
304 return false;
305 } else if (is_oat_pic == PIC) {
306 // Do not need to do ELF-file patching. Create a symlink and skip the ELF patching.
307 if (!ReplaceOatFileWithSymlink(input_oat->GetPath(),
308 output_oat->GetPath(),
309 output_oat_opened_from_fd,
310 new_oat_out)) {
311 // Errors already logged by above call.
312 return false;
313 }
314 // Don't patch the OAT, since we just symlinked it. Image still needs patching.
315 skip_patching_oat = true;
316 } else {
317 CHECK(is_oat_pic == NOT_PIC);
318 }
319
Mathieu Chartier2d721012014-11-10 11:08:06 -0800320 PatchOat p(isa, elf.release(), image.release(), ispc->GetLiveBitmap(), ispc->GetMemMap(),
Alex Light53cb16b2014-06-12 11:26:29 -0700321 delta, timings);
322 t.NewTiming("Patching files");
Igor Murashkin46774762014-10-22 11:37:02 -0700323 if (!skip_patching_oat && !p.PatchElf()) {
Alex Lighta59dd802014-07-02 16:28:08 -0700324 LOG(ERROR) << "Failed to patch oat file " << input_oat->GetPath();
Alex Light53cb16b2014-06-12 11:26:29 -0700325 return false;
326 }
327 if (!p.PatchImage()) {
Alex Lighta59dd802014-07-02 16:28:08 -0700328 LOG(ERROR) << "Failed to patch image file " << input_image->GetPath();
Alex Light53cb16b2014-06-12 11:26:29 -0700329 return false;
330 }
331
332 t.NewTiming("Writing files");
Igor Murashkin46774762014-10-22 11:37:02 -0700333 if (!skip_patching_oat && !p.WriteElf(output_oat)) {
334 LOG(ERROR) << "Failed to write oat file " << input_oat->GetPath();
Alex Light53cb16b2014-06-12 11:26:29 -0700335 return false;
336 }
337 if (!p.WriteImage(output_image)) {
Igor Murashkin46774762014-10-22 11:37:02 -0700338 LOG(ERROR) << "Failed to write image file " << input_image->GetPath();
Alex Light53cb16b2014-06-12 11:26:29 -0700339 return false;
340 }
341 return true;
342}
343
344bool PatchOat::WriteElf(File* out) {
Alex Lighteefbe392014-07-08 09:53:18 -0700345 TimingLogger::ScopedTiming t("Writing Elf File", timings_);
Alex Lighta59dd802014-07-02 16:28:08 -0700346
Alex Light53cb16b2014-06-12 11:26:29 -0700347 CHECK(oat_file_.get() != nullptr);
348 CHECK(out != nullptr);
349 size_t expect = oat_file_->Size();
350 if (out->WriteFully(reinterpret_cast<char*>(oat_file_->Begin()), expect) &&
351 out->SetLength(expect) == 0) {
352 return true;
353 } else {
354 LOG(ERROR) << "Writing to oat file " << out->GetPath() << " failed.";
355 return false;
356 }
357}
358
359bool PatchOat::WriteImage(File* out) {
Alex Lighteefbe392014-07-08 09:53:18 -0700360 TimingLogger::ScopedTiming t("Writing image File", timings_);
Alex Lighta59dd802014-07-02 16:28:08 -0700361 std::string error_msg;
362
Alex Lightcf4bf382014-07-24 11:29:14 -0700363 ScopedFlock img_flock;
364 img_flock.Init(out, &error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -0700365
Alex Light53cb16b2014-06-12 11:26:29 -0700366 CHECK(image_ != nullptr);
367 CHECK(out != nullptr);
368 size_t expect = image_->Size();
369 if (out->WriteFully(reinterpret_cast<char*>(image_->Begin()), expect) &&
370 out->SetLength(expect) == 0) {
371 return true;
372 } else {
373 LOG(ERROR) << "Writing to image file " << out->GetPath() << " failed.";
374 return false;
375 }
376}
377
Igor Murashkin46774762014-10-22 11:37:02 -0700378bool PatchOat::IsImagePic(const ImageHeader& image_header, const std::string& image_path) {
379 if (!image_header.CompilePic()) {
380 if (kIsDebugBuild) {
381 LOG(INFO) << "image at location " << image_path << " was *not* compiled pic";
382 }
383 return false;
384 }
385
386 if (kIsDebugBuild) {
387 LOG(INFO) << "image at location " << image_path << " was compiled PIC";
388 }
389
390 return true;
391}
392
393PatchOat::MaybePic PatchOat::IsOatPic(const ElfFile* oat_in) {
394 if (oat_in == nullptr) {
395 LOG(ERROR) << "No ELF input oat fie available";
396 return ERROR_OAT_FILE;
397 }
398
399 const std::string& file_path = oat_in->GetFile().GetPath();
400
401 const OatHeader* oat_header = GetOatHeader(oat_in);
402 if (oat_header == nullptr) {
403 LOG(ERROR) << "Failed to find oat header in oat file " << file_path;
404 return ERROR_OAT_FILE;
405 }
406
407 if (!oat_header->IsValid()) {
408 LOG(ERROR) << "Elf file " << file_path << " has an invalid oat header";
409 return ERROR_OAT_FILE;
410 }
411
412 bool is_pic = oat_header->IsPic();
413 if (kIsDebugBuild) {
414 LOG(INFO) << "Oat file at " << file_path << " is " << (is_pic ? "PIC" : "not pic");
415 }
416
417 return is_pic ? PIC : NOT_PIC;
418}
419
420bool PatchOat::ReplaceOatFileWithSymlink(const std::string& input_oat_filename,
421 const std::string& output_oat_filename,
422 bool output_oat_opened_from_fd,
423 bool new_oat_out) {
424 // Need a file when we are PIC, since we symlink over it. Refusing to symlink into FD.
425 if (output_oat_opened_from_fd) {
426 // TODO: installd uses --output-oat-fd. Should we change class linking logic for PIC?
427 LOG(ERROR) << "No output oat filename specified, needs filename for when we are PIC";
428 return false;
429 }
430
431 // Image was PIC. Create symlink where the oat is supposed to go.
432 if (!new_oat_out) {
433 LOG(ERROR) << "Oat file " << output_oat_filename << " already exists, refusing to overwrite";
434 return false;
435 }
436
437 // Delete the original file, since we won't need it.
438 TEMP_FAILURE_RETRY(unlink(output_oat_filename.c_str()));
439
440 // Create a symlink from the old oat to the new oat
441 if (symlink(input_oat_filename.c_str(), output_oat_filename.c_str()) < 0) {
442 int err = errno;
443 LOG(ERROR) << "Failed to create symlink at " << output_oat_filename
444 << " error(" << err << "): " << strerror(err);
445 return false;
446 }
447
448 if (kIsDebugBuild) {
449 LOG(INFO) << "Created symlink " << output_oat_filename << " -> " << input_oat_filename;
450 }
451
452 return true;
453}
454
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700455class PatchOatArtFieldVisitor : public ArtFieldVisitor {
456 public:
457 explicit PatchOatArtFieldVisitor(PatchOat* patch_oat) : patch_oat_(patch_oat) {}
458
459 void Visit(ArtField* field) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
460 ArtField* const dest = patch_oat_->RelocatedCopyOf(field);
461 dest->SetDeclaringClass(patch_oat_->RelocatedAddressOfPointer(field->GetDeclaringClass()));
Mathieu Chartiere401d142015-04-22 13:56:20 -0700462 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700463
464 private:
465 PatchOat* const patch_oat_;
466};
467
468void PatchOat::PatchArtFields(const ImageHeader* image_header) {
469 PatchOatArtFieldVisitor visitor(this);
470 const auto& section = image_header->GetImageSection(ImageHeader::kSectionArtFields);
471 section.VisitPackedArtFields(&visitor, heap_->Begin());
Mathieu Chartiere401d142015-04-22 13:56:20 -0700472}
473
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700474class PatchOatArtMethodVisitor : public ArtMethodVisitor {
475 public:
476 explicit PatchOatArtMethodVisitor(PatchOat* patch_oat) : patch_oat_(patch_oat) {}
477
478 void Visit(ArtMethod* method) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
479 ArtMethod* const dest = patch_oat_->RelocatedCopyOf(method);
480 patch_oat_->FixupMethod(method, dest);
481 }
482
483 private:
484 PatchOat* const patch_oat_;
485};
486
Mathieu Chartiere401d142015-04-22 13:56:20 -0700487void PatchOat::PatchArtMethods(const ImageHeader* image_header) {
488 const auto& section = image_header->GetMethodsSection();
489 const size_t pointer_size = InstructionSetPointerSize(isa_);
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700490 PatchOatArtMethodVisitor visitor(this);
Vladimir Markocf36d492015-08-12 19:27:26 +0100491 section.VisitPackedArtMethods(&visitor, heap_->Begin(), pointer_size);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700492}
493
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700494class FixupRootVisitor : public RootVisitor {
495 public:
496 explicit FixupRootVisitor(const PatchOat* patch_oat) : patch_oat_(patch_oat) {
497 }
498
499 void VisitRoots(mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -0700500 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700501 for (size_t i = 0; i < count; ++i) {
502 *roots[i] = patch_oat_->RelocatedAddressOfPointer(*roots[i]);
503 }
504 }
505
506 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots, size_t count,
507 const RootInfo& info ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -0700508 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700509 for (size_t i = 0; i < count; ++i) {
510 roots[i]->Assign(patch_oat_->RelocatedAddressOfPointer(roots[i]->AsMirrorPtr()));
511 }
512 }
513
514 private:
515 const PatchOat* const patch_oat_;
516};
517
518void PatchOat::PatchInternedStrings(const ImageHeader* image_header) {
519 const auto& section = image_header->GetImageSection(ImageHeader::kSectionInternedStrings);
520 InternTable temp_table;
521 // Note that we require that ReadFromMemory does not make an internal copy of the elements.
522 // This also relies on visit roots not doing any verification which could fail after we update
523 // the roots to be the image addresses.
524 temp_table.ReadFromMemory(image_->Begin() + section.Offset());
525 FixupRootVisitor visitor(this);
526 temp_table.VisitRoots(&visitor, kVisitRootFlagAllRoots);
527}
528
Mathieu Chartier208a5cb2015-12-02 15:44:07 -0800529void PatchOat::PatchClassTable(const ImageHeader* image_header) {
530 const auto& section = image_header->GetImageSection(ImageHeader::kSectionClassTable);
Mathieu Chartier208a5cb2015-12-02 15:44:07 -0800531 // Note that we require that ReadFromMemory does not make an internal copy of the elements.
532 // This also relies on visit roots not doing any verification which could fail after we update
533 // the roots to be the image addresses.
534 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
535 ClassTable temp_table;
536 temp_table.ReadFromMemory(image_->Begin() + section.Offset());
537 FixupRootVisitor visitor(this);
538 BufferedRootVisitor<kDefaultBufferedRootCount> buffered_visitor(&visitor, RootInfo(kRootUnknown));
539 temp_table.VisitRoots(buffered_visitor);
540}
541
542
Mathieu Chartier4b00d342015-11-13 10:42:08 -0800543class RelocatedPointerVisitor {
544 public:
545 explicit RelocatedPointerVisitor(PatchOat* patch_oat) : patch_oat_(patch_oat) {}
546
547 template <typename T>
548 T* operator()(T* ptr) const {
549 return patch_oat_->RelocatedAddressOfPointer(ptr);
550 }
551
552 private:
553 PatchOat* const patch_oat_;
554};
555
Mathieu Chartierc7853442015-03-27 14:35:38 -0700556void PatchOat::PatchDexFileArrays(mirror::ObjectArray<mirror::Object>* img_roots) {
557 auto* dex_caches = down_cast<mirror::ObjectArray<mirror::DexCache>*>(
558 img_roots->Get(ImageHeader::kDexCaches));
Mathieu Chartier4b00d342015-11-13 10:42:08 -0800559 const size_t pointer_size = InstructionSetPointerSize(isa_);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700560 for (size_t i = 0, count = dex_caches->GetLength(); i < count; ++i) {
Vladimir Marko05792b92015-08-03 11:56:49 +0100561 auto* orig_dex_cache = dex_caches->GetWithoutChecks(i);
562 auto* copy_dex_cache = RelocatedCopyOf(orig_dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +0100563 // Though the DexCache array fields are usually treated as native pointers, we set the full
564 // 64-bit values here, clearing the top 32 bits for 32-bit targets. The zero-extension is
565 // done by casting to the unsigned type uintptr_t before casting to int64_t, i.e.
566 // static_cast<int64_t>(reinterpret_cast<uintptr_t>(image_begin_ + offset))).
567 GcRoot<mirror::String>* orig_strings = orig_dex_cache->GetStrings();
568 GcRoot<mirror::String>* relocated_strings = RelocatedAddressOfPointer(orig_strings);
569 copy_dex_cache->SetField64<false>(
570 mirror::DexCache::StringsOffset(),
571 static_cast<int64_t>(reinterpret_cast<uintptr_t>(relocated_strings)));
572 if (orig_strings != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -0800573 orig_dex_cache->FixupStrings(RelocatedCopyOf(orig_strings), RelocatedPointerVisitor(this));
Mathieu Chartierc7853442015-03-27 14:35:38 -0700574 }
Vladimir Marko05792b92015-08-03 11:56:49 +0100575 GcRoot<mirror::Class>* orig_types = orig_dex_cache->GetResolvedTypes();
576 GcRoot<mirror::Class>* relocated_types = RelocatedAddressOfPointer(orig_types);
577 copy_dex_cache->SetField64<false>(
578 mirror::DexCache::ResolvedTypesOffset(),
579 static_cast<int64_t>(reinterpret_cast<uintptr_t>(relocated_types)));
580 if (orig_types != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -0800581 orig_dex_cache->FixupResolvedTypes(RelocatedCopyOf(orig_types),
582 RelocatedPointerVisitor(this));
Vladimir Marko05792b92015-08-03 11:56:49 +0100583 }
584 ArtMethod** orig_methods = orig_dex_cache->GetResolvedMethods();
585 ArtMethod** relocated_methods = RelocatedAddressOfPointer(orig_methods);
586 copy_dex_cache->SetField64<false>(
587 mirror::DexCache::ResolvedMethodsOffset(),
588 static_cast<int64_t>(reinterpret_cast<uintptr_t>(relocated_methods)));
589 if (orig_methods != nullptr) {
590 ArtMethod** copy_methods = RelocatedCopyOf(orig_methods);
591 for (size_t j = 0, num = orig_dex_cache->NumResolvedMethods(); j != num; ++j) {
592 ArtMethod* orig = mirror::DexCache::GetElementPtrSize(orig_methods, j, pointer_size);
593 ArtMethod* copy = RelocatedAddressOfPointer(orig);
594 mirror::DexCache::SetElementPtrSize(copy_methods, j, copy, pointer_size);
595 }
596 }
597 ArtField** orig_fields = orig_dex_cache->GetResolvedFields();
598 ArtField** relocated_fields = RelocatedAddressOfPointer(orig_fields);
599 copy_dex_cache->SetField64<false>(
600 mirror::DexCache::ResolvedFieldsOffset(),
601 static_cast<int64_t>(reinterpret_cast<uintptr_t>(relocated_fields)));
602 if (orig_fields != nullptr) {
603 ArtField** copy_fields = RelocatedCopyOf(orig_fields);
604 for (size_t j = 0, num = orig_dex_cache->NumResolvedFields(); j != num; ++j) {
605 ArtField* orig = mirror::DexCache::GetElementPtrSize(orig_fields, j, pointer_size);
606 ArtField* copy = RelocatedAddressOfPointer(orig);
607 mirror::DexCache::SetElementPtrSize(copy_fields, j, copy, pointer_size);
608 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700609 }
610 }
611}
612
Alex Light53cb16b2014-06-12 11:26:29 -0700613bool PatchOat::PatchImage() {
614 ImageHeader* image_header = reinterpret_cast<ImageHeader*>(image_->Begin());
615 CHECK_GT(image_->Size(), sizeof(ImageHeader));
616 // These are the roots from the original file.
Mathieu Chartierc7853442015-03-27 14:35:38 -0700617 auto* img_roots = image_header->GetImageRoots();
Alex Light53cb16b2014-06-12 11:26:29 -0700618 image_header->RelocateImage(delta_);
619
Mathieu Chartierc7853442015-03-27 14:35:38 -0700620 PatchArtFields(image_header);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700621 PatchArtMethods(image_header);
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700622 PatchInternedStrings(image_header);
Mathieu Chartier208a5cb2015-12-02 15:44:07 -0800623 PatchClassTable(image_header);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700624 // Patch dex file int/long arrays which point to ArtFields.
625 PatchDexFileArrays(img_roots);
626
Alex Light53cb16b2014-06-12 11:26:29 -0700627 VisitObject(img_roots);
628 if (!image_header->IsValid()) {
629 LOG(ERROR) << "reloction renders image header invalid";
630 return false;
631 }
632
633 {
Alex Lighteefbe392014-07-08 09:53:18 -0700634 TimingLogger::ScopedTiming t("Walk Bitmap", timings_);
Alex Light53cb16b2014-06-12 11:26:29 -0700635 // Walk the bitmap.
636 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
637 bitmap_->Walk(PatchOat::BitmapCallback, this);
638 }
639 return true;
640}
641
642bool PatchOat::InHeap(mirror::Object* o) {
643 uintptr_t begin = reinterpret_cast<uintptr_t>(heap_->Begin());
644 uintptr_t end = reinterpret_cast<uintptr_t>(heap_->End());
645 uintptr_t obj = reinterpret_cast<uintptr_t>(o);
646 return o == nullptr || (begin <= obj && obj < end);
647}
648
649void PatchOat::PatchVisitor::operator() (mirror::Object* obj, MemberOffset off,
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700650 bool is_static_unused ATTRIBUTE_UNUSED) const {
Alex Light53cb16b2014-06-12 11:26:29 -0700651 mirror::Object* referent = obj->GetFieldObject<mirror::Object, kVerifyNone>(off);
652 DCHECK(patcher_->InHeap(referent)) << "Referent is not in the heap.";
Mathieu Chartierc7853442015-03-27 14:35:38 -0700653 mirror::Object* moved_object = patcher_->RelocatedAddressOfPointer(referent);
Alex Light53cb16b2014-06-12 11:26:29 -0700654 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(off, moved_object);
655}
656
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700657void PatchOat::PatchVisitor::operator() (mirror::Class* cls ATTRIBUTE_UNUSED,
658 mirror::Reference* ref) const {
Alex Light53cb16b2014-06-12 11:26:29 -0700659 MemberOffset off = mirror::Reference::ReferentOffset();
660 mirror::Object* referent = ref->GetReferent();
661 DCHECK(patcher_->InHeap(referent)) << "Referent is not in the heap.";
Mathieu Chartierc7853442015-03-27 14:35:38 -0700662 mirror::Object* moved_object = patcher_->RelocatedAddressOfPointer(referent);
Alex Light53cb16b2014-06-12 11:26:29 -0700663 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(off, moved_object);
664}
665
Alex Light53cb16b2014-06-12 11:26:29 -0700666// Called by BitmapCallback
667void PatchOat::VisitObject(mirror::Object* object) {
668 mirror::Object* copy = RelocatedCopyOf(object);
669 CHECK(copy != nullptr);
670 if (kUseBakerOrBrooksReadBarrier) {
671 object->AssertReadBarrierPointer();
672 if (kUseBrooksReadBarrier) {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700673 mirror::Object* moved_to = RelocatedAddressOfPointer(object);
Alex Light53cb16b2014-06-12 11:26:29 -0700674 copy->SetReadBarrierPointer(moved_to);
675 DCHECK_EQ(copy->GetReadBarrierPointer(), moved_to);
676 }
677 }
678 PatchOat::PatchVisitor visitor(this, copy);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -0700679 object->VisitReferences<kVerifyNone>(visitor, visitor);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700680 if (object->IsClass<kVerifyNone>()) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -0800681 const size_t pointer_size = InstructionSetPointerSize(isa_);
682 mirror::Class* klass = object->AsClass();
683 mirror::Class* copy_klass = down_cast<mirror::Class*>(copy);
684 RelocatedPointerVisitor native_visitor(this);
685 klass->FixupNativePointers(copy_klass, pointer_size, native_visitor);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700686 auto* vtable = klass->GetVTable();
687 if (vtable != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -0800688 vtable->Fixup(RelocatedCopyOf(vtable), pointer_size, native_visitor);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700689 }
690 auto* iftable = klass->GetIfTable();
691 if (iftable != nullptr) {
692 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
693 if (iftable->GetMethodArrayCount(i) > 0) {
694 auto* method_array = iftable->GetMethodArray(i);
695 CHECK(method_array != nullptr);
Mathieu Chartier4b00d342015-11-13 10:42:08 -0800696 method_array->Fixup(RelocatedCopyOf(method_array), pointer_size, native_visitor);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700697 }
698 }
699 }
Mathieu Chartier4b00d342015-11-13 10:42:08 -0800700 } else if (object->GetClass() == mirror::Method::StaticClass() ||
701 object->GetClass() == mirror::Constructor::StaticClass()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700702 // Need to go update the ArtMethod.
703 auto* dest = down_cast<mirror::AbstractMethod*>(copy);
704 auto* src = down_cast<mirror::AbstractMethod*>(object);
705 dest->SetArtMethod(RelocatedAddressOfPointer(src->GetArtMethod()));
Alex Light53cb16b2014-06-12 11:26:29 -0700706 }
707}
708
Mathieu Chartiere401d142015-04-22 13:56:20 -0700709void PatchOat::FixupMethod(ArtMethod* object, ArtMethod* copy) {
Mathieu Chartier2d721012014-11-10 11:08:06 -0800710 const size_t pointer_size = InstructionSetPointerSize(isa_);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700711 copy->CopyFrom(object, pointer_size);
Alex Light53cb16b2014-06-12 11:26:29 -0700712 // Just update the entry points if it looks like we should.
Alex Lighteefbe392014-07-08 09:53:18 -0700713 // TODO: sanity check all the pointers' values
Mathieu Chartiere401d142015-04-22 13:56:20 -0700714 copy->SetDeclaringClass(RelocatedAddressOfPointer(object->GetDeclaringClass()));
Vladimir Marko05792b92015-08-03 11:56:49 +0100715 copy->SetDexCacheResolvedMethods(
716 RelocatedAddressOfPointer(object->GetDexCacheResolvedMethods(pointer_size)), pointer_size);
717 copy->SetDexCacheResolvedTypes(
718 RelocatedAddressOfPointer(object->GetDexCacheResolvedTypes(pointer_size)), pointer_size);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700719 copy->SetEntryPointFromQuickCompiledCodePtrSize(RelocatedAddressOfPointer(
720 object->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size)), pointer_size);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700721 copy->SetEntryPointFromJniPtrSize(RelocatedAddressOfPointer(
722 object->GetEntryPointFromJniPtrSize(pointer_size)), pointer_size);
Alex Light53cb16b2014-06-12 11:26:29 -0700723}
724
Igor Murashkin46774762014-10-22 11:37:02 -0700725bool PatchOat::Patch(File* input_oat, off_t delta, File* output_oat, TimingLogger* timings,
726 bool output_oat_opened_from_fd, bool new_oat_out) {
Alex Light53cb16b2014-06-12 11:26:29 -0700727 CHECK(input_oat != nullptr);
728 CHECK(output_oat != nullptr);
729 CHECK_GE(input_oat->Fd(), 0);
730 CHECK_GE(output_oat->Fd(), 0);
Alex Lighteefbe392014-07-08 09:53:18 -0700731 TimingLogger::ScopedTiming t("Setup Oat File Patching", timings);
Alex Light53cb16b2014-06-12 11:26:29 -0700732
733 std::string error_msg;
Igor Murashkin46774762014-10-22 11:37:02 -0700734 std::unique_ptr<ElfFile> elf(ElfFile::Open(input_oat,
Alex Light53cb16b2014-06-12 11:26:29 -0700735 PROT_READ | PROT_WRITE, MAP_PRIVATE, &error_msg));
736 if (elf.get() == nullptr) {
737 LOG(ERROR) << "unable to open oat file " << input_oat->GetPath() << " : " << error_msg;
738 return false;
739 }
740
Igor Murashkin46774762014-10-22 11:37:02 -0700741 MaybePic is_oat_pic = IsOatPic(elf.get());
742 if (is_oat_pic >= ERROR_FIRST) {
743 // Error logged by IsOatPic
744 return false;
745 } else if (is_oat_pic == PIC) {
746 // Do not need to do ELF-file patching. Create a symlink and skip the rest.
747 // Any errors will be logged by the function call.
748 return ReplaceOatFileWithSymlink(input_oat->GetPath(),
749 output_oat->GetPath(),
750 output_oat_opened_from_fd,
751 new_oat_out);
752 } else {
753 CHECK(is_oat_pic == NOT_PIC);
754 }
755
Alex Light53cb16b2014-06-12 11:26:29 -0700756 PatchOat p(elf.release(), delta, timings);
757 t.NewTiming("Patch Oat file");
758 if (!p.PatchElf()) {
759 return false;
760 }
761
762 t.NewTiming("Writing oat file");
763 if (!p.WriteElf(output_oat)) {
764 return false;
765 }
766 return true;
767}
768
Tong Shen62d1ca32014-09-03 17:24:56 -0700769template <typename ElfFileImpl>
770bool PatchOat::PatchOatHeader(ElfFileImpl* oat_file) {
771 auto rodata_sec = oat_file->FindSectionByName(".rodata");
Alex Lighta59dd802014-07-02 16:28:08 -0700772 if (rodata_sec == nullptr) {
773 return false;
774 }
Tong Shen62d1ca32014-09-03 17:24:56 -0700775 OatHeader* oat_header = reinterpret_cast<OatHeader*>(oat_file->Begin() + rodata_sec->sh_offset);
Alex Lighta59dd802014-07-02 16:28:08 -0700776 if (!oat_header->IsValid()) {
Tong Shen62d1ca32014-09-03 17:24:56 -0700777 LOG(ERROR) << "Elf file " << oat_file->GetFile().GetPath() << " has an invalid oat header";
Alex Lighta59dd802014-07-02 16:28:08 -0700778 return false;
779 }
780 oat_header->RelocateOat(delta_);
781 return true;
782}
783
Alex Light53cb16b2014-06-12 11:26:29 -0700784bool PatchOat::PatchElf() {
Ian Rogersd4c4d952014-10-16 20:31:53 -0700785 if (oat_file_->Is64Bit())
Tong Shen62d1ca32014-09-03 17:24:56 -0700786 return PatchElf<ElfFileImpl64>(oat_file_->GetImpl64());
787 else
788 return PatchElf<ElfFileImpl32>(oat_file_->GetImpl32());
789}
790
791template <typename ElfFileImpl>
792bool PatchOat::PatchElf(ElfFileImpl* oat_file) {
Alex Lighta59dd802014-07-02 16:28:08 -0700793 TimingLogger::ScopedTiming t("Fixup Elf Text Section", timings_);
Vladimir Marko3fc99032015-05-13 19:06:30 +0100794
795 // Fix up absolute references to locations within the boot image.
David Srbecky2f6cdb02015-04-11 00:17:53 +0100796 if (!oat_file->ApplyOatPatchesTo(".text", delta_)) {
Alex Lighta59dd802014-07-02 16:28:08 -0700797 return false;
798 }
799
Vladimir Marko3fc99032015-05-13 19:06:30 +0100800 // Update the OatHeader fields referencing the boot image.
Tong Shen62d1ca32014-09-03 17:24:56 -0700801 if (!PatchOatHeader<ElfFileImpl>(oat_file)) {
Alex Lighta59dd802014-07-02 16:28:08 -0700802 return false;
803 }
804
Vladimir Marko3fc99032015-05-13 19:06:30 +0100805 bool need_boot_oat_fixup = true;
Ian Rogersd4c4d952014-10-16 20:31:53 -0700806 for (unsigned int i = 0; i < oat_file->GetProgramHeaderNum(); ++i) {
Tong Shen62d1ca32014-09-03 17:24:56 -0700807 auto hdr = oat_file->GetProgramHeader(i);
Vladimir Marko3fc99032015-05-13 19:06:30 +0100808 if (hdr->p_type == PT_LOAD && hdr->p_vaddr == 0u) {
809 need_boot_oat_fixup = false;
Ian Rogersd4c4d952014-10-16 20:31:53 -0700810 break;
Alex Light53cb16b2014-06-12 11:26:29 -0700811 }
812 }
Vladimir Marko3fc99032015-05-13 19:06:30 +0100813 if (!need_boot_oat_fixup) {
814 // This is an app oat file that can be loaded at an arbitrary address in memory.
815 // Boot image references were patched above and there's nothing else to do.
Alex Lighta59dd802014-07-02 16:28:08 -0700816 return true;
817 }
Tong Shen62d1ca32014-09-03 17:24:56 -0700818
Vladimir Marko3fc99032015-05-13 19:06:30 +0100819 // This is a boot oat file that's loaded at a particular address and we need
820 // to patch all absolute addresses, starting with ELF program headers.
821
Tong Shen62d1ca32014-09-03 17:24:56 -0700822 t.NewTiming("Fixup Elf Headers");
823 // Fixup Phdr's
824 oat_file->FixupProgramHeaders(delta_);
825
Alex Lighta59dd802014-07-02 16:28:08 -0700826 t.NewTiming("Fixup Section Headers");
Tong Shen62d1ca32014-09-03 17:24:56 -0700827 // Fixup Shdr's
828 oat_file->FixupSectionHeaders(delta_);
Alex Light53cb16b2014-06-12 11:26:29 -0700829
Alex Lighta59dd802014-07-02 16:28:08 -0700830 t.NewTiming("Fixup Dynamics");
Tong Shen62d1ca32014-09-03 17:24:56 -0700831 oat_file->FixupDynamic(delta_);
Alex Light53cb16b2014-06-12 11:26:29 -0700832
833 t.NewTiming("Fixup Elf Symbols");
834 // Fixup dynsym
Tong Shen62d1ca32014-09-03 17:24:56 -0700835 if (!oat_file->FixupSymbols(delta_, true)) {
Alex Light53cb16b2014-06-12 11:26:29 -0700836 return false;
837 }
Alex Light53cb16b2014-06-12 11:26:29 -0700838 // Fixup symtab
Tong Shen62d1ca32014-09-03 17:24:56 -0700839 if (!oat_file->FixupSymbols(delta_, false)) {
840 return false;
Alex Light53cb16b2014-06-12 11:26:29 -0700841 }
842
Yevgeny Roubane3ea8382014-08-08 16:29:38 +0700843 t.NewTiming("Fixup Debug Sections");
Tong Shen62d1ca32014-09-03 17:24:56 -0700844 if (!oat_file->FixupDebugSections(delta_)) {
Yevgeny Roubane3ea8382014-08-08 16:29:38 +0700845 return false;
846 }
847
Alex Light53cb16b2014-06-12 11:26:29 -0700848 return true;
849}
850
Alex Light53cb16b2014-06-12 11:26:29 -0700851static int orig_argc;
852static char** orig_argv;
853
854static std::string CommandLine() {
855 std::vector<std::string> command;
856 for (int i = 0; i < orig_argc; ++i) {
857 command.push_back(orig_argv[i]);
858 }
859 return Join(command, ' ');
860}
861
862static void UsageErrorV(const char* fmt, va_list ap) {
863 std::string error;
864 StringAppendV(&error, fmt, ap);
865 LOG(ERROR) << error;
866}
867
868static void UsageError(const char* fmt, ...) {
869 va_list ap;
870 va_start(ap, fmt);
871 UsageErrorV(fmt, ap);
872 va_end(ap);
873}
874
Andreas Gampe794ad762015-02-23 08:12:24 -0800875NO_RETURN static void Usage(const char *fmt, ...) {
Alex Light53cb16b2014-06-12 11:26:29 -0700876 va_list ap;
877 va_start(ap, fmt);
878 UsageErrorV(fmt, ap);
879 va_end(ap);
880
881 UsageError("Command: %s", CommandLine().c_str());
882 UsageError("Usage: patchoat [options]...");
883 UsageError("");
884 UsageError(" --instruction-set=<isa>: Specifies the instruction set the patched code is");
885 UsageError(" compiled for. Required if you use --input-oat-location");
886 UsageError("");
887 UsageError(" --input-oat-file=<file.oat>: Specifies the exact filename of the oat file to be");
888 UsageError(" patched.");
889 UsageError("");
890 UsageError(" --input-oat-fd=<file-descriptor>: Specifies the file-descriptor of the oat file");
891 UsageError(" to be patched.");
892 UsageError("");
893 UsageError(" --input-oat-location=<file.oat>: Specifies the 'location' to read the patched");
894 UsageError(" oat file from. If used one must also supply the --instruction-set");
895 UsageError("");
896 UsageError(" --input-image-location=<file.art>: Specifies the 'location' of the image file to");
897 UsageError(" be patched. If --instruction-set is not given it will use the instruction set");
898 UsageError(" extracted from the --input-oat-file.");
899 UsageError("");
900 UsageError(" --output-oat-file=<file.oat>: Specifies the exact file to write the patched oat");
901 UsageError(" file to.");
902 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700903 UsageError(" --output-oat-fd=<file-descriptor>: Specifies the file-descriptor to write the");
904 UsageError(" the patched oat file to.");
905 UsageError("");
906 UsageError(" --output-image-file=<file.art>: Specifies the exact file to write the patched");
907 UsageError(" image file to.");
908 UsageError("");
909 UsageError(" --output-image-fd=<file-descriptor>: Specifies the file-descriptor to write the");
910 UsageError(" the patched image file to.");
911 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700912 UsageError(" --orig-base-offset=<original-base-offset>: Specify the base offset the input file");
913 UsageError(" was compiled with. This is needed if one is specifying a --base-offset");
914 UsageError("");
915 UsageError(" --base-offset=<new-base-offset>: Specify the base offset we will repatch the");
916 UsageError(" given files to use. This requires that --orig-base-offset is also given.");
917 UsageError("");
918 UsageError(" --base-offset-delta=<delta>: Specify the amount to change the old base-offset by.");
919 UsageError(" This value may be negative.");
920 UsageError("");
Alex Light0eb76d22015-08-11 18:03:47 -0700921 UsageError(" --patched-image-file=<file.art>: Relocate the oat file to be the same as the");
922 UsageError(" given image file.");
Alex Light53cb16b2014-06-12 11:26:29 -0700923 UsageError("");
Alex Light0eb76d22015-08-11 18:03:47 -0700924 UsageError(" --patched-image-location=<file.art>: Relocate the oat file to be the same as the");
925 UsageError(" image at the given location. If used one must also specify the");
Alex Lighta59dd802014-07-02 16:28:08 -0700926 UsageError(" --instruction-set flag. It will search for this image in the same way that");
927 UsageError(" is done when loading one.");
Alex Light53cb16b2014-06-12 11:26:29 -0700928 UsageError("");
Alex Lightcf4bf382014-07-24 11:29:14 -0700929 UsageError(" --lock-output: Obtain a flock on output oat file before starting.");
930 UsageError("");
931 UsageError(" --no-lock-output: Do not attempt to obtain a flock on output oat file.");
932 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700933 UsageError(" --dump-timings: dump out patch timing information");
934 UsageError("");
935 UsageError(" --no-dump-timings: do not dump out patch timing information");
936 UsageError("");
937
938 exit(EXIT_FAILURE);
939}
940
Alex Lighteefbe392014-07-08 09:53:18 -0700941static bool ReadBaseDelta(const char* name, off_t* delta, std::string* error_msg) {
Alex Light53cb16b2014-06-12 11:26:29 -0700942 CHECK(name != nullptr);
943 CHECK(delta != nullptr);
944 std::unique_ptr<File> file;
945 if (OS::FileExists(name)) {
946 file.reset(OS::OpenFileForReading(name));
947 if (file.get() == nullptr) {
Alex Lighteefbe392014-07-08 09:53:18 -0700948 *error_msg = "Failed to open file %s for reading";
Alex Light53cb16b2014-06-12 11:26:29 -0700949 return false;
950 }
951 } else {
Alex Lighteefbe392014-07-08 09:53:18 -0700952 *error_msg = "File %s does not exist";
Alex Light53cb16b2014-06-12 11:26:29 -0700953 return false;
954 }
955 CHECK(file.get() != nullptr);
956 ImageHeader hdr;
957 if (sizeof(hdr) != file->Read(reinterpret_cast<char*>(&hdr), sizeof(hdr), 0)) {
Alex Lighteefbe392014-07-08 09:53:18 -0700958 *error_msg = "Failed to read file %s";
Alex Light53cb16b2014-06-12 11:26:29 -0700959 return false;
960 }
961 if (!hdr.IsValid()) {
Alex Lighteefbe392014-07-08 09:53:18 -0700962 *error_msg = "%s does not contain a valid image header.";
Alex Light53cb16b2014-06-12 11:26:29 -0700963 return false;
964 }
965 *delta = hdr.GetPatchDelta();
966 return true;
967}
968
969static File* CreateOrOpen(const char* name, bool* created) {
970 if (OS::FileExists(name)) {
971 *created = false;
972 return OS::OpenFileReadWrite(name);
973 } else {
974 *created = true;
Alex Lightcf4bf382014-07-24 11:29:14 -0700975 std::unique_ptr<File> f(OS::CreateEmptyFile(name));
976 if (f.get() != nullptr) {
977 if (fchmod(f->Fd(), 0644) != 0) {
978 PLOG(ERROR) << "Unable to make " << name << " world readable";
Brian Carlstrom8c52a3f2014-09-30 16:18:01 -0700979 TEMP_FAILURE_RETRY(unlink(name));
Alex Lightcf4bf382014-07-24 11:29:14 -0700980 return nullptr;
981 }
982 }
983 return f.release();
Alex Light53cb16b2014-06-12 11:26:29 -0700984 }
985}
986
Andreas Gampe4303ba92014-11-06 01:00:46 -0800987// Either try to close the file (close=true), or erase it.
988static bool FinishFile(File* file, bool close) {
989 if (close) {
990 if (file->FlushCloseOrErase() != 0) {
991 PLOG(ERROR) << "Failed to flush and close file.";
992 return false;
993 }
994 return true;
995 } else {
996 file->Erase();
997 return false;
998 }
999}
1000
Alex Lighteefbe392014-07-08 09:53:18 -07001001static int patchoat(int argc, char **argv) {
Alex Light53cb16b2014-06-12 11:26:29 -07001002 InitLogging(argv);
Mathieu Chartier6e88ef62014-10-14 15:01:24 -07001003 MemMap::Init();
Alex Light53cb16b2014-06-12 11:26:29 -07001004 const bool debug = kIsDebugBuild;
1005 orig_argc = argc;
1006 orig_argv = argv;
1007 TimingLogger timings("patcher", false, false);
1008
1009 InitLogging(argv);
1010
1011 // Skip over the command name.
1012 argv++;
1013 argc--;
1014
1015 if (argc == 0) {
1016 Usage("No arguments specified");
1017 }
1018
1019 timings.StartTiming("Patchoat");
1020
1021 // cmd line args
1022 bool isa_set = false;
1023 InstructionSet isa = kNone;
1024 std::string input_oat_filename;
1025 std::string input_oat_location;
1026 int input_oat_fd = -1;
1027 bool have_input_oat = false;
1028 std::string input_image_location;
1029 std::string output_oat_filename;
Alex Light53cb16b2014-06-12 11:26:29 -07001030 int output_oat_fd = -1;
1031 bool have_output_oat = false;
1032 std::string output_image_filename;
Alex Light53cb16b2014-06-12 11:26:29 -07001033 int output_image_fd = -1;
1034 bool have_output_image = false;
1035 uintptr_t base_offset = 0;
1036 bool base_offset_set = false;
1037 uintptr_t orig_base_offset = 0;
1038 bool orig_base_offset_set = false;
1039 off_t base_delta = 0;
1040 bool base_delta_set = false;
Alex Light0eb76d22015-08-11 18:03:47 -07001041 bool match_delta = false;
Alex Light53cb16b2014-06-12 11:26:29 -07001042 std::string patched_image_filename;
1043 std::string patched_image_location;
1044 bool dump_timings = kIsDebugBuild;
Alex Lightcf4bf382014-07-24 11:29:14 -07001045 bool lock_output = true;
Alex Light53cb16b2014-06-12 11:26:29 -07001046
Ian Rogersd4c4d952014-10-16 20:31:53 -07001047 for (int i = 0; i < argc; ++i) {
Alex Light53cb16b2014-06-12 11:26:29 -07001048 const StringPiece option(argv[i]);
1049 const bool log_options = false;
1050 if (log_options) {
1051 LOG(INFO) << "patchoat: option[" << i << "]=" << argv[i];
1052 }
Alex Light53cb16b2014-06-12 11:26:29 -07001053 if (option.starts_with("--instruction-set=")) {
1054 isa_set = true;
1055 const char* isa_str = option.substr(strlen("--instruction-set=")).data();
Andreas Gampe20c89302014-08-19 17:28:06 -07001056 isa = GetInstructionSetFromString(isa_str);
1057 if (isa == kNone) {
1058 Usage("Unknown or invalid instruction set %s", isa_str);
Alex Light53cb16b2014-06-12 11:26:29 -07001059 }
1060 } else if (option.starts_with("--input-oat-location=")) {
1061 if (have_input_oat) {
1062 Usage("Only one of --input-oat-file, --input-oat-location and --input-oat-fd may be used.");
1063 }
1064 have_input_oat = true;
1065 input_oat_location = option.substr(strlen("--input-oat-location=")).data();
1066 } else if (option.starts_with("--input-oat-file=")) {
1067 if (have_input_oat) {
1068 Usage("Only one of --input-oat-file, --input-oat-location and --input-oat-fd may be used.");
1069 }
1070 have_input_oat = true;
1071 input_oat_filename = option.substr(strlen("--input-oat-file=")).data();
1072 } else if (option.starts_with("--input-oat-fd=")) {
1073 if (have_input_oat) {
1074 Usage("Only one of --input-oat-file, --input-oat-location and --input-oat-fd may be used.");
1075 }
1076 have_input_oat = true;
1077 const char* oat_fd_str = option.substr(strlen("--input-oat-fd=")).data();
1078 if (!ParseInt(oat_fd_str, &input_oat_fd)) {
1079 Usage("Failed to parse --input-oat-fd argument '%s' as an integer", oat_fd_str);
1080 }
1081 if (input_oat_fd < 0) {
1082 Usage("--input-oat-fd pass a negative value %d", input_oat_fd);
1083 }
1084 } else if (option.starts_with("--input-image-location=")) {
1085 input_image_location = option.substr(strlen("--input-image-location=")).data();
Alex Light53cb16b2014-06-12 11:26:29 -07001086 } else if (option.starts_with("--output-oat-file=")) {
1087 if (have_output_oat) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001088 Usage("Only one of --output-oat-file, and --output-oat-fd may be used.");
Alex Light53cb16b2014-06-12 11:26:29 -07001089 }
1090 have_output_oat = true;
1091 output_oat_filename = option.substr(strlen("--output-oat-file=")).data();
1092 } else if (option.starts_with("--output-oat-fd=")) {
1093 if (have_output_oat) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001094 Usage("Only one of --output-oat-file, --output-oat-fd may be used.");
Alex Light53cb16b2014-06-12 11:26:29 -07001095 }
1096 have_output_oat = true;
1097 const char* oat_fd_str = option.substr(strlen("--output-oat-fd=")).data();
1098 if (!ParseInt(oat_fd_str, &output_oat_fd)) {
1099 Usage("Failed to parse --output-oat-fd argument '%s' as an integer", oat_fd_str);
1100 }
1101 if (output_oat_fd < 0) {
1102 Usage("--output-oat-fd pass a negative value %d", output_oat_fd);
1103 }
Alex Light53cb16b2014-06-12 11:26:29 -07001104 } else if (option.starts_with("--output-image-file=")) {
1105 if (have_output_image) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001106 Usage("Only one of --output-image-file, and --output-image-fd may be used.");
Alex Light53cb16b2014-06-12 11:26:29 -07001107 }
1108 have_output_image = true;
1109 output_image_filename = option.substr(strlen("--output-image-file=")).data();
1110 } else if (option.starts_with("--output-image-fd=")) {
1111 if (have_output_image) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001112 Usage("Only one of --output-image-file, and --output-image-fd may be used.");
Alex Light53cb16b2014-06-12 11:26:29 -07001113 }
1114 have_output_image = true;
1115 const char* image_fd_str = option.substr(strlen("--output-image-fd=")).data();
1116 if (!ParseInt(image_fd_str, &output_image_fd)) {
1117 Usage("Failed to parse --output-image-fd argument '%s' as an integer", image_fd_str);
1118 }
1119 if (output_image_fd < 0) {
1120 Usage("--output-image-fd pass a negative value %d", output_image_fd);
1121 }
1122 } else if (option.starts_with("--orig-base-offset=")) {
1123 const char* orig_base_offset_str = option.substr(strlen("--orig-base-offset=")).data();
1124 orig_base_offset_set = true;
1125 if (!ParseUint(orig_base_offset_str, &orig_base_offset)) {
1126 Usage("Failed to parse --orig-base-offset argument '%s' as an uintptr_t",
1127 orig_base_offset_str);
1128 }
1129 } else if (option.starts_with("--base-offset=")) {
1130 const char* base_offset_str = option.substr(strlen("--base-offset=")).data();
1131 base_offset_set = true;
1132 if (!ParseUint(base_offset_str, &base_offset)) {
1133 Usage("Failed to parse --base-offset argument '%s' as an uintptr_t", base_offset_str);
1134 }
1135 } else if (option.starts_with("--base-offset-delta=")) {
1136 const char* base_delta_str = option.substr(strlen("--base-offset-delta=")).data();
1137 base_delta_set = true;
1138 if (!ParseInt(base_delta_str, &base_delta)) {
1139 Usage("Failed to parse --base-offset-delta argument '%s' as an off_t", base_delta_str);
1140 }
1141 } else if (option.starts_with("--patched-image-location=")) {
1142 patched_image_location = option.substr(strlen("--patched-image-location=")).data();
1143 } else if (option.starts_with("--patched-image-file=")) {
1144 patched_image_filename = option.substr(strlen("--patched-image-file=")).data();
Alex Lightcf4bf382014-07-24 11:29:14 -07001145 } else if (option == "--lock-output") {
1146 lock_output = true;
1147 } else if (option == "--no-lock-output") {
1148 lock_output = false;
Alex Light53cb16b2014-06-12 11:26:29 -07001149 } else if (option == "--dump-timings") {
1150 dump_timings = true;
1151 } else if (option == "--no-dump-timings") {
1152 dump_timings = false;
1153 } else {
1154 Usage("Unknown argument %s", option.data());
1155 }
1156 }
1157
1158 {
1159 // Only 1 of these may be set.
1160 uint32_t cnt = 0;
1161 cnt += (base_delta_set) ? 1 : 0;
1162 cnt += (base_offset_set && orig_base_offset_set) ? 1 : 0;
1163 cnt += (!patched_image_filename.empty()) ? 1 : 0;
1164 cnt += (!patched_image_location.empty()) ? 1 : 0;
1165 if (cnt > 1) {
1166 Usage("Only one of --base-offset/--orig-base-offset, --base-offset-delta, "
1167 "--patched-image-filename or --patched-image-location may be used.");
1168 } else if (cnt == 0) {
1169 Usage("Must specify --base-offset-delta, --base-offset and --orig-base-offset, "
1170 "--patched-image-location or --patched-image-file");
1171 }
1172 }
1173
1174 if (have_input_oat != have_output_oat) {
1175 Usage("Either both input and output oat must be supplied or niether must be.");
1176 }
1177
1178 if ((!input_image_location.empty()) != have_output_image) {
1179 Usage("Either both input and output image must be supplied or niether must be.");
1180 }
1181
1182 // We know we have both the input and output so rename for clarity.
1183 bool have_image_files = have_output_image;
1184 bool have_oat_files = have_output_oat;
1185
1186 if (!have_oat_files && !have_image_files) {
1187 Usage("Must be patching either an oat or an image file or both.");
1188 }
1189
1190 if (!have_oat_files && !isa_set) {
1191 Usage("Must include ISA if patching an image file without an oat file.");
1192 }
1193
1194 if (!input_oat_location.empty()) {
1195 if (!isa_set) {
1196 Usage("specifying a location requires specifying an instruction set");
1197 }
Alex Lightcf4bf382014-07-24 11:29:14 -07001198 if (!LocationToFilename(input_oat_location, isa, &input_oat_filename)) {
1199 Usage("Unable to find filename for input oat location %s", input_oat_location.c_str());
1200 }
Alex Light53cb16b2014-06-12 11:26:29 -07001201 if (debug) {
1202 LOG(INFO) << "Using input-oat-file " << input_oat_filename;
1203 }
1204 }
Alex Light53cb16b2014-06-12 11:26:29 -07001205 if (!patched_image_location.empty()) {
1206 if (!isa_set) {
1207 Usage("specifying a location requires specifying an instruction set");
1208 }
Alex Lighta59dd802014-07-02 16:28:08 -07001209 std::string system_filename;
1210 bool has_system = false;
1211 std::string cache_filename;
1212 bool has_cache = false;
1213 bool has_android_data_unused = false;
Andreas Gampe3c13a792014-09-18 20:56:04 -07001214 bool is_global_cache = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001215 if (!gc::space::ImageSpace::FindImageFilename(patched_image_location.c_str(), isa,
1216 &system_filename, &has_system, &cache_filename,
Andreas Gampe3c13a792014-09-18 20:56:04 -07001217 &has_android_data_unused, &has_cache,
1218 &is_global_cache)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001219 Usage("Unable to determine image file for location %s", patched_image_location.c_str());
1220 }
1221 if (has_cache) {
1222 patched_image_filename = cache_filename;
1223 } else if (has_system) {
1224 LOG(WARNING) << "Only image file found was in /system for image location "
1225 << patched_image_location;
1226 patched_image_filename = system_filename;
1227 } else {
1228 Usage("Unable to determine image file for location %s", patched_image_location.c_str());
1229 }
Alex Light53cb16b2014-06-12 11:26:29 -07001230 if (debug) {
1231 LOG(INFO) << "Using patched-image-file " << patched_image_filename;
1232 }
1233 }
1234
1235 if (!base_delta_set) {
1236 if (orig_base_offset_set && base_offset_set) {
1237 base_delta_set = true;
1238 base_delta = base_offset - orig_base_offset;
1239 } else if (!patched_image_filename.empty()) {
Alex Light0eb76d22015-08-11 18:03:47 -07001240 if (have_image_files) {
1241 Usage("--patched-image-location should not be used when patching other images");
1242 }
Alex Light53cb16b2014-06-12 11:26:29 -07001243 base_delta_set = true;
Alex Light0eb76d22015-08-11 18:03:47 -07001244 match_delta = true;
Alex Light53cb16b2014-06-12 11:26:29 -07001245 std::string error_msg;
Alex Lighteefbe392014-07-08 09:53:18 -07001246 if (!ReadBaseDelta(patched_image_filename.c_str(), &base_delta, &error_msg)) {
Alex Light53cb16b2014-06-12 11:26:29 -07001247 Usage(error_msg.c_str(), patched_image_filename.c_str());
1248 }
1249 } else {
1250 if (base_offset_set) {
1251 Usage("Unable to determine original base offset.");
1252 } else {
1253 Usage("Must supply a desired new offset or delta.");
1254 }
1255 }
1256 }
1257
1258 if (!IsAligned<kPageSize>(base_delta)) {
1259 Usage("Base offset/delta must be alligned to a pagesize (0x%08x) boundary.", kPageSize);
1260 }
1261
1262 // Do we need to cleanup output files if we fail?
1263 bool new_image_out = false;
1264 bool new_oat_out = false;
1265
1266 std::unique_ptr<File> input_oat;
1267 std::unique_ptr<File> output_oat;
1268 std::unique_ptr<File> output_image;
1269
1270 if (have_image_files) {
1271 CHECK(!input_image_location.empty());
1272
1273 if (output_image_fd != -1) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001274 if (output_image_filename.empty()) {
1275 output_image_filename = "output-image-file";
1276 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001277 output_image.reset(new File(output_image_fd, output_image_filename, true));
Alex Light53cb16b2014-06-12 11:26:29 -07001278 } else {
1279 CHECK(!output_image_filename.empty());
1280 output_image.reset(CreateOrOpen(output_image_filename.c_str(), &new_image_out));
1281 }
1282 } else {
1283 CHECK(output_image_filename.empty() && output_image_fd == -1 && input_image_location.empty());
1284 }
1285
1286 if (have_oat_files) {
1287 if (input_oat_fd != -1) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001288 if (input_oat_filename.empty()) {
1289 input_oat_filename = "input-oat-file";
1290 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001291 input_oat.reset(new File(input_oat_fd, input_oat_filename, false));
Julien Delayena473f512015-03-05 16:37:52 +01001292 if (input_oat_fd == output_oat_fd) {
1293 input_oat.get()->DisableAutoClose();
1294 }
Igor Murashkin46774762014-10-22 11:37:02 -07001295 if (input_oat == nullptr) {
1296 // Unlikely, but ensure exhaustive logging in non-0 exit code case
1297 LOG(ERROR) << "Failed to open input oat file by its FD" << input_oat_fd;
1298 }
Alex Light53cb16b2014-06-12 11:26:29 -07001299 } else {
1300 CHECK(!input_oat_filename.empty());
1301 input_oat.reset(OS::OpenFileForReading(input_oat_filename.c_str()));
Igor Murashkin46774762014-10-22 11:37:02 -07001302 if (input_oat == nullptr) {
1303 int err = errno;
1304 LOG(ERROR) << "Failed to open input oat file " << input_oat_filename
1305 << ": " << strerror(err) << "(" << err << ")";
Andreas Gampe1c83cbc2014-07-22 18:52:29 -07001306 }
Alex Light53cb16b2014-06-12 11:26:29 -07001307 }
1308
1309 if (output_oat_fd != -1) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001310 if (output_oat_filename.empty()) {
1311 output_oat_filename = "output-oat-file";
Alex Lighta59dd802014-07-02 16:28:08 -07001312 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001313 output_oat.reset(new File(output_oat_fd, output_oat_filename, true));
Igor Murashkin46774762014-10-22 11:37:02 -07001314 if (output_oat == nullptr) {
1315 // Unlikely, but ensure exhaustive logging in non-0 exit code case
1316 LOG(ERROR) << "Failed to open output oat file by its FD" << output_oat_fd;
1317 }
Alex Light53cb16b2014-06-12 11:26:29 -07001318 } else {
1319 CHECK(!output_oat_filename.empty());
1320 output_oat.reset(CreateOrOpen(output_oat_filename.c_str(), &new_oat_out));
Igor Murashkin46774762014-10-22 11:37:02 -07001321 if (output_oat == nullptr) {
1322 int err = errno;
1323 LOG(ERROR) << "Failed to open output oat file " << output_oat_filename
1324 << ": " << strerror(err) << "(" << err << ")";
1325 }
Alex Light53cb16b2014-06-12 11:26:29 -07001326 }
1327 }
1328
Igor Murashkin46774762014-10-22 11:37:02 -07001329 // TODO: get rid of this.
Alex Light53cb16b2014-06-12 11:26:29 -07001330 auto cleanup = [&output_image_filename, &output_oat_filename,
1331 &new_oat_out, &new_image_out, &timings, &dump_timings](bool success) {
1332 timings.EndTiming();
1333 if (!success) {
1334 if (new_oat_out) {
1335 CHECK(!output_oat_filename.empty());
Brian Carlstrom8c52a3f2014-09-30 16:18:01 -07001336 TEMP_FAILURE_RETRY(unlink(output_oat_filename.c_str()));
Alex Light53cb16b2014-06-12 11:26:29 -07001337 }
1338 if (new_image_out) {
1339 CHECK(!output_image_filename.empty());
Brian Carlstrom8c52a3f2014-09-30 16:18:01 -07001340 TEMP_FAILURE_RETRY(unlink(output_image_filename.c_str()));
Alex Light53cb16b2014-06-12 11:26:29 -07001341 }
1342 }
1343 if (dump_timings) {
1344 LOG(INFO) << Dumpable<TimingLogger>(timings);
1345 }
Igor Murashkin46774762014-10-22 11:37:02 -07001346
1347 if (kIsDebugBuild) {
1348 LOG(INFO) << "Cleaning up.. success? " << success;
1349 }
Alex Light53cb16b2014-06-12 11:26:29 -07001350 };
1351
Igor Murashkin46774762014-10-22 11:37:02 -07001352 if (have_oat_files && (input_oat.get() == nullptr || output_oat.get() == nullptr)) {
1353 LOG(ERROR) << "Failed to open input/output oat files";
1354 cleanup(false);
1355 return EXIT_FAILURE;
1356 } else if (have_image_files && output_image.get() == nullptr) {
1357 LOG(ERROR) << "Failed to open output image file";
Alex Lightcf4bf382014-07-24 11:29:14 -07001358 cleanup(false);
1359 return EXIT_FAILURE;
1360 }
1361
Alex Light0eb76d22015-08-11 18:03:47 -07001362 if (match_delta) {
1363 CHECK(!have_image_files); // We will not do this with images.
1364 std::string error_msg;
1365 // Figure out what the current delta is so we can match it to the desired delta.
1366 std::unique_ptr<ElfFile> elf(ElfFile::Open(input_oat.get(), PROT_READ, MAP_PRIVATE,
1367 &error_msg));
1368 off_t current_delta = 0;
1369 if (elf.get() == nullptr) {
1370 LOG(ERROR) << "unable to open oat file " << input_oat->GetPath() << " : " << error_msg;
1371 cleanup(false);
1372 return EXIT_FAILURE;
1373 } else if (!ReadOatPatchDelta(elf.get(), &current_delta, &error_msg)) {
1374 LOG(ERROR) << "Unable to get current delta: " << error_msg;
1375 cleanup(false);
1376 return EXIT_FAILURE;
1377 }
1378 // Before this line base_delta is the desired final delta. We need it to be the actual amount to
1379 // change everything by. We subtract the current delta from it to make it this.
1380 base_delta -= current_delta;
1381 if (!IsAligned<kPageSize>(base_delta)) {
1382 LOG(ERROR) << "Given image file was relocated by an illegal delta";
1383 cleanup(false);
1384 return false;
1385 }
1386 }
1387
Igor Murashkin46774762014-10-22 11:37:02 -07001388 if (debug) {
1389 LOG(INFO) << "moving offset by " << base_delta
1390 << " (0x" << std::hex << base_delta << ") bytes or "
1391 << std::dec << (base_delta/kPageSize) << " pages.";
1392 }
1393
1394 // TODO: is it going to be promatic to unlink a file that was flock-ed?
Alex Lightcf4bf382014-07-24 11:29:14 -07001395 ScopedFlock output_oat_lock;
1396 if (lock_output) {
1397 std::string error_msg;
1398 if (have_oat_files && !output_oat_lock.Init(output_oat.get(), &error_msg)) {
1399 LOG(ERROR) << "Unable to lock output oat " << output_image->GetPath() << ": " << error_msg;
1400 cleanup(false);
1401 return EXIT_FAILURE;
1402 }
1403 }
1404
Alex Light53cb16b2014-06-12 11:26:29 -07001405 bool ret;
1406 if (have_image_files && have_oat_files) {
1407 TimingLogger::ScopedTiming pt("patch image and oat", &timings);
1408 ret = PatchOat::Patch(input_oat.get(), input_image_location, base_delta,
Igor Murashkin46774762014-10-22 11:37:02 -07001409 output_oat.get(), output_image.get(), isa, &timings,
1410 output_oat_fd >= 0, // was it opened from FD?
1411 new_oat_out);
Andreas Gampe4303ba92014-11-06 01:00:46 -08001412 // The order here doesn't matter. If the first one is successfully saved and the second one
1413 // erased, ImageSpace will still detect a problem and not use the files.
Alex Light0eb76d22015-08-11 18:03:47 -07001414 ret = FinishFile(output_image.get(), ret);
1415 ret = FinishFile(output_oat.get(), ret);
Alex Light53cb16b2014-06-12 11:26:29 -07001416 } else if (have_oat_files) {
1417 TimingLogger::ScopedTiming pt("patch oat", &timings);
Igor Murashkin46774762014-10-22 11:37:02 -07001418 ret = PatchOat::Patch(input_oat.get(), base_delta, output_oat.get(), &timings,
1419 output_oat_fd >= 0, // was it opened from FD?
1420 new_oat_out);
Alex Light0eb76d22015-08-11 18:03:47 -07001421 ret = FinishFile(output_oat.get(), ret);
Igor Murashkin46774762014-10-22 11:37:02 -07001422 } else if (have_image_files) {
Alex Light53cb16b2014-06-12 11:26:29 -07001423 TimingLogger::ScopedTiming pt("patch image", &timings);
Alex Lighteefbe392014-07-08 09:53:18 -07001424 ret = PatchOat::Patch(input_image_location, base_delta, output_image.get(), isa, &timings);
Alex Light0eb76d22015-08-11 18:03:47 -07001425 ret = FinishFile(output_image.get(), ret);
Igor Murashkin46774762014-10-22 11:37:02 -07001426 } else {
1427 CHECK(false);
1428 ret = true;
1429 }
1430
1431 if (kIsDebugBuild) {
1432 LOG(INFO) << "Exiting with return ... " << ret;
Alex Light53cb16b2014-06-12 11:26:29 -07001433 }
1434 cleanup(ret);
Alex Light53cb16b2014-06-12 11:26:29 -07001435 return (ret) ? EXIT_SUCCESS : EXIT_FAILURE;
1436}
1437
1438} // namespace art
1439
1440int main(int argc, char **argv) {
1441 return art::patchoat(argc, argv);
1442}