blob: 46ab34bea3b41f40a750171b43a5743989589cbd [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
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800156 if (image_header.GetStorageMode() != ImageHeader::kStorageModeUncompressed) {
157 LOG(ERROR) << "Patchoat is not supported with compressed image files "
158 << input_image->GetPath();
159 return false;
160 }
161
Igor Murashkin46774762014-10-22 11:37:02 -0700162 /*bool is_image_pic = */IsImagePic(image_header, input_image->GetPath());
163 // Nothing special to do right now since the image always needs to get patched.
164 // Perhaps in some far-off future we may have images with relative addresses that are true-PIC.
165
Alex Light53cb16b2014-06-12 11:26:29 -0700166 // Set up the runtime
Ian Rogerse63db272014-07-15 15:36:11 -0700167 RuntimeOptions options;
Alex Light53cb16b2014-06-12 11:26:29 -0700168 NoopCompilerCallbacks callbacks;
169 options.push_back(std::make_pair("compilercallbacks", &callbacks));
170 std::string img = "-Ximage:" + image_location;
171 options.push_back(std::make_pair(img.c_str(), nullptr));
172 options.push_back(std::make_pair("imageinstructionset", reinterpret_cast<const void*>(isa_name)));
Calin Juravle01aaf6e2015-06-19 22:05:39 +0100173 options.push_back(std::make_pair("-Xno-sig-chain", nullptr));
Alex Light53cb16b2014-06-12 11:26:29 -0700174 if (!Runtime::Create(options, false)) {
175 LOG(ERROR) << "Unable to initialize runtime";
176 return false;
177 }
178 // Runtime::Create acquired the mutator_lock_ that is normally given away when we Runtime::Start,
179 // give it away now and then switch to a more manageable ScopedObjectAccess.
180 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
181 ScopedObjectAccess soa(Thread::Current());
182
183 t.NewTiming("Image and oat Patching setup");
184 // Create the map where we will write the image patches to.
Alex Lighteefbe392014-07-08 09:53:18 -0700185 std::string error_msg;
Mathieu Chartier42bddce2015-11-09 15:16:56 -0800186 std::unique_ptr<MemMap> image(MemMap::MapFile(image_len,
187 PROT_READ | PROT_WRITE,
188 MAP_PRIVATE,
189 input_image->Fd(),
190 0,
191 /*low_4gb*/false,
Alex Light53cb16b2014-06-12 11:26:29 -0700192 input_image->GetPath().c_str(),
193 &error_msg));
194 if (image.get() == nullptr) {
195 LOG(ERROR) << "unable to map image file " << input_image->GetPath() << " : " << error_msg;
196 return false;
197 }
Mathieu Chartier073b16c2015-11-10 14:13:23 -0800198 gc::space::ImageSpace* ispc = Runtime::Current()->GetHeap()->GetBootImageSpace();
Alex Light53cb16b2014-06-12 11:26:29 -0700199
Mathieu Chartier42bddce2015-11-09 15:16:56 -0800200 PatchOat p(isa, image.release(), ispc->GetLiveBitmap(), ispc->GetMemMap(), delta, timings);
Alex Light53cb16b2014-06-12 11:26:29 -0700201 t.NewTiming("Patching files");
202 if (!p.PatchImage()) {
Alex Lighta59dd802014-07-02 16:28:08 -0700203 LOG(ERROR) << "Failed to patch image file " << input_image->GetPath();
Alex Light53cb16b2014-06-12 11:26:29 -0700204 return false;
205 }
206
207 t.NewTiming("Writing files");
208 if (!p.WriteImage(output_image)) {
209 return false;
210 }
211 return true;
212}
213
Igor Murashkin46774762014-10-22 11:37:02 -0700214bool PatchOat::Patch(File* input_oat, const std::string& image_location, off_t delta,
Alex Light53cb16b2014-06-12 11:26:29 -0700215 File* output_oat, File* output_image, InstructionSet isa,
Igor Murashkin46774762014-10-22 11:37:02 -0700216 TimingLogger* timings,
217 bool output_oat_opened_from_fd,
218 bool new_oat_out) {
Alex Light53cb16b2014-06-12 11:26:29 -0700219 CHECK(Runtime::Current() == nullptr);
220 CHECK(output_image != nullptr);
221 CHECK_GE(output_image->Fd(), 0);
222 CHECK(input_oat != nullptr);
223 CHECK(output_oat != nullptr);
224 CHECK_GE(input_oat->Fd(), 0);
225 CHECK_GE(output_oat->Fd(), 0);
226 CHECK(!image_location.empty()) << "image file must have a filename.";
227
Alex Lighteefbe392014-07-08 09:53:18 -0700228 TimingLogger::ScopedTiming t("Runtime Setup", timings);
Alex Light53cb16b2014-06-12 11:26:29 -0700229
230 if (isa == kNone) {
231 Elf32_Ehdr elf_hdr;
232 if (sizeof(elf_hdr) != input_oat->Read(reinterpret_cast<char*>(&elf_hdr), sizeof(elf_hdr), 0)) {
233 LOG(ERROR) << "unable to read elf header";
234 return false;
235 }
Andreas Gampe6f611412015-01-21 22:25:24 -0800236 isa = GetInstructionSetFromELF(elf_hdr.e_machine, elf_hdr.e_flags);
Alex Light53cb16b2014-06-12 11:26:29 -0700237 }
238 const char* isa_name = GetInstructionSetString(isa);
Alex Lightcf4bf382014-07-24 11:29:14 -0700239 std::string image_filename;
240 if (!LocationToFilename(image_location, isa, &image_filename)) {
241 LOG(ERROR) << "Unable to find image at location " << image_location;
242 return false;
243 }
Alex Light53cb16b2014-06-12 11:26:29 -0700244 std::unique_ptr<File> input_image(OS::OpenFileForReading(image_filename.c_str()));
245 if (input_image.get() == nullptr) {
Alex Lightcf4bf382014-07-24 11:29:14 -0700246 LOG(ERROR) << "unable to open input image file at " << image_filename
247 << " for location " << image_location;
Alex Light53cb16b2014-06-12 11:26:29 -0700248 return false;
249 }
250 int64_t image_len = input_image->GetLength();
251 if (image_len < 0) {
252 LOG(ERROR) << "Error while getting image length";
253 return false;
254 }
255 ImageHeader image_header;
256 if (sizeof(image_header) != input_image->Read(reinterpret_cast<char*>(&image_header),
257 sizeof(image_header), 0)) {
258 LOG(ERROR) << "Unable to read image header from image file " << input_image->GetPath();
259 }
260
Igor Murashkin46774762014-10-22 11:37:02 -0700261 /*bool is_image_pic = */IsImagePic(image_header, input_image->GetPath());
262 // Nothing special to do right now since the image always needs to get patched.
263 // Perhaps in some far-off future we may have images with relative addresses that are true-PIC.
264
Alex Light53cb16b2014-06-12 11:26:29 -0700265 // Set up the runtime
Ian Rogerse63db272014-07-15 15:36:11 -0700266 RuntimeOptions options;
Alex Light53cb16b2014-06-12 11:26:29 -0700267 NoopCompilerCallbacks callbacks;
268 options.push_back(std::make_pair("compilercallbacks", &callbacks));
269 std::string img = "-Ximage:" + image_location;
270 options.push_back(std::make_pair(img.c_str(), nullptr));
271 options.push_back(std::make_pair("imageinstructionset", reinterpret_cast<const void*>(isa_name)));
Calin Juravle01aaf6e2015-06-19 22:05:39 +0100272 options.push_back(std::make_pair("-Xno-sig-chain", nullptr));
Alex Light53cb16b2014-06-12 11:26:29 -0700273 if (!Runtime::Create(options, false)) {
274 LOG(ERROR) << "Unable to initialize runtime";
275 return false;
276 }
277 // Runtime::Create acquired the mutator_lock_ that is normally given away when we Runtime::Start,
278 // give it away now and then switch to a more manageable ScopedObjectAccess.
279 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
280 ScopedObjectAccess soa(Thread::Current());
281
282 t.NewTiming("Image and oat Patching setup");
283 // Create the map where we will write the image patches to.
Alex Lighteefbe392014-07-08 09:53:18 -0700284 std::string error_msg;
Mathieu Chartier42bddce2015-11-09 15:16:56 -0800285 std::unique_ptr<MemMap> image(MemMap::MapFile(image_len,
286 PROT_READ | PROT_WRITE,
287 MAP_PRIVATE,
288 input_image->Fd(),
289 0,
290 /*low_4gb*/false,
Alex Light53cb16b2014-06-12 11:26:29 -0700291 input_image->GetPath().c_str(),
292 &error_msg));
293 if (image.get() == nullptr) {
294 LOG(ERROR) << "unable to map image file " << input_image->GetPath() << " : " << error_msg;
295 return false;
296 }
Mathieu Chartier073b16c2015-11-10 14:13:23 -0800297 gc::space::ImageSpace* ispc = Runtime::Current()->GetHeap()->GetBootImageSpace();
Alex Light53cb16b2014-06-12 11:26:29 -0700298
Igor Murashkin46774762014-10-22 11:37:02 -0700299 std::unique_ptr<ElfFile> elf(ElfFile::Open(input_oat,
Alex Light53cb16b2014-06-12 11:26:29 -0700300 PROT_READ | PROT_WRITE, MAP_PRIVATE, &error_msg));
301 if (elf.get() == nullptr) {
302 LOG(ERROR) << "unable to open oat file " << input_oat->GetPath() << " : " << error_msg;
303 return false;
304 }
305
Igor Murashkin46774762014-10-22 11:37:02 -0700306 bool skip_patching_oat = false;
307 MaybePic is_oat_pic = IsOatPic(elf.get());
308 if (is_oat_pic >= ERROR_FIRST) {
309 // Error logged by IsOatPic
310 return false;
311 } else if (is_oat_pic == PIC) {
312 // Do not need to do ELF-file patching. Create a symlink and skip the ELF patching.
313 if (!ReplaceOatFileWithSymlink(input_oat->GetPath(),
314 output_oat->GetPath(),
315 output_oat_opened_from_fd,
316 new_oat_out)) {
317 // Errors already logged by above call.
318 return false;
319 }
320 // Don't patch the OAT, since we just symlinked it. Image still needs patching.
321 skip_patching_oat = true;
322 } else {
323 CHECK(is_oat_pic == NOT_PIC);
324 }
325
Mathieu Chartier2d721012014-11-10 11:08:06 -0800326 PatchOat p(isa, elf.release(), image.release(), ispc->GetLiveBitmap(), ispc->GetMemMap(),
Alex Light53cb16b2014-06-12 11:26:29 -0700327 delta, timings);
328 t.NewTiming("Patching files");
Igor Murashkin46774762014-10-22 11:37:02 -0700329 if (!skip_patching_oat && !p.PatchElf()) {
Alex Lighta59dd802014-07-02 16:28:08 -0700330 LOG(ERROR) << "Failed to patch oat file " << input_oat->GetPath();
Alex Light53cb16b2014-06-12 11:26:29 -0700331 return false;
332 }
333 if (!p.PatchImage()) {
Alex Lighta59dd802014-07-02 16:28:08 -0700334 LOG(ERROR) << "Failed to patch image file " << input_image->GetPath();
Alex Light53cb16b2014-06-12 11:26:29 -0700335 return false;
336 }
337
338 t.NewTiming("Writing files");
Igor Murashkin46774762014-10-22 11:37:02 -0700339 if (!skip_patching_oat && !p.WriteElf(output_oat)) {
340 LOG(ERROR) << "Failed to write oat file " << input_oat->GetPath();
Alex Light53cb16b2014-06-12 11:26:29 -0700341 return false;
342 }
343 if (!p.WriteImage(output_image)) {
Igor Murashkin46774762014-10-22 11:37:02 -0700344 LOG(ERROR) << "Failed to write image file " << input_image->GetPath();
Alex Light53cb16b2014-06-12 11:26:29 -0700345 return false;
346 }
347 return true;
348}
349
350bool PatchOat::WriteElf(File* out) {
Alex Lighteefbe392014-07-08 09:53:18 -0700351 TimingLogger::ScopedTiming t("Writing Elf File", timings_);
Alex Lighta59dd802014-07-02 16:28:08 -0700352
Alex Light53cb16b2014-06-12 11:26:29 -0700353 CHECK(oat_file_.get() != nullptr);
354 CHECK(out != nullptr);
355 size_t expect = oat_file_->Size();
356 if (out->WriteFully(reinterpret_cast<char*>(oat_file_->Begin()), expect) &&
357 out->SetLength(expect) == 0) {
358 return true;
359 } else {
360 LOG(ERROR) << "Writing to oat file " << out->GetPath() << " failed.";
361 return false;
362 }
363}
364
365bool PatchOat::WriteImage(File* out) {
Alex Lighteefbe392014-07-08 09:53:18 -0700366 TimingLogger::ScopedTiming t("Writing image File", timings_);
Alex Lighta59dd802014-07-02 16:28:08 -0700367 std::string error_msg;
368
Alex Lightcf4bf382014-07-24 11:29:14 -0700369 ScopedFlock img_flock;
370 img_flock.Init(out, &error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -0700371
Alex Light53cb16b2014-06-12 11:26:29 -0700372 CHECK(image_ != nullptr);
373 CHECK(out != nullptr);
374 size_t expect = image_->Size();
375 if (out->WriteFully(reinterpret_cast<char*>(image_->Begin()), expect) &&
376 out->SetLength(expect) == 0) {
377 return true;
378 } else {
379 LOG(ERROR) << "Writing to image file " << out->GetPath() << " failed.";
380 return false;
381 }
382}
383
Igor Murashkin46774762014-10-22 11:37:02 -0700384bool PatchOat::IsImagePic(const ImageHeader& image_header, const std::string& image_path) {
385 if (!image_header.CompilePic()) {
386 if (kIsDebugBuild) {
387 LOG(INFO) << "image at location " << image_path << " was *not* compiled pic";
388 }
389 return false;
390 }
391
392 if (kIsDebugBuild) {
393 LOG(INFO) << "image at location " << image_path << " was compiled PIC";
394 }
395
396 return true;
397}
398
399PatchOat::MaybePic PatchOat::IsOatPic(const ElfFile* oat_in) {
400 if (oat_in == nullptr) {
401 LOG(ERROR) << "No ELF input oat fie available";
402 return ERROR_OAT_FILE;
403 }
404
405 const std::string& file_path = oat_in->GetFile().GetPath();
406
407 const OatHeader* oat_header = GetOatHeader(oat_in);
408 if (oat_header == nullptr) {
409 LOG(ERROR) << "Failed to find oat header in oat file " << file_path;
410 return ERROR_OAT_FILE;
411 }
412
413 if (!oat_header->IsValid()) {
414 LOG(ERROR) << "Elf file " << file_path << " has an invalid oat header";
415 return ERROR_OAT_FILE;
416 }
417
418 bool is_pic = oat_header->IsPic();
419 if (kIsDebugBuild) {
420 LOG(INFO) << "Oat file at " << file_path << " is " << (is_pic ? "PIC" : "not pic");
421 }
422
423 return is_pic ? PIC : NOT_PIC;
424}
425
426bool PatchOat::ReplaceOatFileWithSymlink(const std::string& input_oat_filename,
427 const std::string& output_oat_filename,
428 bool output_oat_opened_from_fd,
429 bool new_oat_out) {
430 // Need a file when we are PIC, since we symlink over it. Refusing to symlink into FD.
431 if (output_oat_opened_from_fd) {
432 // TODO: installd uses --output-oat-fd. Should we change class linking logic for PIC?
433 LOG(ERROR) << "No output oat filename specified, needs filename for when we are PIC";
434 return false;
435 }
436
437 // Image was PIC. Create symlink where the oat is supposed to go.
438 if (!new_oat_out) {
439 LOG(ERROR) << "Oat file " << output_oat_filename << " already exists, refusing to overwrite";
440 return false;
441 }
442
443 // Delete the original file, since we won't need it.
444 TEMP_FAILURE_RETRY(unlink(output_oat_filename.c_str()));
445
446 // Create a symlink from the old oat to the new oat
447 if (symlink(input_oat_filename.c_str(), output_oat_filename.c_str()) < 0) {
448 int err = errno;
449 LOG(ERROR) << "Failed to create symlink at " << output_oat_filename
450 << " error(" << err << "): " << strerror(err);
451 return false;
452 }
453
454 if (kIsDebugBuild) {
455 LOG(INFO) << "Created symlink " << output_oat_filename << " -> " << input_oat_filename;
456 }
457
458 return true;
459}
460
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700461class PatchOatArtFieldVisitor : public ArtFieldVisitor {
462 public:
463 explicit PatchOatArtFieldVisitor(PatchOat* patch_oat) : patch_oat_(patch_oat) {}
464
465 void Visit(ArtField* field) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
466 ArtField* const dest = patch_oat_->RelocatedCopyOf(field);
467 dest->SetDeclaringClass(patch_oat_->RelocatedAddressOfPointer(field->GetDeclaringClass()));
Mathieu Chartiere401d142015-04-22 13:56:20 -0700468 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700469
470 private:
471 PatchOat* const patch_oat_;
472};
473
474void PatchOat::PatchArtFields(const ImageHeader* image_header) {
475 PatchOatArtFieldVisitor visitor(this);
476 const auto& section = image_header->GetImageSection(ImageHeader::kSectionArtFields);
477 section.VisitPackedArtFields(&visitor, heap_->Begin());
Mathieu Chartiere401d142015-04-22 13:56:20 -0700478}
479
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700480class PatchOatArtMethodVisitor : public ArtMethodVisitor {
481 public:
482 explicit PatchOatArtMethodVisitor(PatchOat* patch_oat) : patch_oat_(patch_oat) {}
483
484 void Visit(ArtMethod* method) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
485 ArtMethod* const dest = patch_oat_->RelocatedCopyOf(method);
486 patch_oat_->FixupMethod(method, dest);
487 }
488
489 private:
490 PatchOat* const patch_oat_;
491};
492
Mathieu Chartiere401d142015-04-22 13:56:20 -0700493void PatchOat::PatchArtMethods(const ImageHeader* image_header) {
494 const auto& section = image_header->GetMethodsSection();
495 const size_t pointer_size = InstructionSetPointerSize(isa_);
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700496 PatchOatArtMethodVisitor visitor(this);
Vladimir Markocf36d492015-08-12 19:27:26 +0100497 section.VisitPackedArtMethods(&visitor, heap_->Begin(), pointer_size);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700498}
499
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700500class FixupRootVisitor : public RootVisitor {
501 public:
502 explicit FixupRootVisitor(const PatchOat* patch_oat) : patch_oat_(patch_oat) {
503 }
504
505 void VisitRoots(mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -0700506 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700507 for (size_t i = 0; i < count; ++i) {
508 *roots[i] = patch_oat_->RelocatedAddressOfPointer(*roots[i]);
509 }
510 }
511
512 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots, size_t count,
513 const RootInfo& info ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -0700514 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700515 for (size_t i = 0; i < count; ++i) {
516 roots[i]->Assign(patch_oat_->RelocatedAddressOfPointer(roots[i]->AsMirrorPtr()));
517 }
518 }
519
520 private:
521 const PatchOat* const patch_oat_;
522};
523
524void PatchOat::PatchInternedStrings(const ImageHeader* image_header) {
525 const auto& section = image_header->GetImageSection(ImageHeader::kSectionInternedStrings);
526 InternTable temp_table;
527 // Note that we require that ReadFromMemory does not make an internal copy of the elements.
528 // This also relies on visit roots not doing any verification which could fail after we update
529 // the roots to be the image addresses.
530 temp_table.ReadFromMemory(image_->Begin() + section.Offset());
531 FixupRootVisitor visitor(this);
532 temp_table.VisitRoots(&visitor, kVisitRootFlagAllRoots);
533}
534
Mathieu Chartier208a5cb2015-12-02 15:44:07 -0800535void PatchOat::PatchClassTable(const ImageHeader* image_header) {
536 const auto& section = image_header->GetImageSection(ImageHeader::kSectionClassTable);
Mathieu Chartier208a5cb2015-12-02 15:44:07 -0800537 // Note that we require that ReadFromMemory does not make an internal copy of the elements.
538 // This also relies on visit roots not doing any verification which could fail after we update
539 // the roots to be the image addresses.
540 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
541 ClassTable temp_table;
542 temp_table.ReadFromMemory(image_->Begin() + section.Offset());
543 FixupRootVisitor visitor(this);
544 BufferedRootVisitor<kDefaultBufferedRootCount> buffered_visitor(&visitor, RootInfo(kRootUnknown));
545 temp_table.VisitRoots(buffered_visitor);
546}
547
548
Mathieu Chartier4b00d342015-11-13 10:42:08 -0800549class RelocatedPointerVisitor {
550 public:
551 explicit RelocatedPointerVisitor(PatchOat* patch_oat) : patch_oat_(patch_oat) {}
552
553 template <typename T>
554 T* operator()(T* ptr) const {
555 return patch_oat_->RelocatedAddressOfPointer(ptr);
556 }
557
558 private:
559 PatchOat* const patch_oat_;
560};
561
Mathieu Chartierc7853442015-03-27 14:35:38 -0700562void PatchOat::PatchDexFileArrays(mirror::ObjectArray<mirror::Object>* img_roots) {
563 auto* dex_caches = down_cast<mirror::ObjectArray<mirror::DexCache>*>(
564 img_roots->Get(ImageHeader::kDexCaches));
Mathieu Chartier4b00d342015-11-13 10:42:08 -0800565 const size_t pointer_size = InstructionSetPointerSize(isa_);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700566 for (size_t i = 0, count = dex_caches->GetLength(); i < count; ++i) {
Vladimir Marko05792b92015-08-03 11:56:49 +0100567 auto* orig_dex_cache = dex_caches->GetWithoutChecks(i);
568 auto* copy_dex_cache = RelocatedCopyOf(orig_dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +0100569 // Though the DexCache array fields are usually treated as native pointers, we set the full
570 // 64-bit values here, clearing the top 32 bits for 32-bit targets. The zero-extension is
571 // done by casting to the unsigned type uintptr_t before casting to int64_t, i.e.
572 // static_cast<int64_t>(reinterpret_cast<uintptr_t>(image_begin_ + offset))).
573 GcRoot<mirror::String>* orig_strings = orig_dex_cache->GetStrings();
574 GcRoot<mirror::String>* relocated_strings = RelocatedAddressOfPointer(orig_strings);
575 copy_dex_cache->SetField64<false>(
576 mirror::DexCache::StringsOffset(),
577 static_cast<int64_t>(reinterpret_cast<uintptr_t>(relocated_strings)));
578 if (orig_strings != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -0800579 orig_dex_cache->FixupStrings(RelocatedCopyOf(orig_strings), RelocatedPointerVisitor(this));
Mathieu Chartierc7853442015-03-27 14:35:38 -0700580 }
Vladimir Marko05792b92015-08-03 11:56:49 +0100581 GcRoot<mirror::Class>* orig_types = orig_dex_cache->GetResolvedTypes();
582 GcRoot<mirror::Class>* relocated_types = RelocatedAddressOfPointer(orig_types);
583 copy_dex_cache->SetField64<false>(
584 mirror::DexCache::ResolvedTypesOffset(),
585 static_cast<int64_t>(reinterpret_cast<uintptr_t>(relocated_types)));
586 if (orig_types != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -0800587 orig_dex_cache->FixupResolvedTypes(RelocatedCopyOf(orig_types),
588 RelocatedPointerVisitor(this));
Vladimir Marko05792b92015-08-03 11:56:49 +0100589 }
590 ArtMethod** orig_methods = orig_dex_cache->GetResolvedMethods();
591 ArtMethod** relocated_methods = RelocatedAddressOfPointer(orig_methods);
592 copy_dex_cache->SetField64<false>(
593 mirror::DexCache::ResolvedMethodsOffset(),
594 static_cast<int64_t>(reinterpret_cast<uintptr_t>(relocated_methods)));
595 if (orig_methods != nullptr) {
596 ArtMethod** copy_methods = RelocatedCopyOf(orig_methods);
597 for (size_t j = 0, num = orig_dex_cache->NumResolvedMethods(); j != num; ++j) {
598 ArtMethod* orig = mirror::DexCache::GetElementPtrSize(orig_methods, j, pointer_size);
599 ArtMethod* copy = RelocatedAddressOfPointer(orig);
600 mirror::DexCache::SetElementPtrSize(copy_methods, j, copy, pointer_size);
601 }
602 }
603 ArtField** orig_fields = orig_dex_cache->GetResolvedFields();
604 ArtField** relocated_fields = RelocatedAddressOfPointer(orig_fields);
605 copy_dex_cache->SetField64<false>(
606 mirror::DexCache::ResolvedFieldsOffset(),
607 static_cast<int64_t>(reinterpret_cast<uintptr_t>(relocated_fields)));
608 if (orig_fields != nullptr) {
609 ArtField** copy_fields = RelocatedCopyOf(orig_fields);
610 for (size_t j = 0, num = orig_dex_cache->NumResolvedFields(); j != num; ++j) {
611 ArtField* orig = mirror::DexCache::GetElementPtrSize(orig_fields, j, pointer_size);
612 ArtField* copy = RelocatedAddressOfPointer(orig);
613 mirror::DexCache::SetElementPtrSize(copy_fields, j, copy, pointer_size);
614 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700615 }
616 }
617}
618
Alex Light53cb16b2014-06-12 11:26:29 -0700619bool PatchOat::PatchImage() {
620 ImageHeader* image_header = reinterpret_cast<ImageHeader*>(image_->Begin());
621 CHECK_GT(image_->Size(), sizeof(ImageHeader));
622 // These are the roots from the original file.
Mathieu Chartierc7853442015-03-27 14:35:38 -0700623 auto* img_roots = image_header->GetImageRoots();
Alex Light53cb16b2014-06-12 11:26:29 -0700624 image_header->RelocateImage(delta_);
625
Mathieu Chartierc7853442015-03-27 14:35:38 -0700626 PatchArtFields(image_header);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700627 PatchArtMethods(image_header);
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700628 PatchInternedStrings(image_header);
Mathieu Chartier208a5cb2015-12-02 15:44:07 -0800629 PatchClassTable(image_header);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700630 // Patch dex file int/long arrays which point to ArtFields.
631 PatchDexFileArrays(img_roots);
632
Alex Light53cb16b2014-06-12 11:26:29 -0700633 VisitObject(img_roots);
634 if (!image_header->IsValid()) {
635 LOG(ERROR) << "reloction renders image header invalid";
636 return false;
637 }
638
639 {
Alex Lighteefbe392014-07-08 09:53:18 -0700640 TimingLogger::ScopedTiming t("Walk Bitmap", timings_);
Alex Light53cb16b2014-06-12 11:26:29 -0700641 // Walk the bitmap.
642 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
643 bitmap_->Walk(PatchOat::BitmapCallback, this);
644 }
645 return true;
646}
647
648bool PatchOat::InHeap(mirror::Object* o) {
649 uintptr_t begin = reinterpret_cast<uintptr_t>(heap_->Begin());
650 uintptr_t end = reinterpret_cast<uintptr_t>(heap_->End());
651 uintptr_t obj = reinterpret_cast<uintptr_t>(o);
652 return o == nullptr || (begin <= obj && obj < end);
653}
654
655void PatchOat::PatchVisitor::operator() (mirror::Object* obj, MemberOffset off,
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700656 bool is_static_unused ATTRIBUTE_UNUSED) const {
Alex Light53cb16b2014-06-12 11:26:29 -0700657 mirror::Object* referent = obj->GetFieldObject<mirror::Object, kVerifyNone>(off);
658 DCHECK(patcher_->InHeap(referent)) << "Referent is not in the heap.";
Mathieu Chartierc7853442015-03-27 14:35:38 -0700659 mirror::Object* moved_object = patcher_->RelocatedAddressOfPointer(referent);
Alex Light53cb16b2014-06-12 11:26:29 -0700660 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(off, moved_object);
661}
662
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700663void PatchOat::PatchVisitor::operator() (mirror::Class* cls ATTRIBUTE_UNUSED,
664 mirror::Reference* ref) const {
Alex Light53cb16b2014-06-12 11:26:29 -0700665 MemberOffset off = mirror::Reference::ReferentOffset();
666 mirror::Object* referent = ref->GetReferent();
667 DCHECK(patcher_->InHeap(referent)) << "Referent is not in the heap.";
Mathieu Chartierc7853442015-03-27 14:35:38 -0700668 mirror::Object* moved_object = patcher_->RelocatedAddressOfPointer(referent);
Alex Light53cb16b2014-06-12 11:26:29 -0700669 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(off, moved_object);
670}
671
Alex Light53cb16b2014-06-12 11:26:29 -0700672// Called by BitmapCallback
673void PatchOat::VisitObject(mirror::Object* object) {
674 mirror::Object* copy = RelocatedCopyOf(object);
675 CHECK(copy != nullptr);
676 if (kUseBakerOrBrooksReadBarrier) {
677 object->AssertReadBarrierPointer();
678 if (kUseBrooksReadBarrier) {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700679 mirror::Object* moved_to = RelocatedAddressOfPointer(object);
Alex Light53cb16b2014-06-12 11:26:29 -0700680 copy->SetReadBarrierPointer(moved_to);
681 DCHECK_EQ(copy->GetReadBarrierPointer(), moved_to);
682 }
683 }
684 PatchOat::PatchVisitor visitor(this, copy);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -0700685 object->VisitReferences<kVerifyNone>(visitor, visitor);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700686 if (object->IsClass<kVerifyNone>()) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -0800687 const size_t pointer_size = InstructionSetPointerSize(isa_);
688 mirror::Class* klass = object->AsClass();
689 mirror::Class* copy_klass = down_cast<mirror::Class*>(copy);
690 RelocatedPointerVisitor native_visitor(this);
691 klass->FixupNativePointers(copy_klass, pointer_size, native_visitor);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700692 auto* vtable = klass->GetVTable();
693 if (vtable != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -0800694 vtable->Fixup(RelocatedCopyOf(vtable), pointer_size, native_visitor);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700695 }
696 auto* iftable = klass->GetIfTable();
697 if (iftable != nullptr) {
698 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
699 if (iftable->GetMethodArrayCount(i) > 0) {
700 auto* method_array = iftable->GetMethodArray(i);
701 CHECK(method_array != nullptr);
Mathieu Chartier4b00d342015-11-13 10:42:08 -0800702 method_array->Fixup(RelocatedCopyOf(method_array), pointer_size, native_visitor);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700703 }
704 }
705 }
Mathieu Chartier4b00d342015-11-13 10:42:08 -0800706 } else if (object->GetClass() == mirror::Method::StaticClass() ||
707 object->GetClass() == mirror::Constructor::StaticClass()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700708 // Need to go update the ArtMethod.
709 auto* dest = down_cast<mirror::AbstractMethod*>(copy);
710 auto* src = down_cast<mirror::AbstractMethod*>(object);
711 dest->SetArtMethod(RelocatedAddressOfPointer(src->GetArtMethod()));
Alex Light53cb16b2014-06-12 11:26:29 -0700712 }
713}
714
Mathieu Chartiere401d142015-04-22 13:56:20 -0700715void PatchOat::FixupMethod(ArtMethod* object, ArtMethod* copy) {
Mathieu Chartier2d721012014-11-10 11:08:06 -0800716 const size_t pointer_size = InstructionSetPointerSize(isa_);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700717 copy->CopyFrom(object, pointer_size);
Alex Light53cb16b2014-06-12 11:26:29 -0700718 // Just update the entry points if it looks like we should.
Alex Lighteefbe392014-07-08 09:53:18 -0700719 // TODO: sanity check all the pointers' values
Mathieu Chartiere401d142015-04-22 13:56:20 -0700720 copy->SetDeclaringClass(RelocatedAddressOfPointer(object->GetDeclaringClass()));
Vladimir Marko05792b92015-08-03 11:56:49 +0100721 copy->SetDexCacheResolvedMethods(
722 RelocatedAddressOfPointer(object->GetDexCacheResolvedMethods(pointer_size)), pointer_size);
723 copy->SetDexCacheResolvedTypes(
724 RelocatedAddressOfPointer(object->GetDexCacheResolvedTypes(pointer_size)), pointer_size);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700725 copy->SetEntryPointFromQuickCompiledCodePtrSize(RelocatedAddressOfPointer(
726 object->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size)), pointer_size);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700727 copy->SetEntryPointFromJniPtrSize(RelocatedAddressOfPointer(
728 object->GetEntryPointFromJniPtrSize(pointer_size)), pointer_size);
Alex Light53cb16b2014-06-12 11:26:29 -0700729}
730
Igor Murashkin46774762014-10-22 11:37:02 -0700731bool PatchOat::Patch(File* input_oat, off_t delta, File* output_oat, TimingLogger* timings,
732 bool output_oat_opened_from_fd, bool new_oat_out) {
Alex Light53cb16b2014-06-12 11:26:29 -0700733 CHECK(input_oat != nullptr);
734 CHECK(output_oat != nullptr);
735 CHECK_GE(input_oat->Fd(), 0);
736 CHECK_GE(output_oat->Fd(), 0);
Alex Lighteefbe392014-07-08 09:53:18 -0700737 TimingLogger::ScopedTiming t("Setup Oat File Patching", timings);
Alex Light53cb16b2014-06-12 11:26:29 -0700738
739 std::string error_msg;
Igor Murashkin46774762014-10-22 11:37:02 -0700740 std::unique_ptr<ElfFile> elf(ElfFile::Open(input_oat,
Alex Light53cb16b2014-06-12 11:26:29 -0700741 PROT_READ | PROT_WRITE, MAP_PRIVATE, &error_msg));
742 if (elf.get() == nullptr) {
743 LOG(ERROR) << "unable to open oat file " << input_oat->GetPath() << " : " << error_msg;
744 return false;
745 }
746
Igor Murashkin46774762014-10-22 11:37:02 -0700747 MaybePic is_oat_pic = IsOatPic(elf.get());
748 if (is_oat_pic >= ERROR_FIRST) {
749 // Error logged by IsOatPic
750 return false;
751 } else if (is_oat_pic == PIC) {
752 // Do not need to do ELF-file patching. Create a symlink and skip the rest.
753 // Any errors will be logged by the function call.
754 return ReplaceOatFileWithSymlink(input_oat->GetPath(),
755 output_oat->GetPath(),
756 output_oat_opened_from_fd,
757 new_oat_out);
758 } else {
759 CHECK(is_oat_pic == NOT_PIC);
760 }
761
Alex Light53cb16b2014-06-12 11:26:29 -0700762 PatchOat p(elf.release(), delta, timings);
763 t.NewTiming("Patch Oat file");
764 if (!p.PatchElf()) {
765 return false;
766 }
767
768 t.NewTiming("Writing oat file");
769 if (!p.WriteElf(output_oat)) {
770 return false;
771 }
772 return true;
773}
774
Tong Shen62d1ca32014-09-03 17:24:56 -0700775template <typename ElfFileImpl>
776bool PatchOat::PatchOatHeader(ElfFileImpl* oat_file) {
777 auto rodata_sec = oat_file->FindSectionByName(".rodata");
Alex Lighta59dd802014-07-02 16:28:08 -0700778 if (rodata_sec == nullptr) {
779 return false;
780 }
Tong Shen62d1ca32014-09-03 17:24:56 -0700781 OatHeader* oat_header = reinterpret_cast<OatHeader*>(oat_file->Begin() + rodata_sec->sh_offset);
Alex Lighta59dd802014-07-02 16:28:08 -0700782 if (!oat_header->IsValid()) {
Tong Shen62d1ca32014-09-03 17:24:56 -0700783 LOG(ERROR) << "Elf file " << oat_file->GetFile().GetPath() << " has an invalid oat header";
Alex Lighta59dd802014-07-02 16:28:08 -0700784 return false;
785 }
786 oat_header->RelocateOat(delta_);
787 return true;
788}
789
Alex Light53cb16b2014-06-12 11:26:29 -0700790bool PatchOat::PatchElf() {
Ian Rogersd4c4d952014-10-16 20:31:53 -0700791 if (oat_file_->Is64Bit())
Tong Shen62d1ca32014-09-03 17:24:56 -0700792 return PatchElf<ElfFileImpl64>(oat_file_->GetImpl64());
793 else
794 return PatchElf<ElfFileImpl32>(oat_file_->GetImpl32());
795}
796
797template <typename ElfFileImpl>
798bool PatchOat::PatchElf(ElfFileImpl* oat_file) {
Alex Lighta59dd802014-07-02 16:28:08 -0700799 TimingLogger::ScopedTiming t("Fixup Elf Text Section", timings_);
Vladimir Marko3fc99032015-05-13 19:06:30 +0100800
801 // Fix up absolute references to locations within the boot image.
David Srbecky2f6cdb02015-04-11 00:17:53 +0100802 if (!oat_file->ApplyOatPatchesTo(".text", delta_)) {
Alex Lighta59dd802014-07-02 16:28:08 -0700803 return false;
804 }
805
Vladimir Marko3fc99032015-05-13 19:06:30 +0100806 // Update the OatHeader fields referencing the boot image.
Tong Shen62d1ca32014-09-03 17:24:56 -0700807 if (!PatchOatHeader<ElfFileImpl>(oat_file)) {
Alex Lighta59dd802014-07-02 16:28:08 -0700808 return false;
809 }
810
Vladimir Marko3fc99032015-05-13 19:06:30 +0100811 bool need_boot_oat_fixup = true;
Ian Rogersd4c4d952014-10-16 20:31:53 -0700812 for (unsigned int i = 0; i < oat_file->GetProgramHeaderNum(); ++i) {
Tong Shen62d1ca32014-09-03 17:24:56 -0700813 auto hdr = oat_file->GetProgramHeader(i);
Vladimir Marko3fc99032015-05-13 19:06:30 +0100814 if (hdr->p_type == PT_LOAD && hdr->p_vaddr == 0u) {
815 need_boot_oat_fixup = false;
Ian Rogersd4c4d952014-10-16 20:31:53 -0700816 break;
Alex Light53cb16b2014-06-12 11:26:29 -0700817 }
818 }
Vladimir Marko3fc99032015-05-13 19:06:30 +0100819 if (!need_boot_oat_fixup) {
820 // This is an app oat file that can be loaded at an arbitrary address in memory.
821 // Boot image references were patched above and there's nothing else to do.
Alex Lighta59dd802014-07-02 16:28:08 -0700822 return true;
823 }
Tong Shen62d1ca32014-09-03 17:24:56 -0700824
Vladimir Marko3fc99032015-05-13 19:06:30 +0100825 // This is a boot oat file that's loaded at a particular address and we need
826 // to patch all absolute addresses, starting with ELF program headers.
827
Tong Shen62d1ca32014-09-03 17:24:56 -0700828 t.NewTiming("Fixup Elf Headers");
829 // Fixup Phdr's
830 oat_file->FixupProgramHeaders(delta_);
831
Alex Lighta59dd802014-07-02 16:28:08 -0700832 t.NewTiming("Fixup Section Headers");
Tong Shen62d1ca32014-09-03 17:24:56 -0700833 // Fixup Shdr's
834 oat_file->FixupSectionHeaders(delta_);
Alex Light53cb16b2014-06-12 11:26:29 -0700835
Alex Lighta59dd802014-07-02 16:28:08 -0700836 t.NewTiming("Fixup Dynamics");
Tong Shen62d1ca32014-09-03 17:24:56 -0700837 oat_file->FixupDynamic(delta_);
Alex Light53cb16b2014-06-12 11:26:29 -0700838
839 t.NewTiming("Fixup Elf Symbols");
840 // Fixup dynsym
Tong Shen62d1ca32014-09-03 17:24:56 -0700841 if (!oat_file->FixupSymbols(delta_, true)) {
Alex Light53cb16b2014-06-12 11:26:29 -0700842 return false;
843 }
Alex Light53cb16b2014-06-12 11:26:29 -0700844 // Fixup symtab
Tong Shen62d1ca32014-09-03 17:24:56 -0700845 if (!oat_file->FixupSymbols(delta_, false)) {
846 return false;
Alex Light53cb16b2014-06-12 11:26:29 -0700847 }
848
Yevgeny Roubane3ea8382014-08-08 16:29:38 +0700849 t.NewTiming("Fixup Debug Sections");
Tong Shen62d1ca32014-09-03 17:24:56 -0700850 if (!oat_file->FixupDebugSections(delta_)) {
Yevgeny Roubane3ea8382014-08-08 16:29:38 +0700851 return false;
852 }
853
Alex Light53cb16b2014-06-12 11:26:29 -0700854 return true;
855}
856
Alex Light53cb16b2014-06-12 11:26:29 -0700857static int orig_argc;
858static char** orig_argv;
859
860static std::string CommandLine() {
861 std::vector<std::string> command;
862 for (int i = 0; i < orig_argc; ++i) {
863 command.push_back(orig_argv[i]);
864 }
865 return Join(command, ' ');
866}
867
868static void UsageErrorV(const char* fmt, va_list ap) {
869 std::string error;
870 StringAppendV(&error, fmt, ap);
871 LOG(ERROR) << error;
872}
873
874static void UsageError(const char* fmt, ...) {
875 va_list ap;
876 va_start(ap, fmt);
877 UsageErrorV(fmt, ap);
878 va_end(ap);
879}
880
Andreas Gampe794ad762015-02-23 08:12:24 -0800881NO_RETURN static void Usage(const char *fmt, ...) {
Alex Light53cb16b2014-06-12 11:26:29 -0700882 va_list ap;
883 va_start(ap, fmt);
884 UsageErrorV(fmt, ap);
885 va_end(ap);
886
887 UsageError("Command: %s", CommandLine().c_str());
888 UsageError("Usage: patchoat [options]...");
889 UsageError("");
890 UsageError(" --instruction-set=<isa>: Specifies the instruction set the patched code is");
891 UsageError(" compiled for. Required if you use --input-oat-location");
892 UsageError("");
893 UsageError(" --input-oat-file=<file.oat>: Specifies the exact filename of the oat file to be");
894 UsageError(" patched.");
895 UsageError("");
896 UsageError(" --input-oat-fd=<file-descriptor>: Specifies the file-descriptor of the oat file");
897 UsageError(" to be patched.");
898 UsageError("");
899 UsageError(" --input-oat-location=<file.oat>: Specifies the 'location' to read the patched");
900 UsageError(" oat file from. If used one must also supply the --instruction-set");
901 UsageError("");
902 UsageError(" --input-image-location=<file.art>: Specifies the 'location' of the image file to");
903 UsageError(" be patched. If --instruction-set is not given it will use the instruction set");
904 UsageError(" extracted from the --input-oat-file.");
905 UsageError("");
906 UsageError(" --output-oat-file=<file.oat>: Specifies the exact file to write the patched oat");
907 UsageError(" file to.");
908 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700909 UsageError(" --output-oat-fd=<file-descriptor>: Specifies the file-descriptor to write the");
910 UsageError(" the patched oat file to.");
911 UsageError("");
912 UsageError(" --output-image-file=<file.art>: Specifies the exact file to write the patched");
913 UsageError(" image file to.");
914 UsageError("");
915 UsageError(" --output-image-fd=<file-descriptor>: Specifies the file-descriptor to write the");
916 UsageError(" the patched image file to.");
917 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700918 UsageError(" --orig-base-offset=<original-base-offset>: Specify the base offset the input file");
919 UsageError(" was compiled with. This is needed if one is specifying a --base-offset");
920 UsageError("");
921 UsageError(" --base-offset=<new-base-offset>: Specify the base offset we will repatch the");
922 UsageError(" given files to use. This requires that --orig-base-offset is also given.");
923 UsageError("");
924 UsageError(" --base-offset-delta=<delta>: Specify the amount to change the old base-offset by.");
925 UsageError(" This value may be negative.");
926 UsageError("");
Alex Light0eb76d22015-08-11 18:03:47 -0700927 UsageError(" --patched-image-file=<file.art>: Relocate the oat file to be the same as the");
928 UsageError(" given image file.");
Alex Light53cb16b2014-06-12 11:26:29 -0700929 UsageError("");
Alex Light0eb76d22015-08-11 18:03:47 -0700930 UsageError(" --patched-image-location=<file.art>: Relocate the oat file to be the same as the");
931 UsageError(" image at the given location. If used one must also specify the");
Alex Lighta59dd802014-07-02 16:28:08 -0700932 UsageError(" --instruction-set flag. It will search for this image in the same way that");
933 UsageError(" is done when loading one.");
Alex Light53cb16b2014-06-12 11:26:29 -0700934 UsageError("");
Alex Lightcf4bf382014-07-24 11:29:14 -0700935 UsageError(" --lock-output: Obtain a flock on output oat file before starting.");
936 UsageError("");
937 UsageError(" --no-lock-output: Do not attempt to obtain a flock on output oat file.");
938 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700939 UsageError(" --dump-timings: dump out patch timing information");
940 UsageError("");
941 UsageError(" --no-dump-timings: do not dump out patch timing information");
942 UsageError("");
943
944 exit(EXIT_FAILURE);
945}
946
Alex Lighteefbe392014-07-08 09:53:18 -0700947static bool ReadBaseDelta(const char* name, off_t* delta, std::string* error_msg) {
Alex Light53cb16b2014-06-12 11:26:29 -0700948 CHECK(name != nullptr);
949 CHECK(delta != nullptr);
950 std::unique_ptr<File> file;
951 if (OS::FileExists(name)) {
952 file.reset(OS::OpenFileForReading(name));
953 if (file.get() == nullptr) {
Alex Lighteefbe392014-07-08 09:53:18 -0700954 *error_msg = "Failed to open file %s for reading";
Alex Light53cb16b2014-06-12 11:26:29 -0700955 return false;
956 }
957 } else {
Alex Lighteefbe392014-07-08 09:53:18 -0700958 *error_msg = "File %s does not exist";
Alex Light53cb16b2014-06-12 11:26:29 -0700959 return false;
960 }
961 CHECK(file.get() != nullptr);
962 ImageHeader hdr;
963 if (sizeof(hdr) != file->Read(reinterpret_cast<char*>(&hdr), sizeof(hdr), 0)) {
Alex Lighteefbe392014-07-08 09:53:18 -0700964 *error_msg = "Failed to read file %s";
Alex Light53cb16b2014-06-12 11:26:29 -0700965 return false;
966 }
967 if (!hdr.IsValid()) {
Alex Lighteefbe392014-07-08 09:53:18 -0700968 *error_msg = "%s does not contain a valid image header.";
Alex Light53cb16b2014-06-12 11:26:29 -0700969 return false;
970 }
971 *delta = hdr.GetPatchDelta();
972 return true;
973}
974
975static File* CreateOrOpen(const char* name, bool* created) {
976 if (OS::FileExists(name)) {
977 *created = false;
978 return OS::OpenFileReadWrite(name);
979 } else {
980 *created = true;
Alex Lightcf4bf382014-07-24 11:29:14 -0700981 std::unique_ptr<File> f(OS::CreateEmptyFile(name));
982 if (f.get() != nullptr) {
983 if (fchmod(f->Fd(), 0644) != 0) {
984 PLOG(ERROR) << "Unable to make " << name << " world readable";
Brian Carlstrom8c52a3f2014-09-30 16:18:01 -0700985 TEMP_FAILURE_RETRY(unlink(name));
Alex Lightcf4bf382014-07-24 11:29:14 -0700986 return nullptr;
987 }
988 }
989 return f.release();
Alex Light53cb16b2014-06-12 11:26:29 -0700990 }
991}
992
Andreas Gampe4303ba92014-11-06 01:00:46 -0800993// Either try to close the file (close=true), or erase it.
994static bool FinishFile(File* file, bool close) {
995 if (close) {
996 if (file->FlushCloseOrErase() != 0) {
997 PLOG(ERROR) << "Failed to flush and close file.";
998 return false;
999 }
1000 return true;
1001 } else {
1002 file->Erase();
1003 return false;
1004 }
1005}
1006
Alex Lighteefbe392014-07-08 09:53:18 -07001007static int patchoat(int argc, char **argv) {
Alex Light53cb16b2014-06-12 11:26:29 -07001008 InitLogging(argv);
Mathieu Chartier6e88ef62014-10-14 15:01:24 -07001009 MemMap::Init();
Alex Light53cb16b2014-06-12 11:26:29 -07001010 const bool debug = kIsDebugBuild;
1011 orig_argc = argc;
1012 orig_argv = argv;
1013 TimingLogger timings("patcher", false, false);
1014
1015 InitLogging(argv);
1016
1017 // Skip over the command name.
1018 argv++;
1019 argc--;
1020
1021 if (argc == 0) {
1022 Usage("No arguments specified");
1023 }
1024
1025 timings.StartTiming("Patchoat");
1026
1027 // cmd line args
1028 bool isa_set = false;
1029 InstructionSet isa = kNone;
1030 std::string input_oat_filename;
1031 std::string input_oat_location;
1032 int input_oat_fd = -1;
1033 bool have_input_oat = false;
1034 std::string input_image_location;
1035 std::string output_oat_filename;
Alex Light53cb16b2014-06-12 11:26:29 -07001036 int output_oat_fd = -1;
1037 bool have_output_oat = false;
1038 std::string output_image_filename;
Alex Light53cb16b2014-06-12 11:26:29 -07001039 int output_image_fd = -1;
1040 bool have_output_image = false;
1041 uintptr_t base_offset = 0;
1042 bool base_offset_set = false;
1043 uintptr_t orig_base_offset = 0;
1044 bool orig_base_offset_set = false;
1045 off_t base_delta = 0;
1046 bool base_delta_set = false;
Alex Light0eb76d22015-08-11 18:03:47 -07001047 bool match_delta = false;
Alex Light53cb16b2014-06-12 11:26:29 -07001048 std::string patched_image_filename;
1049 std::string patched_image_location;
1050 bool dump_timings = kIsDebugBuild;
Alex Lightcf4bf382014-07-24 11:29:14 -07001051 bool lock_output = true;
Alex Light53cb16b2014-06-12 11:26:29 -07001052
Ian Rogersd4c4d952014-10-16 20:31:53 -07001053 for (int i = 0; i < argc; ++i) {
Alex Light53cb16b2014-06-12 11:26:29 -07001054 const StringPiece option(argv[i]);
1055 const bool log_options = false;
1056 if (log_options) {
1057 LOG(INFO) << "patchoat: option[" << i << "]=" << argv[i];
1058 }
Alex Light53cb16b2014-06-12 11:26:29 -07001059 if (option.starts_with("--instruction-set=")) {
1060 isa_set = true;
1061 const char* isa_str = option.substr(strlen("--instruction-set=")).data();
Andreas Gampe20c89302014-08-19 17:28:06 -07001062 isa = GetInstructionSetFromString(isa_str);
1063 if (isa == kNone) {
1064 Usage("Unknown or invalid instruction set %s", isa_str);
Alex Light53cb16b2014-06-12 11:26:29 -07001065 }
1066 } else if (option.starts_with("--input-oat-location=")) {
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_location = option.substr(strlen("--input-oat-location=")).data();
1072 } else if (option.starts_with("--input-oat-file=")) {
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 input_oat_filename = option.substr(strlen("--input-oat-file=")).data();
1078 } else if (option.starts_with("--input-oat-fd=")) {
1079 if (have_input_oat) {
1080 Usage("Only one of --input-oat-file, --input-oat-location and --input-oat-fd may be used.");
1081 }
1082 have_input_oat = true;
1083 const char* oat_fd_str = option.substr(strlen("--input-oat-fd=")).data();
1084 if (!ParseInt(oat_fd_str, &input_oat_fd)) {
1085 Usage("Failed to parse --input-oat-fd argument '%s' as an integer", oat_fd_str);
1086 }
1087 if (input_oat_fd < 0) {
1088 Usage("--input-oat-fd pass a negative value %d", input_oat_fd);
1089 }
1090 } else if (option.starts_with("--input-image-location=")) {
1091 input_image_location = option.substr(strlen("--input-image-location=")).data();
Alex Light53cb16b2014-06-12 11:26:29 -07001092 } else if (option.starts_with("--output-oat-file=")) {
1093 if (have_output_oat) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001094 Usage("Only one of --output-oat-file, and --output-oat-fd may be used.");
Alex Light53cb16b2014-06-12 11:26:29 -07001095 }
1096 have_output_oat = true;
1097 output_oat_filename = option.substr(strlen("--output-oat-file=")).data();
1098 } else if (option.starts_with("--output-oat-fd=")) {
1099 if (have_output_oat) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001100 Usage("Only one of --output-oat-file, --output-oat-fd may be used.");
Alex Light53cb16b2014-06-12 11:26:29 -07001101 }
1102 have_output_oat = true;
1103 const char* oat_fd_str = option.substr(strlen("--output-oat-fd=")).data();
1104 if (!ParseInt(oat_fd_str, &output_oat_fd)) {
1105 Usage("Failed to parse --output-oat-fd argument '%s' as an integer", oat_fd_str);
1106 }
1107 if (output_oat_fd < 0) {
1108 Usage("--output-oat-fd pass a negative value %d", output_oat_fd);
1109 }
Alex Light53cb16b2014-06-12 11:26:29 -07001110 } else if (option.starts_with("--output-image-file=")) {
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 output_image_filename = option.substr(strlen("--output-image-file=")).data();
1116 } else if (option.starts_with("--output-image-fd=")) {
1117 if (have_output_image) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001118 Usage("Only one of --output-image-file, and --output-image-fd may be used.");
Alex Light53cb16b2014-06-12 11:26:29 -07001119 }
1120 have_output_image = true;
1121 const char* image_fd_str = option.substr(strlen("--output-image-fd=")).data();
1122 if (!ParseInt(image_fd_str, &output_image_fd)) {
1123 Usage("Failed to parse --output-image-fd argument '%s' as an integer", image_fd_str);
1124 }
1125 if (output_image_fd < 0) {
1126 Usage("--output-image-fd pass a negative value %d", output_image_fd);
1127 }
1128 } else if (option.starts_with("--orig-base-offset=")) {
1129 const char* orig_base_offset_str = option.substr(strlen("--orig-base-offset=")).data();
1130 orig_base_offset_set = true;
1131 if (!ParseUint(orig_base_offset_str, &orig_base_offset)) {
1132 Usage("Failed to parse --orig-base-offset argument '%s' as an uintptr_t",
1133 orig_base_offset_str);
1134 }
1135 } else if (option.starts_with("--base-offset=")) {
1136 const char* base_offset_str = option.substr(strlen("--base-offset=")).data();
1137 base_offset_set = true;
1138 if (!ParseUint(base_offset_str, &base_offset)) {
1139 Usage("Failed to parse --base-offset argument '%s' as an uintptr_t", base_offset_str);
1140 }
1141 } else if (option.starts_with("--base-offset-delta=")) {
1142 const char* base_delta_str = option.substr(strlen("--base-offset-delta=")).data();
1143 base_delta_set = true;
1144 if (!ParseInt(base_delta_str, &base_delta)) {
1145 Usage("Failed to parse --base-offset-delta argument '%s' as an off_t", base_delta_str);
1146 }
1147 } else if (option.starts_with("--patched-image-location=")) {
1148 patched_image_location = option.substr(strlen("--patched-image-location=")).data();
1149 } else if (option.starts_with("--patched-image-file=")) {
1150 patched_image_filename = option.substr(strlen("--patched-image-file=")).data();
Alex Lightcf4bf382014-07-24 11:29:14 -07001151 } else if (option == "--lock-output") {
1152 lock_output = true;
1153 } else if (option == "--no-lock-output") {
1154 lock_output = false;
Alex Light53cb16b2014-06-12 11:26:29 -07001155 } else if (option == "--dump-timings") {
1156 dump_timings = true;
1157 } else if (option == "--no-dump-timings") {
1158 dump_timings = false;
1159 } else {
1160 Usage("Unknown argument %s", option.data());
1161 }
1162 }
1163
1164 {
1165 // Only 1 of these may be set.
1166 uint32_t cnt = 0;
1167 cnt += (base_delta_set) ? 1 : 0;
1168 cnt += (base_offset_set && orig_base_offset_set) ? 1 : 0;
1169 cnt += (!patched_image_filename.empty()) ? 1 : 0;
1170 cnt += (!patched_image_location.empty()) ? 1 : 0;
1171 if (cnt > 1) {
1172 Usage("Only one of --base-offset/--orig-base-offset, --base-offset-delta, "
1173 "--patched-image-filename or --patched-image-location may be used.");
1174 } else if (cnt == 0) {
1175 Usage("Must specify --base-offset-delta, --base-offset and --orig-base-offset, "
1176 "--patched-image-location or --patched-image-file");
1177 }
1178 }
1179
1180 if (have_input_oat != have_output_oat) {
1181 Usage("Either both input and output oat must be supplied or niether must be.");
1182 }
1183
1184 if ((!input_image_location.empty()) != have_output_image) {
1185 Usage("Either both input and output image must be supplied or niether must be.");
1186 }
1187
1188 // We know we have both the input and output so rename for clarity.
1189 bool have_image_files = have_output_image;
1190 bool have_oat_files = have_output_oat;
1191
1192 if (!have_oat_files && !have_image_files) {
1193 Usage("Must be patching either an oat or an image file or both.");
1194 }
1195
1196 if (!have_oat_files && !isa_set) {
1197 Usage("Must include ISA if patching an image file without an oat file.");
1198 }
1199
1200 if (!input_oat_location.empty()) {
1201 if (!isa_set) {
1202 Usage("specifying a location requires specifying an instruction set");
1203 }
Alex Lightcf4bf382014-07-24 11:29:14 -07001204 if (!LocationToFilename(input_oat_location, isa, &input_oat_filename)) {
1205 Usage("Unable to find filename for input oat location %s", input_oat_location.c_str());
1206 }
Alex Light53cb16b2014-06-12 11:26:29 -07001207 if (debug) {
1208 LOG(INFO) << "Using input-oat-file " << input_oat_filename;
1209 }
1210 }
Alex Light53cb16b2014-06-12 11:26:29 -07001211 if (!patched_image_location.empty()) {
1212 if (!isa_set) {
1213 Usage("specifying a location requires specifying an instruction set");
1214 }
Alex Lighta59dd802014-07-02 16:28:08 -07001215 std::string system_filename;
1216 bool has_system = false;
1217 std::string cache_filename;
1218 bool has_cache = false;
1219 bool has_android_data_unused = false;
Andreas Gampe3c13a792014-09-18 20:56:04 -07001220 bool is_global_cache = false;
Alex Lighta59dd802014-07-02 16:28:08 -07001221 if (!gc::space::ImageSpace::FindImageFilename(patched_image_location.c_str(), isa,
1222 &system_filename, &has_system, &cache_filename,
Andreas Gampe3c13a792014-09-18 20:56:04 -07001223 &has_android_data_unused, &has_cache,
1224 &is_global_cache)) {
Alex Lighta59dd802014-07-02 16:28:08 -07001225 Usage("Unable to determine image file for location %s", patched_image_location.c_str());
1226 }
1227 if (has_cache) {
1228 patched_image_filename = cache_filename;
1229 } else if (has_system) {
1230 LOG(WARNING) << "Only image file found was in /system for image location "
1231 << patched_image_location;
1232 patched_image_filename = system_filename;
1233 } else {
1234 Usage("Unable to determine image file for location %s", patched_image_location.c_str());
1235 }
Alex Light53cb16b2014-06-12 11:26:29 -07001236 if (debug) {
1237 LOG(INFO) << "Using patched-image-file " << patched_image_filename;
1238 }
1239 }
1240
1241 if (!base_delta_set) {
1242 if (orig_base_offset_set && base_offset_set) {
1243 base_delta_set = true;
1244 base_delta = base_offset - orig_base_offset;
1245 } else if (!patched_image_filename.empty()) {
Alex Light0eb76d22015-08-11 18:03:47 -07001246 if (have_image_files) {
1247 Usage("--patched-image-location should not be used when patching other images");
1248 }
Alex Light53cb16b2014-06-12 11:26:29 -07001249 base_delta_set = true;
Alex Light0eb76d22015-08-11 18:03:47 -07001250 match_delta = true;
Alex Light53cb16b2014-06-12 11:26:29 -07001251 std::string error_msg;
Alex Lighteefbe392014-07-08 09:53:18 -07001252 if (!ReadBaseDelta(patched_image_filename.c_str(), &base_delta, &error_msg)) {
Alex Light53cb16b2014-06-12 11:26:29 -07001253 Usage(error_msg.c_str(), patched_image_filename.c_str());
1254 }
1255 } else {
1256 if (base_offset_set) {
1257 Usage("Unable to determine original base offset.");
1258 } else {
1259 Usage("Must supply a desired new offset or delta.");
1260 }
1261 }
1262 }
1263
1264 if (!IsAligned<kPageSize>(base_delta)) {
1265 Usage("Base offset/delta must be alligned to a pagesize (0x%08x) boundary.", kPageSize);
1266 }
1267
1268 // Do we need to cleanup output files if we fail?
1269 bool new_image_out = false;
1270 bool new_oat_out = false;
1271
1272 std::unique_ptr<File> input_oat;
1273 std::unique_ptr<File> output_oat;
1274 std::unique_ptr<File> output_image;
1275
1276 if (have_image_files) {
1277 CHECK(!input_image_location.empty());
1278
1279 if (output_image_fd != -1) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001280 if (output_image_filename.empty()) {
1281 output_image_filename = "output-image-file";
1282 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001283 output_image.reset(new File(output_image_fd, output_image_filename, true));
Alex Light53cb16b2014-06-12 11:26:29 -07001284 } else {
1285 CHECK(!output_image_filename.empty());
1286 output_image.reset(CreateOrOpen(output_image_filename.c_str(), &new_image_out));
1287 }
1288 } else {
1289 CHECK(output_image_filename.empty() && output_image_fd == -1 && input_image_location.empty());
1290 }
1291
1292 if (have_oat_files) {
1293 if (input_oat_fd != -1) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001294 if (input_oat_filename.empty()) {
1295 input_oat_filename = "input-oat-file";
1296 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001297 input_oat.reset(new File(input_oat_fd, input_oat_filename, false));
Julien Delayena473f512015-03-05 16:37:52 +01001298 if (input_oat_fd == output_oat_fd) {
1299 input_oat.get()->DisableAutoClose();
1300 }
Igor Murashkin46774762014-10-22 11:37:02 -07001301 if (input_oat == nullptr) {
1302 // Unlikely, but ensure exhaustive logging in non-0 exit code case
1303 LOG(ERROR) << "Failed to open input oat file by its FD" << input_oat_fd;
1304 }
Alex Light53cb16b2014-06-12 11:26:29 -07001305 } else {
1306 CHECK(!input_oat_filename.empty());
1307 input_oat.reset(OS::OpenFileForReading(input_oat_filename.c_str()));
Igor Murashkin46774762014-10-22 11:37:02 -07001308 if (input_oat == nullptr) {
1309 int err = errno;
1310 LOG(ERROR) << "Failed to open input oat file " << input_oat_filename
1311 << ": " << strerror(err) << "(" << err << ")";
Andreas Gampe1c83cbc2014-07-22 18:52:29 -07001312 }
Alex Light53cb16b2014-06-12 11:26:29 -07001313 }
1314
1315 if (output_oat_fd != -1) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001316 if (output_oat_filename.empty()) {
1317 output_oat_filename = "output-oat-file";
Alex Lighta59dd802014-07-02 16:28:08 -07001318 }
Andreas Gampe4303ba92014-11-06 01:00:46 -08001319 output_oat.reset(new File(output_oat_fd, output_oat_filename, true));
Igor Murashkin46774762014-10-22 11:37:02 -07001320 if (output_oat == nullptr) {
1321 // Unlikely, but ensure exhaustive logging in non-0 exit code case
1322 LOG(ERROR) << "Failed to open output oat file by its FD" << output_oat_fd;
1323 }
Alex Light53cb16b2014-06-12 11:26:29 -07001324 } else {
1325 CHECK(!output_oat_filename.empty());
1326 output_oat.reset(CreateOrOpen(output_oat_filename.c_str(), &new_oat_out));
Igor Murashkin46774762014-10-22 11:37:02 -07001327 if (output_oat == nullptr) {
1328 int err = errno;
1329 LOG(ERROR) << "Failed to open output oat file " << output_oat_filename
1330 << ": " << strerror(err) << "(" << err << ")";
1331 }
Alex Light53cb16b2014-06-12 11:26:29 -07001332 }
1333 }
1334
Igor Murashkin46774762014-10-22 11:37:02 -07001335 // TODO: get rid of this.
Alex Light53cb16b2014-06-12 11:26:29 -07001336 auto cleanup = [&output_image_filename, &output_oat_filename,
1337 &new_oat_out, &new_image_out, &timings, &dump_timings](bool success) {
1338 timings.EndTiming();
1339 if (!success) {
1340 if (new_oat_out) {
1341 CHECK(!output_oat_filename.empty());
Brian Carlstrom8c52a3f2014-09-30 16:18:01 -07001342 TEMP_FAILURE_RETRY(unlink(output_oat_filename.c_str()));
Alex Light53cb16b2014-06-12 11:26:29 -07001343 }
1344 if (new_image_out) {
1345 CHECK(!output_image_filename.empty());
Brian Carlstrom8c52a3f2014-09-30 16:18:01 -07001346 TEMP_FAILURE_RETRY(unlink(output_image_filename.c_str()));
Alex Light53cb16b2014-06-12 11:26:29 -07001347 }
1348 }
1349 if (dump_timings) {
1350 LOG(INFO) << Dumpable<TimingLogger>(timings);
1351 }
Igor Murashkin46774762014-10-22 11:37:02 -07001352
1353 if (kIsDebugBuild) {
1354 LOG(INFO) << "Cleaning up.. success? " << success;
1355 }
Alex Light53cb16b2014-06-12 11:26:29 -07001356 };
1357
Igor Murashkin46774762014-10-22 11:37:02 -07001358 if (have_oat_files && (input_oat.get() == nullptr || output_oat.get() == nullptr)) {
1359 LOG(ERROR) << "Failed to open input/output oat files";
1360 cleanup(false);
1361 return EXIT_FAILURE;
1362 } else if (have_image_files && output_image.get() == nullptr) {
1363 LOG(ERROR) << "Failed to open output image file";
Alex Lightcf4bf382014-07-24 11:29:14 -07001364 cleanup(false);
1365 return EXIT_FAILURE;
1366 }
1367
Alex Light0eb76d22015-08-11 18:03:47 -07001368 if (match_delta) {
1369 CHECK(!have_image_files); // We will not do this with images.
1370 std::string error_msg;
1371 // Figure out what the current delta is so we can match it to the desired delta.
1372 std::unique_ptr<ElfFile> elf(ElfFile::Open(input_oat.get(), PROT_READ, MAP_PRIVATE,
1373 &error_msg));
1374 off_t current_delta = 0;
1375 if (elf.get() == nullptr) {
1376 LOG(ERROR) << "unable to open oat file " << input_oat->GetPath() << " : " << error_msg;
1377 cleanup(false);
1378 return EXIT_FAILURE;
1379 } else if (!ReadOatPatchDelta(elf.get(), &current_delta, &error_msg)) {
1380 LOG(ERROR) << "Unable to get current delta: " << error_msg;
1381 cleanup(false);
1382 return EXIT_FAILURE;
1383 }
1384 // Before this line base_delta is the desired final delta. We need it to be the actual amount to
1385 // change everything by. We subtract the current delta from it to make it this.
1386 base_delta -= current_delta;
1387 if (!IsAligned<kPageSize>(base_delta)) {
1388 LOG(ERROR) << "Given image file was relocated by an illegal delta";
1389 cleanup(false);
1390 return false;
1391 }
1392 }
1393
Igor Murashkin46774762014-10-22 11:37:02 -07001394 if (debug) {
1395 LOG(INFO) << "moving offset by " << base_delta
1396 << " (0x" << std::hex << base_delta << ") bytes or "
1397 << std::dec << (base_delta/kPageSize) << " pages.";
1398 }
1399
1400 // TODO: is it going to be promatic to unlink a file that was flock-ed?
Alex Lightcf4bf382014-07-24 11:29:14 -07001401 ScopedFlock output_oat_lock;
1402 if (lock_output) {
1403 std::string error_msg;
1404 if (have_oat_files && !output_oat_lock.Init(output_oat.get(), &error_msg)) {
1405 LOG(ERROR) << "Unable to lock output oat " << output_image->GetPath() << ": " << error_msg;
1406 cleanup(false);
1407 return EXIT_FAILURE;
1408 }
1409 }
1410
Alex Light53cb16b2014-06-12 11:26:29 -07001411 bool ret;
1412 if (have_image_files && have_oat_files) {
1413 TimingLogger::ScopedTiming pt("patch image and oat", &timings);
1414 ret = PatchOat::Patch(input_oat.get(), input_image_location, base_delta,
Igor Murashkin46774762014-10-22 11:37:02 -07001415 output_oat.get(), output_image.get(), isa, &timings,
1416 output_oat_fd >= 0, // was it opened from FD?
1417 new_oat_out);
Andreas Gampe4303ba92014-11-06 01:00:46 -08001418 // The order here doesn't matter. If the first one is successfully saved and the second one
1419 // erased, ImageSpace will still detect a problem and not use the files.
Alex Light0eb76d22015-08-11 18:03:47 -07001420 ret = FinishFile(output_image.get(), ret);
1421 ret = FinishFile(output_oat.get(), ret);
Alex Light53cb16b2014-06-12 11:26:29 -07001422 } else if (have_oat_files) {
1423 TimingLogger::ScopedTiming pt("patch oat", &timings);
Igor Murashkin46774762014-10-22 11:37:02 -07001424 ret = PatchOat::Patch(input_oat.get(), base_delta, output_oat.get(), &timings,
1425 output_oat_fd >= 0, // was it opened from FD?
1426 new_oat_out);
Alex Light0eb76d22015-08-11 18:03:47 -07001427 ret = FinishFile(output_oat.get(), ret);
Igor Murashkin46774762014-10-22 11:37:02 -07001428 } else if (have_image_files) {
Alex Light53cb16b2014-06-12 11:26:29 -07001429 TimingLogger::ScopedTiming pt("patch image", &timings);
Alex Lighteefbe392014-07-08 09:53:18 -07001430 ret = PatchOat::Patch(input_image_location, base_delta, output_image.get(), isa, &timings);
Alex Light0eb76d22015-08-11 18:03:47 -07001431 ret = FinishFile(output_image.get(), ret);
Igor Murashkin46774762014-10-22 11:37:02 -07001432 } else {
1433 CHECK(false);
1434 ret = true;
1435 }
1436
1437 if (kIsDebugBuild) {
1438 LOG(INFO) << "Exiting with return ... " << ret;
Alex Light53cb16b2014-06-12 11:26:29 -07001439 }
1440 cleanup(ret);
Alex Light53cb16b2014-06-12 11:26:29 -07001441 return (ret) ? EXIT_SUCCESS : EXIT_FAILURE;
1442}
1443
1444} // namespace art
1445
1446int main(int argc, char **argv) {
1447 return art::patchoat(argc, argv);
1448}