blob: d58f38cc0676437303fc50649715e38355e185c5 [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"
David Brazdil7b49e6c2016-09-01 11:06:18 +010034#include "base/unix_file/random_access_file_utils.h"
Alex Light53cb16b2014-06-12 11:26:29 -070035#include "elf_utils.h"
36#include "elf_file.h"
Tong Shen62d1ca32014-09-03 17:24:56 -070037#include "elf_file_impl.h"
Ian Rogerse63db272014-07-15 15:36:11 -070038#include "gc/space/image_space.h"
Mathieu Chartier4a26f172016-01-26 14:26:18 -080039#include "image-inl.h"
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -070040#include "mirror/dex_cache.h"
Neil Fuller0e844392016-09-08 13:43:31 +010041#include "mirror/executable.h"
Alex Light53cb16b2014-06-12 11:26:29 -070042#include "mirror/object-inl.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070043#include "mirror/method.h"
Alex Light53cb16b2014-06-12 11:26:29 -070044#include "mirror/reference.h"
45#include "noop_compiler_callbacks.h"
46#include "offsets.h"
47#include "os.h"
48#include "runtime.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070049#include "scoped_thread_state_change-inl.h"
Alex Light53cb16b2014-06-12 11:26:29 -070050#include "thread.h"
51#include "utils.h"
52
53namespace art {
54
Alex Lightcf4bf382014-07-24 11:29:14 -070055static bool LocationToFilename(const std::string& location, InstructionSet isa,
56 std::string* filename) {
57 bool has_system = false;
58 bool has_cache = false;
59 // image_location = /system/framework/boot.art
Igor Murashkin46774762014-10-22 11:37:02 -070060 // system_image_filename = /system/framework/<image_isa>/boot.art
Alex Lightcf4bf382014-07-24 11:29:14 -070061 std::string system_filename(GetSystemImageFilename(location.c_str(), isa));
62 if (OS::FileExists(system_filename.c_str())) {
63 has_system = true;
64 }
65
66 bool have_android_data = false;
67 bool dalvik_cache_exists = false;
Andreas Gampe3c13a792014-09-18 20:56:04 -070068 bool is_global_cache = false;
Alex Lightcf4bf382014-07-24 11:29:14 -070069 std::string dalvik_cache;
70 GetDalvikCache(GetInstructionSetString(isa), false, &dalvik_cache,
Andreas Gampe3c13a792014-09-18 20:56:04 -070071 &have_android_data, &dalvik_cache_exists, &is_global_cache);
Alex Lightcf4bf382014-07-24 11:29:14 -070072
73 std::string cache_filename;
74 if (have_android_data && dalvik_cache_exists) {
75 // Always set output location even if it does not exist,
76 // so that the caller knows where to create the image.
77 //
78 // image_location = /system/framework/boot.art
79 // *image_filename = /data/dalvik-cache/<image_isa>/boot.art
80 std::string error_msg;
81 if (GetDalvikCacheFilename(location.c_str(), dalvik_cache.c_str(),
82 &cache_filename, &error_msg)) {
83 has_cache = true;
84 }
85 }
86 if (has_system) {
87 *filename = system_filename;
88 return true;
89 } else if (has_cache) {
90 *filename = cache_filename;
91 return true;
92 } else {
93 return false;
94 }
95}
96
Alex Light0eb76d22015-08-11 18:03:47 -070097static const OatHeader* GetOatHeader(const ElfFile* elf_file) {
98 uint64_t off = 0;
99 if (!elf_file->GetSectionOffsetAndSize(".rodata", &off, nullptr)) {
100 return nullptr;
101 }
102
103 OatHeader* oat_header = reinterpret_cast<OatHeader*>(elf_file->Begin() + off);
104 return oat_header;
105}
106
107// This function takes an elf file and reads the current patch delta value
108// encoded in its oat header value
109static bool ReadOatPatchDelta(const ElfFile* elf_file, off_t* delta, std::string* error_msg) {
110 const OatHeader* oat_header = GetOatHeader(elf_file);
111 if (oat_header == nullptr) {
112 *error_msg = "Unable to get oat header from elf file.";
113 return false;
114 }
115 if (!oat_header->IsValid()) {
116 *error_msg = "Elf file has an invalid oat header";
117 return false;
118 }
119 *delta = oat_header->GetImagePatchDelta();
120 return true;
121}
122
Jeff Haodcdc85b2015-12-04 14:06:18 -0800123static File* CreateOrOpen(const char* name, bool* created) {
124 if (OS::FileExists(name)) {
125 *created = false;
126 return OS::OpenFileReadWrite(name);
127 } else {
128 *created = true;
129 std::unique_ptr<File> f(OS::CreateEmptyFile(name));
130 if (f.get() != nullptr) {
131 if (fchmod(f->Fd(), 0644) != 0) {
132 PLOG(ERROR) << "Unable to make " << name << " world readable";
Dimitry Ivanov7a1c0142016-03-17 15:59:38 -0700133 unlink(name);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800134 return nullptr;
135 }
136 }
137 return f.release();
138 }
139}
140
141// Either try to close the file (close=true), or erase it.
142static bool FinishFile(File* file, bool close) {
143 if (close) {
144 if (file->FlushCloseOrErase() != 0) {
145 PLOG(ERROR) << "Failed to flush and close file.";
146 return false;
147 }
148 return true;
149 } else {
150 file->Erase();
151 return false;
152 }
153}
154
David Brazdil7b49e6c2016-09-01 11:06:18 +0100155static bool SymlinkFile(const std::string& input_filename, const std::string& output_filename) {
156 if (input_filename == output_filename) {
157 // Input and output are the same, nothing to do.
158 return true;
159 }
160
161 // Unlink the original filename, since we are overwriting it.
162 unlink(output_filename.c_str());
163
164 // Create a symlink from the source file to the target path.
165 if (symlink(input_filename.c_str(), output_filename.c_str()) < 0) {
166 PLOG(ERROR) << "Failed to create symlink " << output_filename << " -> " << input_filename;
167 return false;
168 }
169
170 if (kIsDebugBuild) {
171 LOG(INFO) << "Created symlink " << output_filename << " -> " << input_filename;
172 }
173
174 return true;
175}
176
Andreas Gampe6eb6a392016-02-10 20:18:37 -0800177bool PatchOat::Patch(const std::string& image_location,
178 off_t delta,
179 const std::string& output_directory,
180 InstructionSet isa,
181 TimingLogger* timings) {
Alex Light53cb16b2014-06-12 11:26:29 -0700182 CHECK(Runtime::Current() == nullptr);
Alex Light53cb16b2014-06-12 11:26:29 -0700183 CHECK(!image_location.empty()) << "image file must have a filename.";
184
Alex Lighteefbe392014-07-08 09:53:18 -0700185 TimingLogger::ScopedTiming t("Runtime Setup", timings);
Alex Light53cb16b2014-06-12 11:26:29 -0700186
Andreas Gampe6eb6a392016-02-10 20:18:37 -0800187 CHECK_NE(isa, kNone);
Alex Light53cb16b2014-06-12 11:26:29 -0700188 const char* isa_name = GetInstructionSetString(isa);
Igor Murashkin46774762014-10-22 11:37:02 -0700189
Alex Light53cb16b2014-06-12 11:26:29 -0700190 // Set up the runtime
Ian Rogerse63db272014-07-15 15:36:11 -0700191 RuntimeOptions options;
Alex Light53cb16b2014-06-12 11:26:29 -0700192 NoopCompilerCallbacks callbacks;
193 options.push_back(std::make_pair("compilercallbacks", &callbacks));
194 std::string img = "-Ximage:" + image_location;
195 options.push_back(std::make_pair(img.c_str(), nullptr));
196 options.push_back(std::make_pair("imageinstructionset", reinterpret_cast<const void*>(isa_name)));
Calin Juravle01aaf6e2015-06-19 22:05:39 +0100197 options.push_back(std::make_pair("-Xno-sig-chain", nullptr));
Alex Light53cb16b2014-06-12 11:26:29 -0700198 if (!Runtime::Create(options, false)) {
199 LOG(ERROR) << "Unable to initialize runtime";
200 return false;
201 }
202 // Runtime::Create acquired the mutator_lock_ that is normally given away when we Runtime::Start,
203 // give it away now and then switch to a more manageable ScopedObjectAccess.
204 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
205 ScopedObjectAccess soa(Thread::Current());
206
207 t.NewTiming("Image and oat Patching setup");
Jeff Haodcdc85b2015-12-04 14:06:18 -0800208 std::vector<gc::space::ImageSpace*> spaces = Runtime::Current()->GetHeap()->GetBootImageSpaces();
209 std::map<gc::space::ImageSpace*, std::unique_ptr<File>> space_to_file_map;
210 std::map<gc::space::ImageSpace*, std::unique_ptr<MemMap>> space_to_memmap_map;
211 std::map<gc::space::ImageSpace*, PatchOat> space_to_patchoat_map;
212 std::map<gc::space::ImageSpace*, bool> space_to_skip_patching_map;
Alex Light53cb16b2014-06-12 11:26:29 -0700213
Jeff Haodcdc85b2015-12-04 14:06:18 -0800214 for (size_t i = 0; i < spaces.size(); ++i) {
215 gc::space::ImageSpace* space = spaces[i];
216 std::string input_image_filename = space->GetImageFilename();
217 std::unique_ptr<File> input_image(OS::OpenFileForReading(input_image_filename.c_str()));
218 if (input_image.get() == nullptr) {
219 LOG(ERROR) << "Unable to open input image file at " << input_image_filename;
Igor Murashkin46774762014-10-22 11:37:02 -0700220 return false;
221 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800222
223 int64_t image_len = input_image->GetLength();
224 if (image_len < 0) {
225 LOG(ERROR) << "Error while getting image length";
226 return false;
227 }
228 ImageHeader image_header;
229 if (sizeof(image_header) != input_image->Read(reinterpret_cast<char*>(&image_header),
230 sizeof(image_header), 0)) {
231 LOG(ERROR) << "Unable to read image header from image file " << input_image->GetPath();
232 }
233
234 /*bool is_image_pic = */IsImagePic(image_header, input_image->GetPath());
235 // Nothing special to do right now since the image always needs to get patched.
236 // Perhaps in some far-off future we may have images with relative addresses that are true-PIC.
237
238 // Create the map where we will write the image patches to.
239 std::string error_msg;
240 std::unique_ptr<MemMap> image(MemMap::MapFile(image_len,
241 PROT_READ | PROT_WRITE,
242 MAP_PRIVATE,
243 input_image->Fd(),
244 0,
245 /*low_4gb*/false,
246 input_image->GetPath().c_str(),
247 &error_msg));
248 if (image.get() == nullptr) {
249 LOG(ERROR) << "Unable to map image file " << input_image->GetPath() << " : " << error_msg;
250 return false;
251 }
252 space_to_file_map.emplace(space, std::move(input_image));
253 space_to_memmap_map.emplace(space, std::move(image));
Igor Murashkin46774762014-10-22 11:37:02 -0700254 }
255
David Brazdil7b49e6c2016-09-01 11:06:18 +0100256 // Do a first pass over the image spaces. Symlink PIC oat and vdex files, and
257 // prepare PatchOat instances for the rest.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800258 for (size_t i = 0; i < spaces.size(); ++i) {
259 gc::space::ImageSpace* space = spaces[i];
260 std::string input_image_filename = space->GetImageFilename();
David Brazdil7b49e6c2016-09-01 11:06:18 +0100261 std::string input_vdex_filename =
262 ImageHeader::GetVdexLocationFromImageLocation(input_image_filename);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800263 std::string input_oat_filename =
264 ImageHeader::GetOatLocationFromImageLocation(input_image_filename);
265 std::unique_ptr<File> input_oat_file(OS::OpenFileForReading(input_oat_filename.c_str()));
266 if (input_oat_file.get() == nullptr) {
267 LOG(ERROR) << "Unable to open input oat file at " << input_oat_filename;
268 return false;
269 }
270 std::string error_msg;
271 std::unique_ptr<ElfFile> elf(ElfFile::Open(input_oat_file.get(),
272 PROT_READ | PROT_WRITE, MAP_PRIVATE, &error_msg));
273 if (elf.get() == nullptr) {
274 LOG(ERROR) << "Unable to open oat file " << input_oat_file->GetPath() << " : " << error_msg;
275 return false;
276 }
277
278 bool skip_patching_oat = false;
279 MaybePic is_oat_pic = IsOatPic(elf.get());
280 if (is_oat_pic >= ERROR_FIRST) {
281 // Error logged by IsOatPic
282 return false;
283 } else if (is_oat_pic == PIC) {
284 // Do not need to do ELF-file patching. Create a symlink and skip the ELF patching.
285
286 std::string converted_image_filename = space->GetImageLocation();
287 std::replace(converted_image_filename.begin() + 1, converted_image_filename.end(), '/', '@');
288 std::string output_image_filename = output_directory +
289 (StartsWith(converted_image_filename, "/") ? "" : "/") +
290 converted_image_filename;
David Brazdil7b49e6c2016-09-01 11:06:18 +0100291 std::string output_vdex_filename =
292 ImageHeader::GetVdexLocationFromImageLocation(output_image_filename);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800293 std::string output_oat_filename =
294 ImageHeader::GetOatLocationFromImageLocation(output_image_filename);
295
296 if (!ReplaceOatFileWithSymlink(input_oat_file->GetPath(),
297 output_oat_filename,
298 false,
David Brazdil7b49e6c2016-09-01 11:06:18 +0100299 true) ||
300 !SymlinkFile(input_vdex_filename, output_vdex_filename)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800301 // Errors already logged by above call.
302 return false;
303 }
304 // Don't patch the OAT, since we just symlinked it. Image still needs patching.
305 skip_patching_oat = true;
306 } else {
307 CHECK(is_oat_pic == NOT_PIC);
308 }
309
310 PatchOat& p = space_to_patchoat_map.emplace(space,
311 PatchOat(
312 isa,
313 elf.release(),
314 space_to_memmap_map.find(space)->second.get(),
315 space->GetLiveBitmap(),
316 space->GetMemMap(),
317 delta,
318 &space_to_memmap_map,
319 timings)).first->second;
320
321 t.NewTiming("Patching files");
322 if (!skip_patching_oat && !p.PatchElf()) {
323 LOG(ERROR) << "Failed to patch oat file " << input_oat_file->GetPath();
324 return false;
325 }
326 if (!p.PatchImage(i == 0)) {
327 LOG(ERROR) << "Failed to patch image file " << input_image_filename;
328 return false;
329 }
330
331 space_to_skip_patching_map.emplace(space, skip_patching_oat);
Alex Light53cb16b2014-06-12 11:26:29 -0700332 }
333
David Brazdil7b49e6c2016-09-01 11:06:18 +0100334 // Do a second pass over the image spaces. Patch image files, non-PIC oat files
335 // and symlink their corresponding vdex files.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800336 for (size_t i = 0; i < spaces.size(); ++i) {
337 gc::space::ImageSpace* space = spaces[i];
338 std::string input_image_filename = space->GetImageFilename();
David Brazdil7b49e6c2016-09-01 11:06:18 +0100339 std::string input_vdex_filename =
340 ImageHeader::GetVdexLocationFromImageLocation(input_image_filename);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800341
342 t.NewTiming("Writing files");
343 std::string converted_image_filename = space->GetImageLocation();
344 std::replace(converted_image_filename.begin() + 1, converted_image_filename.end(), '/', '@');
345 std::string output_image_filename = output_directory +
346 (StartsWith(converted_image_filename, "/") ? "" : "/") +
347 converted_image_filename;
Andreas Gampe6eb6a392016-02-10 20:18:37 -0800348 bool new_oat_out;
Jeff Haodcdc85b2015-12-04 14:06:18 -0800349 std::unique_ptr<File>
350 output_image_file(CreateOrOpen(output_image_filename.c_str(), &new_oat_out));
351 if (output_image_file.get() == nullptr) {
352 LOG(ERROR) << "Failed to open output image file at " << output_image_filename;
353 return false;
354 }
355
356 PatchOat& p = space_to_patchoat_map.find(space)->second;
357
Serdjuk, Nikolay Yd12f9c12016-03-22 10:06:33 +0600358 bool success = p.WriteImage(output_image_file.get());
359 success = FinishFile(output_image_file.get(), success);
360 if (!success) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800361 return false;
362 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800363
364 bool skip_patching_oat = space_to_skip_patching_map.find(space)->second;
365 if (!skip_patching_oat) {
David Brazdil7b49e6c2016-09-01 11:06:18 +0100366 std::string output_vdex_filename =
367 ImageHeader::GetVdexLocationFromImageLocation(output_image_filename);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800368 std::string output_oat_filename =
369 ImageHeader::GetOatLocationFromImageLocation(output_image_filename);
David Brazdil7b49e6c2016-09-01 11:06:18 +0100370
Jeff Haodcdc85b2015-12-04 14:06:18 -0800371 std::unique_ptr<File>
372 output_oat_file(CreateOrOpen(output_oat_filename.c_str(), &new_oat_out));
373 if (output_oat_file.get() == nullptr) {
374 LOG(ERROR) << "Failed to open output oat file at " << output_oat_filename;
375 return false;
376 }
Serdjuk, Nikolay Yd12f9c12016-03-22 10:06:33 +0600377 success = p.WriteElf(output_oat_file.get());
378 success = FinishFile(output_oat_file.get(), success);
David Brazdil7b49e6c2016-09-01 11:06:18 +0100379 if (success) {
380 success = SymlinkFile(input_vdex_filename, output_vdex_filename);
381 }
Serdjuk, Nikolay Yd12f9c12016-03-22 10:06:33 +0600382 if (!success) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800383 return false;
384 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800385 }
Alex Light53cb16b2014-06-12 11:26:29 -0700386 }
387 return true;
388}
389
390bool PatchOat::WriteElf(File* out) {
Alex Lighteefbe392014-07-08 09:53:18 -0700391 TimingLogger::ScopedTiming t("Writing Elf File", timings_);
Alex Lighta59dd802014-07-02 16:28:08 -0700392
Alex Light53cb16b2014-06-12 11:26:29 -0700393 CHECK(oat_file_.get() != nullptr);
394 CHECK(out != nullptr);
395 size_t expect = oat_file_->Size();
396 if (out->WriteFully(reinterpret_cast<char*>(oat_file_->Begin()), expect) &&
397 out->SetLength(expect) == 0) {
398 return true;
399 } else {
400 LOG(ERROR) << "Writing to oat file " << out->GetPath() << " failed.";
401 return false;
402 }
403}
404
405bool PatchOat::WriteImage(File* out) {
Alex Lighteefbe392014-07-08 09:53:18 -0700406 TimingLogger::ScopedTiming t("Writing image File", timings_);
Alex Lighta59dd802014-07-02 16:28:08 -0700407 std::string error_msg;
408
Alex Lightcf4bf382014-07-24 11:29:14 -0700409 ScopedFlock img_flock;
410 img_flock.Init(out, &error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -0700411
Alex Light53cb16b2014-06-12 11:26:29 -0700412 CHECK(image_ != nullptr);
413 CHECK(out != nullptr);
414 size_t expect = image_->Size();
415 if (out->WriteFully(reinterpret_cast<char*>(image_->Begin()), expect) &&
416 out->SetLength(expect) == 0) {
417 return true;
418 } else {
419 LOG(ERROR) << "Writing to image file " << out->GetPath() << " failed.";
420 return false;
421 }
422}
423
Igor Murashkin46774762014-10-22 11:37:02 -0700424bool PatchOat::IsImagePic(const ImageHeader& image_header, const std::string& image_path) {
425 if (!image_header.CompilePic()) {
426 if (kIsDebugBuild) {
427 LOG(INFO) << "image at location " << image_path << " was *not* compiled pic";
428 }
429 return false;
430 }
431
432 if (kIsDebugBuild) {
433 LOG(INFO) << "image at location " << image_path << " was compiled PIC";
434 }
435
436 return true;
437}
438
439PatchOat::MaybePic PatchOat::IsOatPic(const ElfFile* oat_in) {
440 if (oat_in == nullptr) {
441 LOG(ERROR) << "No ELF input oat fie available";
442 return ERROR_OAT_FILE;
443 }
444
445 const std::string& file_path = oat_in->GetFile().GetPath();
446
447 const OatHeader* oat_header = GetOatHeader(oat_in);
448 if (oat_header == nullptr) {
449 LOG(ERROR) << "Failed to find oat header in oat file " << file_path;
450 return ERROR_OAT_FILE;
451 }
452
453 if (!oat_header->IsValid()) {
454 LOG(ERROR) << "Elf file " << file_path << " has an invalid oat header";
455 return ERROR_OAT_FILE;
456 }
457
458 bool is_pic = oat_header->IsPic();
459 if (kIsDebugBuild) {
460 LOG(INFO) << "Oat file at " << file_path << " is " << (is_pic ? "PIC" : "not pic");
461 }
462
463 return is_pic ? PIC : NOT_PIC;
464}
465
466bool PatchOat::ReplaceOatFileWithSymlink(const std::string& input_oat_filename,
467 const std::string& output_oat_filename,
468 bool output_oat_opened_from_fd,
469 bool new_oat_out) {
470 // Need a file when we are PIC, since we symlink over it. Refusing to symlink into FD.
471 if (output_oat_opened_from_fd) {
472 // TODO: installd uses --output-oat-fd. Should we change class linking logic for PIC?
473 LOG(ERROR) << "No output oat filename specified, needs filename for when we are PIC";
474 return false;
475 }
476
477 // Image was PIC. Create symlink where the oat is supposed to go.
478 if (!new_oat_out) {
479 LOG(ERROR) << "Oat file " << output_oat_filename << " already exists, refusing to overwrite";
480 return false;
481 }
482
483 // Delete the original file, since we won't need it.
Dimitry Ivanov7a1c0142016-03-17 15:59:38 -0700484 unlink(output_oat_filename.c_str());
Igor Murashkin46774762014-10-22 11:37:02 -0700485
486 // Create a symlink from the old oat to the new oat
487 if (symlink(input_oat_filename.c_str(), output_oat_filename.c_str()) < 0) {
488 int err = errno;
489 LOG(ERROR) << "Failed to create symlink at " << output_oat_filename
490 << " error(" << err << "): " << strerror(err);
491 return false;
492 }
493
494 if (kIsDebugBuild) {
495 LOG(INFO) << "Created symlink " << output_oat_filename << " -> " << input_oat_filename;
496 }
497
498 return true;
499}
500
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700501class PatchOatArtFieldVisitor : public ArtFieldVisitor {
502 public:
503 explicit PatchOatArtFieldVisitor(PatchOat* patch_oat) : patch_oat_(patch_oat) {}
504
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700505 void Visit(ArtField* field) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700506 ArtField* const dest = patch_oat_->RelocatedCopyOf(field);
507 dest->SetDeclaringClass(patch_oat_->RelocatedAddressOfPointer(field->GetDeclaringClass()));
Mathieu Chartiere401d142015-04-22 13:56:20 -0700508 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700509
510 private:
511 PatchOat* const patch_oat_;
512};
513
514void PatchOat::PatchArtFields(const ImageHeader* image_header) {
515 PatchOatArtFieldVisitor visitor(this);
Mathieu Chartiere42888f2016-04-14 10:49:19 -0700516 image_header->VisitPackedArtFields(&visitor, heap_->Begin());
Mathieu Chartiere401d142015-04-22 13:56:20 -0700517}
518
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700519class PatchOatArtMethodVisitor : public ArtMethodVisitor {
520 public:
521 explicit PatchOatArtMethodVisitor(PatchOat* patch_oat) : patch_oat_(patch_oat) {}
522
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700523 void Visit(ArtMethod* method) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700524 ArtMethod* const dest = patch_oat_->RelocatedCopyOf(method);
525 patch_oat_->FixupMethod(method, dest);
526 }
527
528 private:
529 PatchOat* const patch_oat_;
530};
531
Mathieu Chartiere401d142015-04-22 13:56:20 -0700532void PatchOat::PatchArtMethods(const ImageHeader* image_header) {
Andreas Gampe542451c2016-07-26 09:02:02 -0700533 const PointerSize pointer_size = InstructionSetPointerSize(isa_);
Mathieu Chartier54d220e2015-07-30 16:20:06 -0700534 PatchOatArtMethodVisitor visitor(this);
Mathieu Chartiere42888f2016-04-14 10:49:19 -0700535 image_header->VisitPackedArtMethods(&visitor, heap_->Begin(), pointer_size);
536}
537
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +0000538void PatchOat::PatchImTables(const ImageHeader* image_header) {
Andreas Gampe542451c2016-07-26 09:02:02 -0700539 const PointerSize pointer_size = InstructionSetPointerSize(isa_);
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +0000540 // We can safely walk target image since the conflict tables are independent.
541 image_header->VisitPackedImTables(
542 [this](ArtMethod* method) {
543 return RelocatedAddressOfPointer(method);
544 },
545 image_->Begin(),
546 pointer_size);
547}
548
Mathieu Chartiere42888f2016-04-14 10:49:19 -0700549void PatchOat::PatchImtConflictTables(const ImageHeader* image_header) {
Andreas Gampe542451c2016-07-26 09:02:02 -0700550 const PointerSize pointer_size = InstructionSetPointerSize(isa_);
Mathieu Chartiere42888f2016-04-14 10:49:19 -0700551 // We can safely walk target image since the conflict tables are independent.
552 image_header->VisitPackedImtConflictTables(
553 [this](ArtMethod* method) {
554 return RelocatedAddressOfPointer(method);
555 },
556 image_->Begin(),
557 pointer_size);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700558}
559
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700560class FixupRootVisitor : public RootVisitor {
561 public:
562 explicit FixupRootVisitor(const PatchOat* patch_oat) : patch_oat_(patch_oat) {
563 }
564
565 void VisitRoots(mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700566 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700567 for (size_t i = 0; i < count; ++i) {
568 *roots[i] = patch_oat_->RelocatedAddressOfPointer(*roots[i]);
569 }
570 }
571
572 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots, size_t count,
573 const RootInfo& info ATTRIBUTE_UNUSED)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700574 OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700575 for (size_t i = 0; i < count; ++i) {
576 roots[i]->Assign(patch_oat_->RelocatedAddressOfPointer(roots[i]->AsMirrorPtr()));
577 }
578 }
579
580 private:
581 const PatchOat* const patch_oat_;
582};
583
584void PatchOat::PatchInternedStrings(const ImageHeader* image_header) {
585 const auto& section = image_header->GetImageSection(ImageHeader::kSectionInternedStrings);
586 InternTable temp_table;
587 // Note that we require that ReadFromMemory does not make an internal copy of the elements.
588 // This also relies on visit roots not doing any verification which could fail after we update
589 // the roots to be the image addresses.
Mathieu Chartierea0831f2015-12-29 13:17:37 -0800590 temp_table.AddTableFromMemory(image_->Begin() + section.Offset());
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700591 FixupRootVisitor visitor(this);
592 temp_table.VisitRoots(&visitor, kVisitRootFlagAllRoots);
593}
594
Mathieu Chartier208a5cb2015-12-02 15:44:07 -0800595void PatchOat::PatchClassTable(const ImageHeader* image_header) {
596 const auto& section = image_header->GetImageSection(ImageHeader::kSectionClassTable);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800597 if (section.Size() == 0) {
598 return;
599 }
Mathieu Chartier208a5cb2015-12-02 15:44:07 -0800600 // Note that we require that ReadFromMemory does not make an internal copy of the elements.
601 // This also relies on visit roots not doing any verification which could fail after we update
602 // the roots to be the image addresses.
603 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
604 ClassTable temp_table;
605 temp_table.ReadFromMemory(image_->Begin() + section.Offset());
606 FixupRootVisitor visitor(this);
607 BufferedRootVisitor<kDefaultBufferedRootCount> buffered_visitor(&visitor, RootInfo(kRootUnknown));
608 temp_table.VisitRoots(buffered_visitor);
609}
610
611
Mathieu Chartier4b00d342015-11-13 10:42:08 -0800612class RelocatedPointerVisitor {
613 public:
614 explicit RelocatedPointerVisitor(PatchOat* patch_oat) : patch_oat_(patch_oat) {}
615
616 template <typename T>
617 T* operator()(T* ptr) const {
618 return patch_oat_->RelocatedAddressOfPointer(ptr);
619 }
620
621 private:
622 PatchOat* const patch_oat_;
623};
624
Mathieu Chartierc7853442015-03-27 14:35:38 -0700625void PatchOat::PatchDexFileArrays(mirror::ObjectArray<mirror::Object>* img_roots) {
626 auto* dex_caches = down_cast<mirror::ObjectArray<mirror::DexCache>*>(
627 img_roots->Get(ImageHeader::kDexCaches));
Andreas Gampe542451c2016-07-26 09:02:02 -0700628 const PointerSize pointer_size = InstructionSetPointerSize(isa_);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700629 for (size_t i = 0, count = dex_caches->GetLength(); i < count; ++i) {
Vladimir Marko05792b92015-08-03 11:56:49 +0100630 auto* orig_dex_cache = dex_caches->GetWithoutChecks(i);
631 auto* copy_dex_cache = RelocatedCopyOf(orig_dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +0100632 // Though the DexCache array fields are usually treated as native pointers, we set the full
633 // 64-bit values here, clearing the top 32 bits for 32-bit targets. The zero-extension is
634 // done by casting to the unsigned type uintptr_t before casting to int64_t, i.e.
635 // static_cast<int64_t>(reinterpret_cast<uintptr_t>(image_begin_ + offset))).
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -0700636 mirror::StringDexCacheType* orig_strings = orig_dex_cache->GetStrings();
637 mirror::StringDexCacheType* relocated_strings = RelocatedAddressOfPointer(orig_strings);
Vladimir Marko05792b92015-08-03 11:56:49 +0100638 copy_dex_cache->SetField64<false>(
639 mirror::DexCache::StringsOffset(),
640 static_cast<int64_t>(reinterpret_cast<uintptr_t>(relocated_strings)));
641 if (orig_strings != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -0800642 orig_dex_cache->FixupStrings(RelocatedCopyOf(orig_strings), RelocatedPointerVisitor(this));
Mathieu Chartierc7853442015-03-27 14:35:38 -0700643 }
Vladimir Marko05792b92015-08-03 11:56:49 +0100644 GcRoot<mirror::Class>* orig_types = orig_dex_cache->GetResolvedTypes();
645 GcRoot<mirror::Class>* relocated_types = RelocatedAddressOfPointer(orig_types);
646 copy_dex_cache->SetField64<false>(
647 mirror::DexCache::ResolvedTypesOffset(),
648 static_cast<int64_t>(reinterpret_cast<uintptr_t>(relocated_types)));
649 if (orig_types != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -0800650 orig_dex_cache->FixupResolvedTypes(RelocatedCopyOf(orig_types),
651 RelocatedPointerVisitor(this));
Vladimir Marko05792b92015-08-03 11:56:49 +0100652 }
653 ArtMethod** orig_methods = orig_dex_cache->GetResolvedMethods();
654 ArtMethod** relocated_methods = RelocatedAddressOfPointer(orig_methods);
655 copy_dex_cache->SetField64<false>(
656 mirror::DexCache::ResolvedMethodsOffset(),
657 static_cast<int64_t>(reinterpret_cast<uintptr_t>(relocated_methods)));
658 if (orig_methods != nullptr) {
659 ArtMethod** copy_methods = RelocatedCopyOf(orig_methods);
660 for (size_t j = 0, num = orig_dex_cache->NumResolvedMethods(); j != num; ++j) {
661 ArtMethod* orig = mirror::DexCache::GetElementPtrSize(orig_methods, j, pointer_size);
662 ArtMethod* copy = RelocatedAddressOfPointer(orig);
663 mirror::DexCache::SetElementPtrSize(copy_methods, j, copy, pointer_size);
664 }
665 }
666 ArtField** orig_fields = orig_dex_cache->GetResolvedFields();
667 ArtField** relocated_fields = RelocatedAddressOfPointer(orig_fields);
668 copy_dex_cache->SetField64<false>(
669 mirror::DexCache::ResolvedFieldsOffset(),
670 static_cast<int64_t>(reinterpret_cast<uintptr_t>(relocated_fields)));
671 if (orig_fields != nullptr) {
672 ArtField** copy_fields = RelocatedCopyOf(orig_fields);
673 for (size_t j = 0, num = orig_dex_cache->NumResolvedFields(); j != num; ++j) {
674 ArtField* orig = mirror::DexCache::GetElementPtrSize(orig_fields, j, pointer_size);
675 ArtField* copy = RelocatedAddressOfPointer(orig);
676 mirror::DexCache::SetElementPtrSize(copy_fields, j, copy, pointer_size);
677 }
Mathieu Chartiere401d142015-04-22 13:56:20 -0700678 }
679 }
680}
681
Jeff Haodcdc85b2015-12-04 14:06:18 -0800682bool PatchOat::PatchImage(bool primary_image) {
Alex Light53cb16b2014-06-12 11:26:29 -0700683 ImageHeader* image_header = reinterpret_cast<ImageHeader*>(image_->Begin());
684 CHECK_GT(image_->Size(), sizeof(ImageHeader));
685 // These are the roots from the original file.
Mathieu Chartierc7853442015-03-27 14:35:38 -0700686 auto* img_roots = image_header->GetImageRoots();
Alex Light53cb16b2014-06-12 11:26:29 -0700687 image_header->RelocateImage(delta_);
688
Mathieu Chartierc7853442015-03-27 14:35:38 -0700689 PatchArtFields(image_header);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700690 PatchArtMethods(image_header);
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +0000691 PatchImTables(image_header);
Mathieu Chartiere42888f2016-04-14 10:49:19 -0700692 PatchImtConflictTables(image_header);
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700693 PatchInternedStrings(image_header);
Mathieu Chartier208a5cb2015-12-02 15:44:07 -0800694 PatchClassTable(image_header);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700695 // Patch dex file int/long arrays which point to ArtFields.
696 PatchDexFileArrays(img_roots);
697
Jeff Haodcdc85b2015-12-04 14:06:18 -0800698 if (primary_image) {
699 VisitObject(img_roots);
700 }
701
Alex Light53cb16b2014-06-12 11:26:29 -0700702 if (!image_header->IsValid()) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800703 LOG(ERROR) << "relocation renders image header invalid";
Alex Light53cb16b2014-06-12 11:26:29 -0700704 return false;
705 }
706
707 {
Alex Lighteefbe392014-07-08 09:53:18 -0700708 TimingLogger::ScopedTiming t("Walk Bitmap", timings_);
Alex Light53cb16b2014-06-12 11:26:29 -0700709 // Walk the bitmap.
710 WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
711 bitmap_->Walk(PatchOat::BitmapCallback, this);
712 }
713 return true;
714}
715
Alex Light53cb16b2014-06-12 11:26:29 -0700716
717void PatchOat::PatchVisitor::operator() (mirror::Object* obj, MemberOffset off,
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700718 bool is_static_unused ATTRIBUTE_UNUSED) const {
Alex Light53cb16b2014-06-12 11:26:29 -0700719 mirror::Object* referent = obj->GetFieldObject<mirror::Object, kVerifyNone>(off);
Mathieu Chartierc7853442015-03-27 14:35:38 -0700720 mirror::Object* moved_object = patcher_->RelocatedAddressOfPointer(referent);
Alex Light53cb16b2014-06-12 11:26:29 -0700721 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(off, moved_object);
722}
723
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700724void PatchOat::PatchVisitor::operator() (mirror::Class* cls ATTRIBUTE_UNUSED,
725 mirror::Reference* ref) const {
Alex Light53cb16b2014-06-12 11:26:29 -0700726 MemberOffset off = mirror::Reference::ReferentOffset();
727 mirror::Object* referent = ref->GetReferent();
Mathieu Chartiera13abba2016-04-21 10:23:16 -0700728 DCHECK(referent == nullptr ||
729 Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(referent)) << referent;
Mathieu Chartierc7853442015-03-27 14:35:38 -0700730 mirror::Object* moved_object = patcher_->RelocatedAddressOfPointer(referent);
Alex Light53cb16b2014-06-12 11:26:29 -0700731 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(off, moved_object);
732}
733
Alex Light53cb16b2014-06-12 11:26:29 -0700734// Called by BitmapCallback
735void PatchOat::VisitObject(mirror::Object* object) {
736 mirror::Object* copy = RelocatedCopyOf(object);
737 CHECK(copy != nullptr);
738 if (kUseBakerOrBrooksReadBarrier) {
739 object->AssertReadBarrierPointer();
740 if (kUseBrooksReadBarrier) {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700741 mirror::Object* moved_to = RelocatedAddressOfPointer(object);
Alex Light53cb16b2014-06-12 11:26:29 -0700742 copy->SetReadBarrierPointer(moved_to);
743 DCHECK_EQ(copy->GetReadBarrierPointer(), moved_to);
744 }
745 }
746 PatchOat::PatchVisitor visitor(this, copy);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -0700747 object->VisitReferences<kVerifyNone>(visitor, visitor);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700748 if (object->IsClass<kVerifyNone>()) {
Andreas Gampe542451c2016-07-26 09:02:02 -0700749 const PointerSize pointer_size = InstructionSetPointerSize(isa_);
Mathieu Chartier4b00d342015-11-13 10:42:08 -0800750 mirror::Class* klass = object->AsClass();
751 mirror::Class* copy_klass = down_cast<mirror::Class*>(copy);
752 RelocatedPointerVisitor native_visitor(this);
753 klass->FixupNativePointers(copy_klass, pointer_size, native_visitor);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700754 auto* vtable = klass->GetVTable();
755 if (vtable != nullptr) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800756 vtable->Fixup(RelocatedCopyOfFollowImages(vtable), pointer_size, native_visitor);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700757 }
758 auto* iftable = klass->GetIfTable();
759 if (iftable != nullptr) {
760 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
761 if (iftable->GetMethodArrayCount(i) > 0) {
762 auto* method_array = iftable->GetMethodArray(i);
763 CHECK(method_array != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800764 method_array->Fixup(RelocatedCopyOfFollowImages(method_array),
765 pointer_size,
766 native_visitor);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700767 }
768 }
769 }
Mathieu Chartier4b00d342015-11-13 10:42:08 -0800770 } else if (object->GetClass() == mirror::Method::StaticClass() ||
771 object->GetClass() == mirror::Constructor::StaticClass()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700772 // Need to go update the ArtMethod.
Neil Fuller0e844392016-09-08 13:43:31 +0100773 auto* dest = down_cast<mirror::Executable*>(copy);
774 auto* src = down_cast<mirror::Executable*>(object);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700775 dest->SetArtMethod(RelocatedAddressOfPointer(src->GetArtMethod()));
Alex Light53cb16b2014-06-12 11:26:29 -0700776 }
777}
778
Mathieu Chartiere401d142015-04-22 13:56:20 -0700779void PatchOat::FixupMethod(ArtMethod* object, ArtMethod* copy) {
Andreas Gampe542451c2016-07-26 09:02:02 -0700780 const PointerSize pointer_size = InstructionSetPointerSize(isa_);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700781 copy->CopyFrom(object, pointer_size);
Alex Light53cb16b2014-06-12 11:26:29 -0700782 // Just update the entry points if it looks like we should.
Alex Lighteefbe392014-07-08 09:53:18 -0700783 // TODO: sanity check all the pointers' values
Mathieu Chartiere401d142015-04-22 13:56:20 -0700784 copy->SetDeclaringClass(RelocatedAddressOfPointer(object->GetDeclaringClass()));
Vladimir Marko05792b92015-08-03 11:56:49 +0100785 copy->SetDexCacheResolvedMethods(
786 RelocatedAddressOfPointer(object->GetDexCacheResolvedMethods(pointer_size)), pointer_size);
787 copy->SetDexCacheResolvedTypes(
788 RelocatedAddressOfPointer(object->GetDexCacheResolvedTypes(pointer_size)), pointer_size);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700789 copy->SetEntryPointFromQuickCompiledCodePtrSize(RelocatedAddressOfPointer(
790 object->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size)), pointer_size);
Mathieu Chartiere42888f2016-04-14 10:49:19 -0700791 // No special handling for IMT conflict table since all pointers are moved by the same offset.
Andreas Gampe75f08852016-07-19 08:06:07 -0700792 copy->SetDataPtrSize(RelocatedAddressOfPointer(
793 object->GetDataPtrSize(pointer_size)), pointer_size);
Alex Light53cb16b2014-06-12 11:26:29 -0700794}
795
Igor Murashkin46774762014-10-22 11:37:02 -0700796bool PatchOat::Patch(File* input_oat, off_t delta, File* output_oat, TimingLogger* timings,
797 bool output_oat_opened_from_fd, bool new_oat_out) {
Alex Light53cb16b2014-06-12 11:26:29 -0700798 CHECK(input_oat != nullptr);
799 CHECK(output_oat != nullptr);
800 CHECK_GE(input_oat->Fd(), 0);
801 CHECK_GE(output_oat->Fd(), 0);
Alex Lighteefbe392014-07-08 09:53:18 -0700802 TimingLogger::ScopedTiming t("Setup Oat File Patching", timings);
Alex Light53cb16b2014-06-12 11:26:29 -0700803
804 std::string error_msg;
Igor Murashkin46774762014-10-22 11:37:02 -0700805 std::unique_ptr<ElfFile> elf(ElfFile::Open(input_oat,
Alex Light53cb16b2014-06-12 11:26:29 -0700806 PROT_READ | PROT_WRITE, MAP_PRIVATE, &error_msg));
807 if (elf.get() == nullptr) {
808 LOG(ERROR) << "unable to open oat file " << input_oat->GetPath() << " : " << error_msg;
809 return false;
810 }
811
Igor Murashkin46774762014-10-22 11:37:02 -0700812 MaybePic is_oat_pic = IsOatPic(elf.get());
813 if (is_oat_pic >= ERROR_FIRST) {
814 // Error logged by IsOatPic
815 return false;
816 } else if (is_oat_pic == PIC) {
817 // Do not need to do ELF-file patching. Create a symlink and skip the rest.
818 // Any errors will be logged by the function call.
819 return ReplaceOatFileWithSymlink(input_oat->GetPath(),
820 output_oat->GetPath(),
821 output_oat_opened_from_fd,
822 new_oat_out);
823 } else {
824 CHECK(is_oat_pic == NOT_PIC);
825 }
826
Alex Light53cb16b2014-06-12 11:26:29 -0700827 PatchOat p(elf.release(), delta, timings);
828 t.NewTiming("Patch Oat file");
829 if (!p.PatchElf()) {
830 return false;
831 }
832
833 t.NewTiming("Writing oat file");
834 if (!p.WriteElf(output_oat)) {
835 return false;
836 }
837 return true;
838}
839
Tong Shen62d1ca32014-09-03 17:24:56 -0700840template <typename ElfFileImpl>
841bool PatchOat::PatchOatHeader(ElfFileImpl* oat_file) {
842 auto rodata_sec = oat_file->FindSectionByName(".rodata");
Alex Lighta59dd802014-07-02 16:28:08 -0700843 if (rodata_sec == nullptr) {
844 return false;
845 }
Tong Shen62d1ca32014-09-03 17:24:56 -0700846 OatHeader* oat_header = reinterpret_cast<OatHeader*>(oat_file->Begin() + rodata_sec->sh_offset);
Alex Lighta59dd802014-07-02 16:28:08 -0700847 if (!oat_header->IsValid()) {
Tong Shen62d1ca32014-09-03 17:24:56 -0700848 LOG(ERROR) << "Elf file " << oat_file->GetFile().GetPath() << " has an invalid oat header";
Alex Lighta59dd802014-07-02 16:28:08 -0700849 return false;
850 }
851 oat_header->RelocateOat(delta_);
852 return true;
853}
854
Alex Light53cb16b2014-06-12 11:26:29 -0700855bool PatchOat::PatchElf() {
Ian Rogersd4c4d952014-10-16 20:31:53 -0700856 if (oat_file_->Is64Bit())
Tong Shen62d1ca32014-09-03 17:24:56 -0700857 return PatchElf<ElfFileImpl64>(oat_file_->GetImpl64());
858 else
859 return PatchElf<ElfFileImpl32>(oat_file_->GetImpl32());
860}
861
862template <typename ElfFileImpl>
863bool PatchOat::PatchElf(ElfFileImpl* oat_file) {
Alex Lighta59dd802014-07-02 16:28:08 -0700864 TimingLogger::ScopedTiming t("Fixup Elf Text Section", timings_);
Vladimir Marko3fc99032015-05-13 19:06:30 +0100865
866 // Fix up absolute references to locations within the boot image.
David Srbecky2f6cdb02015-04-11 00:17:53 +0100867 if (!oat_file->ApplyOatPatchesTo(".text", delta_)) {
Alex Lighta59dd802014-07-02 16:28:08 -0700868 return false;
869 }
870
Vladimir Marko3fc99032015-05-13 19:06:30 +0100871 // Update the OatHeader fields referencing the boot image.
Tong Shen62d1ca32014-09-03 17:24:56 -0700872 if (!PatchOatHeader<ElfFileImpl>(oat_file)) {
Alex Lighta59dd802014-07-02 16:28:08 -0700873 return false;
874 }
875
Vladimir Marko3fc99032015-05-13 19:06:30 +0100876 bool need_boot_oat_fixup = true;
Ian Rogersd4c4d952014-10-16 20:31:53 -0700877 for (unsigned int i = 0; i < oat_file->GetProgramHeaderNum(); ++i) {
Tong Shen62d1ca32014-09-03 17:24:56 -0700878 auto hdr = oat_file->GetProgramHeader(i);
Vladimir Marko3fc99032015-05-13 19:06:30 +0100879 if (hdr->p_type == PT_LOAD && hdr->p_vaddr == 0u) {
880 need_boot_oat_fixup = false;
Ian Rogersd4c4d952014-10-16 20:31:53 -0700881 break;
Alex Light53cb16b2014-06-12 11:26:29 -0700882 }
883 }
Vladimir Marko3fc99032015-05-13 19:06:30 +0100884 if (!need_boot_oat_fixup) {
885 // This is an app oat file that can be loaded at an arbitrary address in memory.
886 // Boot image references were patched above and there's nothing else to do.
Alex Lighta59dd802014-07-02 16:28:08 -0700887 return true;
888 }
Tong Shen62d1ca32014-09-03 17:24:56 -0700889
Vladimir Marko3fc99032015-05-13 19:06:30 +0100890 // This is a boot oat file that's loaded at a particular address and we need
891 // to patch all absolute addresses, starting with ELF program headers.
892
Tong Shen62d1ca32014-09-03 17:24:56 -0700893 t.NewTiming("Fixup Elf Headers");
894 // Fixup Phdr's
895 oat_file->FixupProgramHeaders(delta_);
896
Alex Lighta59dd802014-07-02 16:28:08 -0700897 t.NewTiming("Fixup Section Headers");
Tong Shen62d1ca32014-09-03 17:24:56 -0700898 // Fixup Shdr's
899 oat_file->FixupSectionHeaders(delta_);
Alex Light53cb16b2014-06-12 11:26:29 -0700900
Alex Lighta59dd802014-07-02 16:28:08 -0700901 t.NewTiming("Fixup Dynamics");
Tong Shen62d1ca32014-09-03 17:24:56 -0700902 oat_file->FixupDynamic(delta_);
Alex Light53cb16b2014-06-12 11:26:29 -0700903
904 t.NewTiming("Fixup Elf Symbols");
905 // Fixup dynsym
Tong Shen62d1ca32014-09-03 17:24:56 -0700906 if (!oat_file->FixupSymbols(delta_, true)) {
Alex Light53cb16b2014-06-12 11:26:29 -0700907 return false;
908 }
Alex Light53cb16b2014-06-12 11:26:29 -0700909 // Fixup symtab
Tong Shen62d1ca32014-09-03 17:24:56 -0700910 if (!oat_file->FixupSymbols(delta_, false)) {
911 return false;
Alex Light53cb16b2014-06-12 11:26:29 -0700912 }
913
Yevgeny Roubane3ea8382014-08-08 16:29:38 +0700914 t.NewTiming("Fixup Debug Sections");
Tong Shen62d1ca32014-09-03 17:24:56 -0700915 if (!oat_file->FixupDebugSections(delta_)) {
Yevgeny Roubane3ea8382014-08-08 16:29:38 +0700916 return false;
917 }
918
Alex Light53cb16b2014-06-12 11:26:29 -0700919 return true;
920}
921
Alex Light53cb16b2014-06-12 11:26:29 -0700922static int orig_argc;
923static char** orig_argv;
924
925static std::string CommandLine() {
926 std::vector<std::string> command;
927 for (int i = 0; i < orig_argc; ++i) {
928 command.push_back(orig_argv[i]);
929 }
930 return Join(command, ' ');
931}
932
933static void UsageErrorV(const char* fmt, va_list ap) {
934 std::string error;
935 StringAppendV(&error, fmt, ap);
936 LOG(ERROR) << error;
937}
938
939static void UsageError(const char* fmt, ...) {
940 va_list ap;
941 va_start(ap, fmt);
942 UsageErrorV(fmt, ap);
943 va_end(ap);
944}
945
Andreas Gampe794ad762015-02-23 08:12:24 -0800946NO_RETURN static void Usage(const char *fmt, ...) {
Alex Light53cb16b2014-06-12 11:26:29 -0700947 va_list ap;
948 va_start(ap, fmt);
949 UsageErrorV(fmt, ap);
950 va_end(ap);
951
952 UsageError("Command: %s", CommandLine().c_str());
953 UsageError("Usage: patchoat [options]...");
954 UsageError("");
955 UsageError(" --instruction-set=<isa>: Specifies the instruction set the patched code is");
956 UsageError(" compiled for. Required if you use --input-oat-location");
957 UsageError("");
958 UsageError(" --input-oat-file=<file.oat>: Specifies the exact filename of the oat file to be");
959 UsageError(" patched.");
960 UsageError("");
961 UsageError(" --input-oat-fd=<file-descriptor>: Specifies the file-descriptor of the oat file");
962 UsageError(" to be patched.");
963 UsageError("");
David Brazdil7b49e6c2016-09-01 11:06:18 +0100964 UsageError(" --input-vdex-fd=<file-descriptor>: Specifies the file-descriptor of the vdex file");
965 UsageError(" associated with the oat file.");
966 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700967 UsageError(" --input-oat-location=<file.oat>: Specifies the 'location' to read the patched");
968 UsageError(" oat file from. If used one must also supply the --instruction-set");
969 UsageError("");
970 UsageError(" --input-image-location=<file.art>: Specifies the 'location' of the image file to");
971 UsageError(" be patched. If --instruction-set is not given it will use the instruction set");
972 UsageError(" extracted from the --input-oat-file.");
973 UsageError("");
974 UsageError(" --output-oat-file=<file.oat>: Specifies the exact file to write the patched oat");
975 UsageError(" file to.");
976 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700977 UsageError(" --output-oat-fd=<file-descriptor>: Specifies the file-descriptor to write the");
David Brazdil7b49e6c2016-09-01 11:06:18 +0100978 UsageError(" patched oat file to.");
979 UsageError("");
980 UsageError(" --output-vdex-fd=<file-descriptor>: Specifies the file-descriptor to copy the");
981 UsageError(" the vdex file associated with the patch oat file to.");
Alex Light53cb16b2014-06-12 11:26:29 -0700982 UsageError("");
983 UsageError(" --output-image-file=<file.art>: Specifies the exact file to write the patched");
984 UsageError(" image file to.");
985 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700986 UsageError(" --base-offset-delta=<delta>: Specify the amount to change the old base-offset by.");
987 UsageError(" This value may be negative.");
988 UsageError("");
Alex Light0eb76d22015-08-11 18:03:47 -0700989 UsageError(" --patched-image-location=<file.art>: Relocate the oat file to be the same as the");
990 UsageError(" image at the given location. If used one must also specify the");
Alex Lighta59dd802014-07-02 16:28:08 -0700991 UsageError(" --instruction-set flag. It will search for this image in the same way that");
992 UsageError(" is done when loading one.");
Alex Light53cb16b2014-06-12 11:26:29 -0700993 UsageError("");
Alex Lightcf4bf382014-07-24 11:29:14 -0700994 UsageError(" --lock-output: Obtain a flock on output oat file before starting.");
995 UsageError("");
996 UsageError(" --no-lock-output: Do not attempt to obtain a flock on output oat file.");
997 UsageError("");
Alex Light53cb16b2014-06-12 11:26:29 -0700998 UsageError(" --dump-timings: dump out patch timing information");
999 UsageError("");
1000 UsageError(" --no-dump-timings: do not dump out patch timing information");
1001 UsageError("");
1002
1003 exit(EXIT_FAILURE);
1004}
1005
Alex Lighteefbe392014-07-08 09:53:18 -07001006static bool ReadBaseDelta(const char* name, off_t* delta, std::string* error_msg) {
Alex Light53cb16b2014-06-12 11:26:29 -07001007 CHECK(name != nullptr);
1008 CHECK(delta != nullptr);
1009 std::unique_ptr<File> file;
1010 if (OS::FileExists(name)) {
1011 file.reset(OS::OpenFileForReading(name));
1012 if (file.get() == nullptr) {
Alex Lighteefbe392014-07-08 09:53:18 -07001013 *error_msg = "Failed to open file %s for reading";
Alex Light53cb16b2014-06-12 11:26:29 -07001014 return false;
1015 }
1016 } else {
Alex Lighteefbe392014-07-08 09:53:18 -07001017 *error_msg = "File %s does not exist";
Alex Light53cb16b2014-06-12 11:26:29 -07001018 return false;
1019 }
1020 CHECK(file.get() != nullptr);
1021 ImageHeader hdr;
1022 if (sizeof(hdr) != file->Read(reinterpret_cast<char*>(&hdr), sizeof(hdr), 0)) {
Alex Lighteefbe392014-07-08 09:53:18 -07001023 *error_msg = "Failed to read file %s";
Alex Light53cb16b2014-06-12 11:26:29 -07001024 return false;
1025 }
1026 if (!hdr.IsValid()) {
Alex Lighteefbe392014-07-08 09:53:18 -07001027 *error_msg = "%s does not contain a valid image header.";
Alex Light53cb16b2014-06-12 11:26:29 -07001028 return false;
1029 }
1030 *delta = hdr.GetPatchDelta();
1031 return true;
1032}
1033
Andreas Gampe6eb6a392016-02-10 20:18:37 -08001034static int patchoat_image(TimingLogger& timings,
1035 InstructionSet isa,
1036 const std::string& input_image_location,
1037 const std::string& output_image_filename,
1038 off_t base_delta,
1039 bool base_delta_set,
1040 bool debug) {
1041 CHECK(!input_image_location.empty());
1042 if (output_image_filename.empty()) {
1043 Usage("Image patching requires --output-image-file");
1044 }
1045
1046 if (!base_delta_set) {
1047 Usage("Must supply a desired new offset or delta.");
1048 }
1049
1050 if (!IsAligned<kPageSize>(base_delta)) {
1051 Usage("Base offset/delta must be aligned to a pagesize (0x%08x) boundary.", kPageSize);
1052 }
1053
1054 if (debug) {
1055 LOG(INFO) << "moving offset by " << base_delta
1056 << " (0x" << std::hex << base_delta << ") bytes or "
1057 << std::dec << (base_delta/kPageSize) << " pages.";
1058 }
1059
1060 TimingLogger::ScopedTiming pt("patch image and oat", &timings);
1061
1062 std::string output_directory =
1063 output_image_filename.substr(0, output_image_filename.find_last_of("/"));
1064 bool ret = PatchOat::Patch(input_image_location, base_delta, output_directory, isa, &timings);
1065
1066 if (kIsDebugBuild) {
1067 LOG(INFO) << "Exiting with return ... " << ret;
1068 }
1069 return ret ? EXIT_SUCCESS : EXIT_FAILURE;
1070}
1071
1072static int patchoat_oat(TimingLogger& timings,
1073 InstructionSet isa,
1074 const std::string& patched_image_location,
1075 off_t base_delta,
1076 bool base_delta_set,
1077 int input_oat_fd,
David Brazdil7b49e6c2016-09-01 11:06:18 +01001078 int input_vdex_fd,
Andreas Gampe6eb6a392016-02-10 20:18:37 -08001079 const std::string& input_oat_location,
1080 std::string input_oat_filename,
1081 bool have_input_oat,
1082 int output_oat_fd,
David Brazdil7b49e6c2016-09-01 11:06:18 +01001083 int output_vdex_fd,
Andreas Gampe6eb6a392016-02-10 20:18:37 -08001084 std::string output_oat_filename,
1085 bool have_output_oat,
1086 bool lock_output,
1087 bool debug) {
1088 {
1089 // Only 1 of these may be set.
1090 uint32_t cnt = 0;
1091 cnt += (base_delta_set) ? 1 : 0;
1092 cnt += (!patched_image_location.empty()) ? 1 : 0;
1093 if (cnt > 1) {
1094 Usage("Only one of --base-offset-delta or --patched-image-location may be used.");
1095 } else if (cnt == 0) {
1096 Usage("Must specify --base-offset-delta or --patched-image-location.");
1097 }
1098 }
1099
1100 if (!have_input_oat || !have_output_oat) {
1101 Usage("Both input and output oat must be supplied to patch an app odex.");
1102 }
1103
1104 if (!input_oat_location.empty()) {
1105 if (!LocationToFilename(input_oat_location, isa, &input_oat_filename)) {
1106 Usage("Unable to find filename for input oat location %s", input_oat_location.c_str());
1107 }
1108 if (debug) {
1109 LOG(INFO) << "Using input-oat-file " << input_oat_filename;
1110 }
1111 }
1112
David Brazdil7b49e6c2016-09-01 11:06:18 +01001113 if ((input_oat_fd == -1) != (input_vdex_fd == -1)) {
1114 Usage("Either both input oat and vdex have to be passed as file descriptors or none of them");
1115 } else if ((output_oat_fd == -1) != (output_vdex_fd == -1)) {
1116 Usage("Either both output oat and vdex have to be passed as file descriptors or none of them");
1117 }
1118
Andreas Gampe6eb6a392016-02-10 20:18:37 -08001119 bool match_delta = false;
1120 if (!patched_image_location.empty()) {
1121 std::string system_filename;
1122 bool has_system = false;
1123 std::string cache_filename;
1124 bool has_cache = false;
1125 bool has_android_data_unused = false;
1126 bool is_global_cache = false;
1127 if (!gc::space::ImageSpace::FindImageFilename(patched_image_location.c_str(), isa,
1128 &system_filename, &has_system, &cache_filename,
1129 &has_android_data_unused, &has_cache,
1130 &is_global_cache)) {
1131 Usage("Unable to determine image file for location %s", patched_image_location.c_str());
1132 }
1133 std::string patched_image_filename;
1134 if (has_cache) {
1135 patched_image_filename = cache_filename;
1136 } else if (has_system) {
1137 LOG(WARNING) << "Only image file found was in /system for image location "
1138 << patched_image_location;
1139 patched_image_filename = system_filename;
1140 } else {
1141 Usage("Unable to determine image file for location %s", patched_image_location.c_str());
1142 }
1143 if (debug) {
1144 LOG(INFO) << "Using patched-image-file " << patched_image_filename;
1145 }
1146
1147 base_delta_set = true;
1148 match_delta = true;
1149 std::string error_msg;
1150 if (!ReadBaseDelta(patched_image_filename.c_str(), &base_delta, &error_msg)) {
1151 Usage(error_msg.c_str(), patched_image_filename.c_str());
1152 }
1153 }
1154
1155 if (!IsAligned<kPageSize>(base_delta)) {
1156 Usage("Base offset/delta must be alligned to a pagesize (0x%08x) boundary.", kPageSize);
1157 }
1158
David Brazdil7b49e6c2016-09-01 11:06:18 +01001159 // We can symlink VDEX only if we have both input and output specified as filenames.
1160 // Store that piece of information before we possibly create bogus filenames for
1161 // files passed as file descriptors.
1162 bool symlink_vdex = !input_oat_filename.empty() && !output_oat_filename.empty();
1163
1164 // Infer names of VDEX files.
1165 std::string input_vdex_filename;
1166 std::string output_vdex_filename;
1167 if (!input_oat_filename.empty()) {
1168 input_vdex_filename = ReplaceFileExtension(input_oat_filename, "vdex");
1169 }
1170 if (!output_oat_filename.empty()) {
1171 output_vdex_filename = ReplaceFileExtension(output_oat_filename, "vdex");
1172 }
1173
Andreas Gampe6eb6a392016-02-10 20:18:37 -08001174 // Do we need to cleanup output files if we fail?
1175 bool new_oat_out = false;
David Brazdil7b49e6c2016-09-01 11:06:18 +01001176 bool new_vdex_out = false;
Andreas Gampe6eb6a392016-02-10 20:18:37 -08001177
1178 std::unique_ptr<File> input_oat;
1179 std::unique_ptr<File> output_oat;
1180
1181 if (input_oat_fd != -1) {
1182 if (input_oat_filename.empty()) {
1183 input_oat_filename = "input-oat-file";
1184 }
1185 input_oat.reset(new File(input_oat_fd, input_oat_filename, false));
1186 if (input_oat_fd == output_oat_fd) {
1187 input_oat.get()->DisableAutoClose();
1188 }
1189 if (input_oat == nullptr) {
1190 // Unlikely, but ensure exhaustive logging in non-0 exit code case
1191 LOG(ERROR) << "Failed to open input oat file by its FD" << input_oat_fd;
Jeff Haoec1514a2016-03-17 21:32:45 -07001192 return EXIT_FAILURE;
Andreas Gampe6eb6a392016-02-10 20:18:37 -08001193 }
1194 } else {
1195 CHECK(!input_oat_filename.empty());
1196 input_oat.reset(OS::OpenFileForReading(input_oat_filename.c_str()));
1197 if (input_oat == nullptr) {
1198 int err = errno;
1199 LOG(ERROR) << "Failed to open input oat file " << input_oat_filename
1200 << ": " << strerror(err) << "(" << err << ")";
Jeff Haoec1514a2016-03-17 21:32:45 -07001201 return EXIT_FAILURE;
Andreas Gampe6eb6a392016-02-10 20:18:37 -08001202 }
1203 }
1204
Jeff Haoec1514a2016-03-17 21:32:45 -07001205 std::string error_msg;
1206 std::unique_ptr<ElfFile> elf(ElfFile::Open(input_oat.get(), PROT_READ, MAP_PRIVATE, &error_msg));
1207 if (elf.get() == nullptr) {
1208 LOG(ERROR) << "unable to open oat file " << input_oat->GetPath() << " : " << error_msg;
1209 return EXIT_FAILURE;
1210 }
1211 if (!elf->HasSection(".text.oat_patches")) {
1212 LOG(ERROR) << "missing oat patch section in input oat file " << input_oat->GetPath();
1213 return EXIT_FAILURE;
1214 }
1215
Andreas Gampe6eb6a392016-02-10 20:18:37 -08001216 if (output_oat_fd != -1) {
1217 if (output_oat_filename.empty()) {
1218 output_oat_filename = "output-oat-file";
1219 }
1220 output_oat.reset(new File(output_oat_fd, output_oat_filename, true));
1221 if (output_oat == nullptr) {
1222 // Unlikely, but ensure exhaustive logging in non-0 exit code case
1223 LOG(ERROR) << "Failed to open output oat file by its FD" << output_oat_fd;
1224 }
1225 } else {
1226 CHECK(!output_oat_filename.empty());
1227 output_oat.reset(CreateOrOpen(output_oat_filename.c_str(), &new_oat_out));
1228 if (output_oat == nullptr) {
1229 int err = errno;
1230 LOG(ERROR) << "Failed to open output oat file " << output_oat_filename
1231 << ": " << strerror(err) << "(" << err << ")";
1232 }
1233 }
1234
David Brazdil7b49e6c2016-09-01 11:06:18 +01001235 // Open VDEX files if we are not symlinking them.
1236 std::unique_ptr<File> input_vdex;
1237 std::unique_ptr<File> output_vdex;
1238 if (symlink_vdex) {
1239 new_vdex_out = !OS::FileExists(output_vdex_filename.c_str());
1240 } else {
1241 if (input_vdex_fd != -1) {
1242 input_vdex.reset(new File(input_vdex_fd, input_vdex_filename, true));
1243 if (input_vdex == nullptr) {
1244 // Unlikely, but ensure exhaustive logging in non-0 exit code case
1245 LOG(ERROR) << "Failed to open input vdex file by its FD" << input_vdex_fd;
1246 }
1247 } else {
1248 input_vdex.reset(OS::OpenFileForReading(input_vdex_filename.c_str()));
1249 if (input_vdex == nullptr) {
1250 PLOG(ERROR) << "Failed to open input vdex file " << input_vdex_filename;
1251 return EXIT_FAILURE;
1252 }
1253 }
1254 if (output_vdex_fd != -1) {
1255 output_vdex.reset(new File(output_vdex_fd, output_vdex_filename, true));
1256 if (output_vdex == nullptr) {
1257 // Unlikely, but ensure exhaustive logging in non-0 exit code case
1258 LOG(ERROR) << "Failed to open output vdex file by its FD" << output_vdex_fd;
1259 }
1260 } else {
1261 output_vdex.reset(CreateOrOpen(output_vdex_filename.c_str(), &new_vdex_out));
1262 if (output_vdex == nullptr) {
1263 PLOG(ERROR) << "Failed to open output vdex file " << output_vdex_filename;
1264 return EXIT_FAILURE;
1265 }
1266 }
1267 }
1268
Andreas Gampe6eb6a392016-02-10 20:18:37 -08001269 // TODO: get rid of this.
David Brazdil7b49e6c2016-09-01 11:06:18 +01001270 auto cleanup = [&output_oat_filename, &output_vdex_filename, &new_oat_out, &new_vdex_out]
1271 (bool success) {
Andreas Gampe6eb6a392016-02-10 20:18:37 -08001272 if (!success) {
1273 if (new_oat_out) {
1274 CHECK(!output_oat_filename.empty());
Dimitry Ivanov7a1c0142016-03-17 15:59:38 -07001275 unlink(output_oat_filename.c_str());
Andreas Gampe6eb6a392016-02-10 20:18:37 -08001276 }
David Brazdil7b49e6c2016-09-01 11:06:18 +01001277 if (new_vdex_out) {
1278 CHECK(!output_vdex_filename.empty());
1279 unlink(output_vdex_filename.c_str());
1280 }
Andreas Gampe6eb6a392016-02-10 20:18:37 -08001281 }
1282
1283 if (kIsDebugBuild) {
1284 LOG(INFO) << "Cleaning up.. success? " << success;
1285 }
1286 };
1287
Jeff Haoec1514a2016-03-17 21:32:45 -07001288 if (output_oat.get() == nullptr) {
Andreas Gampe6eb6a392016-02-10 20:18:37 -08001289 cleanup(false);
1290 return EXIT_FAILURE;
1291 }
1292
1293 if (match_delta) {
Andreas Gampe6eb6a392016-02-10 20:18:37 -08001294 // Figure out what the current delta is so we can match it to the desired delta.
Andreas Gampe6eb6a392016-02-10 20:18:37 -08001295 off_t current_delta = 0;
Jeff Haoec1514a2016-03-17 21:32:45 -07001296 if (!ReadOatPatchDelta(elf.get(), &current_delta, &error_msg)) {
Andreas Gampe6eb6a392016-02-10 20:18:37 -08001297 LOG(ERROR) << "Unable to get current delta: " << error_msg;
1298 cleanup(false);
1299 return EXIT_FAILURE;
1300 }
1301 // Before this line base_delta is the desired final delta. We need it to be the actual amount to
1302 // change everything by. We subtract the current delta from it to make it this.
1303 base_delta -= current_delta;
1304 if (!IsAligned<kPageSize>(base_delta)) {
1305 LOG(ERROR) << "Given image file was relocated by an illegal delta";
1306 cleanup(false);
1307 return false;
1308 }
1309 }
1310
1311 if (debug) {
1312 LOG(INFO) << "moving offset by " << base_delta
1313 << " (0x" << std::hex << base_delta << ") bytes or "
1314 << std::dec << (base_delta/kPageSize) << " pages.";
1315 }
1316
1317 ScopedFlock output_oat_lock;
1318 if (lock_output) {
Andreas Gampe6eb6a392016-02-10 20:18:37 -08001319 if (!output_oat_lock.Init(output_oat.get(), &error_msg)) {
1320 LOG(ERROR) << "Unable to lock output oat " << output_oat->GetPath() << ": " << error_msg;
1321 cleanup(false);
1322 return EXIT_FAILURE;
1323 }
1324 }
1325
1326 TimingLogger::ScopedTiming pt("patch oat", &timings);
1327 bool ret = PatchOat::Patch(input_oat.get(), base_delta, output_oat.get(), &timings,
1328 output_oat_fd >= 0, // was it opened from FD?
1329 new_oat_out);
1330 ret = FinishFile(output_oat.get(), ret);
1331
David Brazdil7b49e6c2016-09-01 11:06:18 +01001332 if (ret) {
1333 if (symlink_vdex) {
1334 ret = SymlinkFile(input_vdex_filename, output_vdex_filename);
1335 } else {
1336 ret = unix_file::CopyFile(*input_vdex.get(), output_vdex.get());
1337 }
1338 }
1339
Andreas Gampe6eb6a392016-02-10 20:18:37 -08001340 if (kIsDebugBuild) {
1341 LOG(INFO) << "Exiting with return ... " << ret;
1342 }
1343 cleanup(ret);
1344 return ret ? EXIT_SUCCESS : EXIT_FAILURE;
1345}
1346
David Brazdil7b49e6c2016-09-01 11:06:18 +01001347static int ParseFd(const StringPiece& option, const char* cmdline_arg) {
1348 int fd;
1349 const char* fd_str = option.substr(strlen(cmdline_arg)).data();
1350 if (!ParseInt(fd_str, &fd)) {
1351 Usage("Failed to parse %d argument '%s' as an integer", cmdline_arg, fd_str);
1352 }
1353 if (fd < 0) {
1354 Usage("%s pass a negative value %d", cmdline_arg, fd);
1355 }
1356 return fd;
1357}
1358
Alex Lighteefbe392014-07-08 09:53:18 -07001359static int patchoat(int argc, char **argv) {
Alex Light53cb16b2014-06-12 11:26:29 -07001360 InitLogging(argv);
Mathieu Chartier6e88ef62014-10-14 15:01:24 -07001361 MemMap::Init();
Alex Light53cb16b2014-06-12 11:26:29 -07001362 const bool debug = kIsDebugBuild;
1363 orig_argc = argc;
1364 orig_argv = argv;
1365 TimingLogger timings("patcher", false, false);
1366
1367 InitLogging(argv);
1368
1369 // Skip over the command name.
1370 argv++;
1371 argc--;
1372
1373 if (argc == 0) {
1374 Usage("No arguments specified");
1375 }
1376
1377 timings.StartTiming("Patchoat");
1378
1379 // cmd line args
1380 bool isa_set = false;
1381 InstructionSet isa = kNone;
1382 std::string input_oat_filename;
1383 std::string input_oat_location;
1384 int input_oat_fd = -1;
David Brazdil7b49e6c2016-09-01 11:06:18 +01001385 int input_vdex_fd = -1;
Alex Light53cb16b2014-06-12 11:26:29 -07001386 bool have_input_oat = false;
1387 std::string input_image_location;
1388 std::string output_oat_filename;
Alex Light53cb16b2014-06-12 11:26:29 -07001389 int output_oat_fd = -1;
David Brazdil7b49e6c2016-09-01 11:06:18 +01001390 int output_vdex_fd = -1;
Alex Light53cb16b2014-06-12 11:26:29 -07001391 bool have_output_oat = false;
1392 std::string output_image_filename;
Alex Light53cb16b2014-06-12 11:26:29 -07001393 off_t base_delta = 0;
1394 bool base_delta_set = false;
1395 std::string patched_image_filename;
1396 std::string patched_image_location;
1397 bool dump_timings = kIsDebugBuild;
Alex Lightcf4bf382014-07-24 11:29:14 -07001398 bool lock_output = true;
Alex Light53cb16b2014-06-12 11:26:29 -07001399
Ian Rogersd4c4d952014-10-16 20:31:53 -07001400 for (int i = 0; i < argc; ++i) {
Alex Light53cb16b2014-06-12 11:26:29 -07001401 const StringPiece option(argv[i]);
1402 const bool log_options = false;
1403 if (log_options) {
1404 LOG(INFO) << "patchoat: option[" << i << "]=" << argv[i];
1405 }
Alex Light53cb16b2014-06-12 11:26:29 -07001406 if (option.starts_with("--instruction-set=")) {
1407 isa_set = true;
1408 const char* isa_str = option.substr(strlen("--instruction-set=")).data();
Andreas Gampe20c89302014-08-19 17:28:06 -07001409 isa = GetInstructionSetFromString(isa_str);
1410 if (isa == kNone) {
1411 Usage("Unknown or invalid instruction set %s", isa_str);
Alex Light53cb16b2014-06-12 11:26:29 -07001412 }
1413 } else if (option.starts_with("--input-oat-location=")) {
1414 if (have_input_oat) {
1415 Usage("Only one of --input-oat-file, --input-oat-location and --input-oat-fd may be used.");
1416 }
1417 have_input_oat = true;
1418 input_oat_location = option.substr(strlen("--input-oat-location=")).data();
1419 } else if (option.starts_with("--input-oat-file=")) {
1420 if (have_input_oat) {
1421 Usage("Only one of --input-oat-file, --input-oat-location and --input-oat-fd may be used.");
1422 }
1423 have_input_oat = true;
1424 input_oat_filename = option.substr(strlen("--input-oat-file=")).data();
1425 } else if (option.starts_with("--input-oat-fd=")) {
1426 if (have_input_oat) {
1427 Usage("Only one of --input-oat-file, --input-oat-location and --input-oat-fd may be used.");
1428 }
1429 have_input_oat = true;
David Brazdil7b49e6c2016-09-01 11:06:18 +01001430 input_oat_fd = ParseFd(option, "--input-oat-fd=");
1431 } else if (option.starts_with("--input-vdex-fd=")) {
1432 input_vdex_fd = ParseFd(option, "--input-vdex-fd=");
Alex Light53cb16b2014-06-12 11:26:29 -07001433 } else if (option.starts_with("--input-image-location=")) {
1434 input_image_location = option.substr(strlen("--input-image-location=")).data();
Alex Light53cb16b2014-06-12 11:26:29 -07001435 } else if (option.starts_with("--output-oat-file=")) {
1436 if (have_output_oat) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001437 Usage("Only one of --output-oat-file, and --output-oat-fd may be used.");
Alex Light53cb16b2014-06-12 11:26:29 -07001438 }
1439 have_output_oat = true;
1440 output_oat_filename = option.substr(strlen("--output-oat-file=")).data();
1441 } else if (option.starts_with("--output-oat-fd=")) {
1442 if (have_output_oat) {
Alex Lightcf4bf382014-07-24 11:29:14 -07001443 Usage("Only one of --output-oat-file, --output-oat-fd may be used.");
Alex Light53cb16b2014-06-12 11:26:29 -07001444 }
1445 have_output_oat = true;
David Brazdil7b49e6c2016-09-01 11:06:18 +01001446 output_oat_fd = ParseFd(option, "--output-oat-fd=");
1447 } else if (option.starts_with("--output-vdex-fd=")) {
1448 output_vdex_fd = ParseFd(option, "--output-vdex-fd=");
Alex Light53cb16b2014-06-12 11:26:29 -07001449 } else if (option.starts_with("--output-image-file=")) {
Alex Light53cb16b2014-06-12 11:26:29 -07001450 output_image_filename = option.substr(strlen("--output-image-file=")).data();
Alex Light53cb16b2014-06-12 11:26:29 -07001451 } else if (option.starts_with("--base-offset-delta=")) {
1452 const char* base_delta_str = option.substr(strlen("--base-offset-delta=")).data();
1453 base_delta_set = true;
1454 if (!ParseInt(base_delta_str, &base_delta)) {
1455 Usage("Failed to parse --base-offset-delta argument '%s' as an off_t", base_delta_str);
1456 }
1457 } else if (option.starts_with("--patched-image-location=")) {
1458 patched_image_location = option.substr(strlen("--patched-image-location=")).data();
Alex Lightcf4bf382014-07-24 11:29:14 -07001459 } else if (option == "--lock-output") {
1460 lock_output = true;
1461 } else if (option == "--no-lock-output") {
1462 lock_output = false;
Alex Light53cb16b2014-06-12 11:26:29 -07001463 } else if (option == "--dump-timings") {
1464 dump_timings = true;
1465 } else if (option == "--no-dump-timings") {
1466 dump_timings = false;
1467 } else {
1468 Usage("Unknown argument %s", option.data());
1469 }
1470 }
1471
Andreas Gampe6eb6a392016-02-10 20:18:37 -08001472 // The instruction set is mandatory. This simplifies things...
1473 if (!isa_set) {
1474 Usage("Instruction set must be set.");
Alex Light53cb16b2014-06-12 11:26:29 -07001475 }
1476
Andreas Gampe6eb6a392016-02-10 20:18:37 -08001477 int ret;
1478 if (!input_image_location.empty()) {
1479 ret = patchoat_image(timings,
1480 isa,
1481 input_image_location,
1482 output_image_filename,
1483 base_delta,
1484 base_delta_set,
1485 debug);
Alex Light53cb16b2014-06-12 11:26:29 -07001486 } else {
Andreas Gampe6eb6a392016-02-10 20:18:37 -08001487 ret = patchoat_oat(timings,
1488 isa,
1489 patched_image_location,
1490 base_delta,
1491 base_delta_set,
1492 input_oat_fd,
David Brazdil7b49e6c2016-09-01 11:06:18 +01001493 input_vdex_fd,
Andreas Gampe6eb6a392016-02-10 20:18:37 -08001494 input_oat_location,
1495 input_oat_filename,
1496 have_input_oat,
1497 output_oat_fd,
David Brazdil7b49e6c2016-09-01 11:06:18 +01001498 output_vdex_fd,
Andreas Gampe6eb6a392016-02-10 20:18:37 -08001499 output_oat_filename,
1500 have_output_oat,
1501 lock_output,
1502 debug);
Alex Light53cb16b2014-06-12 11:26:29 -07001503 }
1504
Andreas Gampe6eb6a392016-02-10 20:18:37 -08001505 timings.EndTiming();
1506 if (dump_timings) {
1507 LOG(INFO) << Dumpable<TimingLogger>(timings);
Alex Light53cb16b2014-06-12 11:26:29 -07001508 }
1509
Andreas Gampe6eb6a392016-02-10 20:18:37 -08001510 return ret;
Alex Light53cb16b2014-06-12 11:26:29 -07001511}
1512
1513} // namespace art
1514
1515int main(int argc, char **argv) {
1516 return art::patchoat(argc, argv);
1517}