1 /*
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 <openssl/sha.h>
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <sys/file.h>
22 #include <sys/stat.h>
23 #include <unistd.h>
24 
25 #include <string>
26 #include <vector>
27 
28 #include "android-base/file.h"
29 #include "android-base/stringprintf.h"
30 #include "android-base/strings.h"
31 
32 #include "art_field-inl.h"
33 #include "art_method-inl.h"
34 #include "base/dumpable.h"
35 #include "base/file_utils.h"
36 #include "base/leb128.h"
37 #include "base/logging.h"  // For InitLogging.
38 #include "base/mutex.h"
39 #include "base/memory_tool.h"
40 #include "base/os.h"
41 #include "base/scoped_flock.h"
42 #include "base/stringpiece.h"
43 #include "base/unix_file/fd_file.h"
44 #include "base/unix_file/random_access_file_utils.h"
45 #include "base/utils.h"
46 #include "elf_file.h"
47 #include "elf_file_impl.h"
48 #include "elf_utils.h"
49 #include "gc/space/image_space.h"
50 #include "image-inl.h"
51 #include "intern_table.h"
52 #include "mirror/dex_cache.h"
53 #include "mirror/executable.h"
54 #include "mirror/method.h"
55 #include "mirror/object-inl.h"
56 #include "mirror/object-refvisitor-inl.h"
57 #include "mirror/reference.h"
58 #include "noop_compiler_callbacks.h"
59 #include "offsets.h"
60 #include "runtime.h"
61 #include "scoped_thread_state_change-inl.h"
62 #include "thread.h"
63 
64 namespace art {
65 
66 using android::base::StringPrintf;
67 
68 namespace {
69 
GetOatHeader(const ElfFile * elf_file)70 static const OatHeader* GetOatHeader(const ElfFile* elf_file) {
71   uint64_t off = 0;
72   if (!elf_file->GetSectionOffsetAndSize(".rodata", &off, nullptr)) {
73     return nullptr;
74   }
75 
76   OatHeader* oat_header = reinterpret_cast<OatHeader*>(elf_file->Begin() + off);
77   return oat_header;
78 }
79 
CreateOrOpen(const char * name)80 static File* CreateOrOpen(const char* name) {
81   if (OS::FileExists(name)) {
82     return OS::OpenFileReadWrite(name);
83   } else {
84     std::unique_ptr<File> f(OS::CreateEmptyFile(name));
85     if (f.get() != nullptr) {
86       if (fchmod(f->Fd(), 0644) != 0) {
87         PLOG(ERROR) << "Unable to make " << name << " world readable";
88         unlink(name);
89         return nullptr;
90       }
91     }
92     return f.release();
93   }
94 }
95 
96 // Either try to close the file (close=true), or erase it.
FinishFile(File * file,bool close)97 static bool FinishFile(File* file, bool close) {
98   if (close) {
99     if (file->FlushCloseOrErase() != 0) {
100       PLOG(ERROR) << "Failed to flush and close file.";
101       return false;
102     }
103     return true;
104   } else {
105     file->Erase();
106     return false;
107   }
108 }
109 
SymlinkFile(const std::string & input_filename,const std::string & output_filename)110 static bool SymlinkFile(const std::string& input_filename, const std::string& output_filename) {
111   if (input_filename == output_filename) {
112     // Input and output are the same, nothing to do.
113     return true;
114   }
115 
116   // Unlink the original filename, since we are overwriting it.
117   unlink(output_filename.c_str());
118 
119   // Create a symlink from the source file to the target path.
120   if (symlink(input_filename.c_str(), output_filename.c_str()) < 0) {
121     PLOG(ERROR) << "Failed to create symlink " << output_filename << " -> " << input_filename;
122     return false;
123   }
124 
125   if (kIsDebugBuild) {
126     LOG(INFO) << "Created symlink " << output_filename << " -> " << input_filename;
127   }
128 
129   return true;
130 }
131 
132 // Holder class for runtime options and related objects.
133 class PatchoatRuntimeOptionsHolder {
134  public:
PatchoatRuntimeOptionsHolder(const std::string & image_location,InstructionSet isa)135   PatchoatRuntimeOptionsHolder(const std::string& image_location, InstructionSet isa) {
136     options_.push_back(std::make_pair("compilercallbacks", &callbacks_));
137     img_ = "-Ximage:" + image_location;
138     options_.push_back(std::make_pair(img_.c_str(), nullptr));
139     isa_name_ = GetInstructionSetString(isa);
140     options_.push_back(std::make_pair("imageinstructionset",
141                                       reinterpret_cast<const void*>(isa_name_.c_str())));
142     options_.push_back(std::make_pair("-Xno-sig-chain", nullptr));
143     // We do not want the runtime to attempt to patch the image.
144     options_.push_back(std::make_pair("-Xnorelocate", nullptr));
145     // Don't try to compile.
146     options_.push_back(std::make_pair("-Xnoimage-dex2oat", nullptr));
147     // Do not accept broken image.
148     options_.push_back(std::make_pair("-Xno-dex-file-fallback", nullptr));
149   }
150 
GetRuntimeOptions()151   const RuntimeOptions& GetRuntimeOptions() {
152     return options_;
153   }
154 
155  private:
156   RuntimeOptions options_;
157   NoopCompilerCallbacks callbacks_;
158   std::string isa_name_;
159   std::string img_;
160 };
161 
162 }  // namespace
163 
GeneratePatch(const MemMap & original,const MemMap & relocated,std::vector<uint8_t> * output,std::string * error_msg)164 bool PatchOat::GeneratePatch(
165     const MemMap& original,
166     const MemMap& relocated,
167     std::vector<uint8_t>* output,
168     std::string* error_msg) {
169   // FORMAT of the patch (aka image relocation) file:
170   // * SHA-256 digest (32 bytes) of original/unrelocated file (e.g., the one from /system)
171   // * List of monotonically increasing offsets (max value defined by uint32_t) at which relocations
172   //   occur.
173   //   Each element is represented as the delta from the previous offset in the list (first element
174   //   is a delta from 0). Each delta is encoded using unsigned LEB128: little-endian
175   //   variable-length 7 bits per byte encoding, where all bytes have the highest bit (0x80) set
176   //   except for the final byte which does not have that bit set. For example, 0x3f is offset 0x3f,
177   //   whereas 0xbf 0x05 is offset (0x3f & 0x7f) | (0x5 << 7) which is 0x2bf. Most deltas end up
178   //   being encoding using just one byte, achieving ~4x decrease in relocation file size compared
179   //   to the encoding where offsets are stored verbatim, as uint32_t.
180 
181   size_t original_size = original.Size();
182   size_t relocated_size = relocated.Size();
183   if (original_size != relocated_size) {
184     *error_msg =
185         StringPrintf(
186             "Original and relocated image sizes differ: %zu vs %zu", original_size, relocated_size);
187     return false;
188   }
189   if ((original_size % 4) != 0) {
190     *error_msg = StringPrintf("Image size not multiple of 4: %zu", original_size);
191     return false;
192   }
193   if (original_size > UINT32_MAX) {
194     *error_msg = StringPrintf("Image too large: %zu" , original_size);
195     return false;
196   }
197 
198   const ImageHeader& relocated_header =
199       *reinterpret_cast<const ImageHeader*>(relocated.Begin());
200   // Offsets are supposed to differ between original and relocated by this value
201   off_t expected_diff = relocated_header.GetPatchDelta();
202   if (expected_diff == 0) {
203     // Can't identify offsets which are supposed to differ due to relocation
204     *error_msg = "Relocation delta is 0";
205     return false;
206   }
207 
208   // Output the SHA-256 digest of the original
209   output->resize(SHA256_DIGEST_LENGTH);
210   const uint8_t* original_bytes = original.Begin();
211   SHA256(original_bytes, original_size, output->data());
212 
213   // Output the list of offsets at which the original and patched images differ
214   size_t last_diff_offset = 0;
215   size_t diff_offset_count = 0;
216   const uint8_t* relocated_bytes = relocated.Begin();
217   for (size_t offset = 0; offset < original_size; offset += 4) {
218     uint32_t original_value = *reinterpret_cast<const uint32_t*>(original_bytes + offset);
219     uint32_t relocated_value = *reinterpret_cast<const uint32_t*>(relocated_bytes + offset);
220     off_t diff = relocated_value - original_value;
221     if (diff == 0) {
222       continue;
223     } else if (diff != expected_diff) {
224       *error_msg =
225           StringPrintf(
226               "Unexpected diff at offset %zu. Expected: %jd, but was: %jd",
227               offset,
228               (intmax_t) expected_diff,
229               (intmax_t) diff);
230       return false;
231     }
232 
233     uint32_t offset_diff = offset - last_diff_offset;
234     last_diff_offset = offset;
235     diff_offset_count++;
236 
237     EncodeUnsignedLeb128(output, offset_diff);
238   }
239 
240   if (diff_offset_count == 0) {
241     *error_msg = "Original and patched images are identical";
242     return false;
243   }
244 
245   return true;
246 }
247 
WriteRelFile(const MemMap & original,const MemMap & relocated,const std::string & rel_filename,std::string * error_msg)248 static bool WriteRelFile(
249     const MemMap& original,
250     const MemMap& relocated,
251     const std::string& rel_filename,
252     std::string* error_msg) {
253   std::vector<uint8_t> output;
254   if (!PatchOat::GeneratePatch(original, relocated, &output, error_msg)) {
255     return false;
256   }
257 
258   std::unique_ptr<File> rel_file(OS::CreateEmptyFileWriteOnly(rel_filename.c_str()));
259   if (rel_file.get() == nullptr) {
260     *error_msg = StringPrintf("Failed to create/open output file %s", rel_filename.c_str());
261     return false;
262   }
263   if (!rel_file->WriteFully(output.data(), output.size())) {
264     *error_msg = StringPrintf("Failed to write to %s", rel_filename.c_str());
265     return false;
266   }
267   if (rel_file->FlushCloseOrErase() != 0) {
268     *error_msg = StringPrintf("Failed to flush and close %s", rel_filename.c_str());
269     return false;
270   }
271 
272   return true;
273 }
274 
CheckImageIdenticalToOriginalExceptForRelocation(const std::string & relocated_filename,const std::string & original_filename,std::string * error_msg)275 static bool CheckImageIdenticalToOriginalExceptForRelocation(
276     const std::string& relocated_filename,
277     const std::string& original_filename,
278     std::string* error_msg) {
279   *error_msg = "";
280   std::string rel_filename = original_filename + ".rel";
281   std::unique_ptr<File> rel_file(OS::OpenFileForReading(rel_filename.c_str()));
282   if (rel_file.get() == nullptr) {
283     *error_msg = StringPrintf("Failed to open image relocation file %s", rel_filename.c_str());
284     return false;
285   }
286   int64_t rel_size = rel_file->GetLength();
287   if (rel_size < 0) {
288     *error_msg = StringPrintf("Error while getting size of image relocation file %s",
289                               rel_filename.c_str());
290     return false;
291   }
292   std::unique_ptr<uint8_t[]> rel(new uint8_t[rel_size]);
293   if (!rel_file->ReadFully(rel.get(), rel_size)) {
294     *error_msg = StringPrintf("Failed to read image relocation file %s", rel_filename.c_str());
295     return false;
296   }
297 
298   std::unique_ptr<File> image_file(OS::OpenFileForReading(relocated_filename.c_str()));
299   if (image_file.get() == nullptr) {
300     *error_msg = StringPrintf("Unable to open relocated image file  %s",
301                               relocated_filename.c_str());
302     return false;
303   }
304 
305   int64_t image_size = image_file->GetLength();
306   if (image_size < 0) {
307     *error_msg = StringPrintf("Error while getting size of relocated image file %s",
308                               relocated_filename.c_str());
309     return false;
310   }
311   if ((image_size % 4) != 0) {
312     *error_msg =
313         StringPrintf(
314             "Relocated image file %s size not multiple of 4: %" PRId64,
315                 relocated_filename.c_str(), image_size);
316     return false;
317   }
318   if (image_size > std::numeric_limits<uint32_t>::max()) {
319     *error_msg =
320         StringPrintf(
321             "Relocated image file %s too large: %" PRId64, relocated_filename.c_str(), image_size);
322     return false;
323   }
324 
325   std::unique_ptr<uint8_t[]> image(new uint8_t[image_size]);
326   if (!image_file->ReadFully(image.get(), image_size)) {
327     *error_msg = StringPrintf("Failed to read relocated image file %s", relocated_filename.c_str());
328     return false;
329   }
330 
331   const uint8_t* original_image_digest = rel.get();
332   if (rel_size < SHA256_DIGEST_LENGTH) {
333     *error_msg = StringPrintf("Malformed image relocation file %s: too short",
334                               rel_filename.c_str());
335     return false;
336   }
337 
338   const ImageHeader& image_header = *reinterpret_cast<const ImageHeader*>(image.get());
339   off_t expected_diff = image_header.GetPatchDelta();
340 
341   if (expected_diff == 0) {
342     *error_msg = StringPrintf("Unsuported patch delta of zero in %s",
343                               relocated_filename.c_str());
344     return false;
345   }
346 
347   // Relocated image is expected to differ from the original due to relocation.
348   // Unrelocate the image in memory to compensate.
349   uint8_t* image_start = image.get();
350   const uint8_t* rel_end = &rel[rel_size];
351   const uint8_t* rel_ptr = &rel[SHA256_DIGEST_LENGTH];
352   // The remaining .rel file consists of offsets at which relocation should've occurred.
353   // For each offset, we "unrelocate" the image by subtracting the expected relocation
354   // diff value (as specified in the image header).
355   //
356   // Each offset is encoded as a delta/diff relative to the previous offset. With the
357   // very first offset being encoded relative to offset 0.
358   // Deltas are encoded using little-endian 7 bits per byte encoding, with all bytes except
359   // the last one having the highest bit set.
360   uint32_t offset = 0;
361   while (rel_ptr != rel_end) {
362     uint32_t offset_delta = 0;
363     if (DecodeUnsignedLeb128Checked(&rel_ptr, rel_end, &offset_delta)) {
364       offset += offset_delta;
365       if (static_cast<int64_t>(offset) + static_cast<int64_t>(sizeof(uint32_t)) > image_size) {
366         *error_msg = StringPrintf("Relocation out of bounds in %s", relocated_filename.c_str());
367         return false;
368       }
369       uint32_t *image_value = reinterpret_cast<uint32_t*>(image_start + offset);
370       *image_value -= expected_diff;
371     } else {
372       *error_msg =
373           StringPrintf(
374               "Malformed image relocation file %s: "
375               "last byte has it's most significant bit set",
376               rel_filename.c_str());
377       return false;
378     }
379   }
380 
381   // Image in memory is now supposed to be identical to the original.  We
382   // confirm this by comparing the digest of the in-memory image to the expected
383   // digest from relocation file.
384   uint8_t image_digest[SHA256_DIGEST_LENGTH];
385   SHA256(image.get(), image_size, image_digest);
386   if (memcmp(image_digest, original_image_digest, SHA256_DIGEST_LENGTH) != 0) {
387     *error_msg =
388         StringPrintf(
389             "Relocated image %s does not match the original %s after unrelocation",
390             relocated_filename.c_str(),
391             original_filename.c_str());
392     return false;
393   }
394 
395   // Relocated image is identical to the original, once relocations are taken into account
396   return true;
397 }
398 
VerifySymlink(const std::string & intended_target,const std::string & link_name)399 static bool VerifySymlink(const std::string& intended_target, const std::string& link_name) {
400   std::string actual_target;
401   if (!android::base::Readlink(link_name, &actual_target)) {
402     PLOG(ERROR) << "Readlink on " << link_name << " failed.";
403     return false;
404   }
405   return actual_target == intended_target;
406 }
407 
VerifyVdexAndOatSymlinks(const std::string & input_image_filename,const std::string & output_image_filename)408 static bool VerifyVdexAndOatSymlinks(const std::string& input_image_filename,
409                                      const std::string& output_image_filename) {
410   return VerifySymlink(ImageHeader::GetVdexLocationFromImageLocation(input_image_filename),
411                        ImageHeader::GetVdexLocationFromImageLocation(output_image_filename))
412       && VerifySymlink(ImageHeader::GetOatLocationFromImageLocation(input_image_filename),
413                        ImageHeader::GetOatLocationFromImageLocation(output_image_filename));
414 }
415 
CreateVdexAndOatSymlinks(const std::string & input_image_filename,const std::string & output_image_filename)416 bool PatchOat::CreateVdexAndOatSymlinks(const std::string& input_image_filename,
417                                         const std::string& output_image_filename) {
418   std::string input_vdex_filename =
419       ImageHeader::GetVdexLocationFromImageLocation(input_image_filename);
420   std::string input_oat_filename =
421       ImageHeader::GetOatLocationFromImageLocation(input_image_filename);
422 
423   std::unique_ptr<File> input_oat_file(OS::OpenFileForReading(input_oat_filename.c_str()));
424   if (input_oat_file.get() == nullptr) {
425     LOG(ERROR) << "Unable to open input oat file at " << input_oat_filename;
426     return false;
427   }
428   std::string error_msg;
429   std::unique_ptr<ElfFile> elf(ElfFile::Open(input_oat_file.get(),
430                                              PROT_READ | PROT_WRITE,
431                                              MAP_PRIVATE,
432                                              &error_msg));
433   if (elf.get() == nullptr) {
434     LOG(ERROR) << "Unable to open oat file " << input_oat_filename << " : " << error_msg;
435     return false;
436   }
437 
438   MaybePic is_oat_pic = IsOatPic(elf.get());
439   if (is_oat_pic >= ERROR_FIRST) {
440     // Error logged by IsOatPic
441     return false;
442   } else if (is_oat_pic == NOT_PIC) {
443     LOG(ERROR) << "patchoat cannot be used on non-PIC oat file: " << input_oat_filename;
444     return false;
445   }
446 
447   CHECK(is_oat_pic == PIC);
448 
449   std::string output_vdex_filename =
450       ImageHeader::GetVdexLocationFromImageLocation(output_image_filename);
451   std::string output_oat_filename =
452       ImageHeader::GetOatLocationFromImageLocation(output_image_filename);
453 
454   return SymlinkFile(input_oat_filename, output_oat_filename) &&
455          SymlinkFile(input_vdex_filename, output_vdex_filename);
456 }
457 
Patch(const std::string & image_location,off_t delta,const std::string & output_image_directory,const std::string & output_image_relocation_directory,InstructionSet isa,TimingLogger * timings)458 bool PatchOat::Patch(const std::string& image_location,
459                      off_t delta,
460                      const std::string& output_image_directory,
461                      const std::string& output_image_relocation_directory,
462                      InstructionSet isa,
463                      TimingLogger* timings) {
464   bool output_image = !output_image_directory.empty();
465   bool output_image_relocation = !output_image_relocation_directory.empty();
466   if ((!output_image) && (!output_image_relocation)) {
467     // Nothing to do
468     return true;
469   }
470   if ((output_image_relocation) && (delta == 0)) {
471     LOG(ERROR) << "Cannot output image relocation information when requested relocation delta is 0";
472     return false;
473   }
474 
475   CHECK(Runtime::Current() == nullptr);
476   CHECK(!image_location.empty()) << "image file must have a filename.";
477 
478   TimingLogger::ScopedTiming t("Runtime Setup", timings);
479 
480   CHECK_NE(isa, InstructionSet::kNone);
481 
482   // Set up the runtime
483   PatchoatRuntimeOptionsHolder options_holder(image_location, isa);
484   if (!Runtime::Create(options_holder.GetRuntimeOptions(), false)) {
485     LOG(ERROR) << "Unable to initialize runtime";
486     return false;
487   }
488   std::unique_ptr<Runtime> runtime(Runtime::Current());
489 
490   // Runtime::Create acquired the mutator_lock_ that is normally given away when we Runtime::Start,
491   // give it away now and then switch to a more manageable ScopedObjectAccess.
492   Thread::Current()->TransitionFromRunnableToSuspended(kNative);
493   ScopedObjectAccess soa(Thread::Current());
494 
495   std::vector<gc::space::ImageSpace*> spaces = Runtime::Current()->GetHeap()->GetBootImageSpaces();
496   std::map<gc::space::ImageSpace*, std::unique_ptr<MemMap>> space_to_memmap_map;
497 
498   for (size_t i = 0; i < spaces.size(); ++i) {
499     t.NewTiming("Image Patching setup");
500     gc::space::ImageSpace* space = spaces[i];
501     std::string input_image_filename = space->GetImageFilename();
502     std::unique_ptr<File> input_image(OS::OpenFileForReading(input_image_filename.c_str()));
503     if (input_image.get() == nullptr) {
504       LOG(ERROR) << "Unable to open input image file at " << input_image_filename;
505       return false;
506     }
507 
508     int64_t image_len = input_image->GetLength();
509     if (image_len < 0) {
510       LOG(ERROR) << "Error while getting image length";
511       return false;
512     }
513     ImageHeader image_header;
514     if (sizeof(image_header) != input_image->Read(reinterpret_cast<char*>(&image_header),
515                                                   sizeof(image_header), 0)) {
516       LOG(ERROR) << "Unable to read image header from image file " << input_image->GetPath();
517     }
518 
519     /*bool is_image_pic = */IsImagePic(image_header, input_image->GetPath());
520     // Nothing special to do right now since the image always needs to get patched.
521     // Perhaps in some far-off future we may have images with relative addresses that are true-PIC.
522 
523     // Create the map where we will write the image patches to.
524     std::string error_msg;
525     std::unique_ptr<MemMap> image(MemMap::MapFile(image_len,
526                                                   PROT_READ | PROT_WRITE,
527                                                   MAP_PRIVATE,
528                                                   input_image->Fd(),
529                                                   0,
530                                                   /*low_4gb*/false,
531                                                   input_image->GetPath().c_str(),
532                                                   &error_msg));
533     if (image.get() == nullptr) {
534       LOG(ERROR) << "Unable to map image file " << input_image->GetPath() << " : " << error_msg;
535       return false;
536     }
537 
538 
539     space_to_memmap_map.emplace(space, std::move(image));
540     PatchOat p = PatchOat(isa,
541                           space_to_memmap_map.at(space).get(),
542                           space->GetLiveBitmap(),
543                           space->GetMemMap(),
544                           delta,
545                           &space_to_memmap_map,
546                           timings);
547 
548     t.NewTiming("Patching image");
549     if (!p.PatchImage(i == 0)) {
550       LOG(ERROR) << "Failed to patch image file " << input_image_filename;
551       return false;
552     }
553 
554     // Write the patched image spaces.
555     if (output_image) {
556       std::string output_image_filename;
557       if (!GetDalvikCacheFilename(space->GetImageLocation().c_str(),
558                                   output_image_directory.c_str(),
559                                   &output_image_filename,
560                                   &error_msg)) {
561         LOG(ERROR) << "Failed to find relocated image file name: " << error_msg;
562         return false;
563       }
564 
565       if (!CreateVdexAndOatSymlinks(input_image_filename, output_image_filename))
566         return false;
567 
568       t.NewTiming("Writing image");
569       std::unique_ptr<File> output_image_file(CreateOrOpen(output_image_filename.c_str()));
570       if (output_image_file.get() == nullptr) {
571         LOG(ERROR) << "Failed to open output image file at " << output_image_filename;
572         return false;
573       }
574 
575       bool success = p.WriteImage(output_image_file.get());
576       success = FinishFile(output_image_file.get(), success);
577       if (!success) {
578         return false;
579       }
580     }
581 
582     if (output_image_relocation) {
583       t.NewTiming("Writing image relocation");
584       std::string original_image_filename(space->GetImageLocation() + ".rel");
585       std::string image_relocation_filename =
586           output_image_relocation_directory
587               + (android::base::StartsWith(original_image_filename, "/") ? "" : "/")
588               + original_image_filename.substr(original_image_filename.find_last_of("/"));
589       int64_t input_image_size = input_image->GetLength();
590       if (input_image_size < 0) {
591         LOG(ERROR) << "Error while getting input image size";
592         return false;
593       }
594       std::unique_ptr<MemMap> original(MemMap::MapFile(input_image_size,
595                                                        PROT_READ,
596                                                        MAP_PRIVATE,
597                                                        input_image->Fd(),
598                                                        0,
599                                                        /*low_4gb*/false,
600                                                        input_image->GetPath().c_str(),
601                                                        &error_msg));
602       if (original.get() == nullptr) {
603         LOG(ERROR) << "Unable to map image file " << input_image->GetPath() << " : " << error_msg;
604         return false;
605       }
606 
607       const MemMap* relocated = p.image_;
608 
609       if (!WriteRelFile(*original, *relocated, image_relocation_filename, &error_msg)) {
610         LOG(ERROR) << "Failed to create image relocation file " << image_relocation_filename
611             << ": " << error_msg;
612         return false;
613       }
614     }
615   }
616 
617   if (!kIsDebugBuild && !(RUNNING_ON_MEMORY_TOOL && kMemoryToolDetectsLeaks)) {
618     // We want to just exit on non-debug builds, not bringing the runtime down
619     // in an orderly fashion. So release the following fields.
620     runtime.release();
621   }
622 
623   return true;
624 }
625 
Verify(const std::string & image_location,const std::string & output_image_directory,InstructionSet isa,TimingLogger * timings)626 bool PatchOat::Verify(const std::string& image_location,
627                       const std::string& output_image_directory,
628                       InstructionSet isa,
629                       TimingLogger* timings) {
630   if (image_location.empty()) {
631     LOG(ERROR) << "Original image file not provided";
632     return false;
633   }
634   if (output_image_directory.empty()) {
635     LOG(ERROR) << "Relocated image directory not provided";
636     return false;
637   }
638 
639   TimingLogger::ScopedTiming t("Runtime Setup", timings);
640 
641   CHECK_NE(isa, InstructionSet::kNone);
642 
643   // Set up the runtime
644   PatchoatRuntimeOptionsHolder options_holder(image_location, isa);
645   if (!Runtime::Create(options_holder.GetRuntimeOptions(), false)) {
646     LOG(ERROR) << "Unable to initialize runtime";
647     return false;
648   }
649   std::unique_ptr<Runtime> runtime(Runtime::Current());
650 
651   // Runtime::Create acquired the mutator_lock_ that is normally given away when we Runtime::Start,
652   // give it away now and then switch to a more manageable ScopedObjectAccess.
653   Thread::Current()->TransitionFromRunnableToSuspended(kNative);
654   ScopedObjectAccess soa(Thread::Current());
655 
656   t.NewTiming("Image Verification setup");
657   std::vector<gc::space::ImageSpace*> spaces = Runtime::Current()->GetHeap()->GetBootImageSpaces();
658 
659   // TODO: Check that no other .rel files exist in the original dir
660 
661   bool success = true;
662   std::string image_location_dir = android::base::Dirname(image_location);
663   for (size_t i = 0; i < spaces.size(); ++i) {
664     gc::space::ImageSpace* space = spaces[i];
665 
666     std::string relocated_image_filename;
667     std::string error_msg;
668     if (!GetDalvikCacheFilename(space->GetImageLocation().c_str(),
669             output_image_directory.c_str(), &relocated_image_filename, &error_msg)) {
670       LOG(ERROR) << "Failed to find relocated image file name: " << error_msg;
671       success = false;
672       break;
673     }
674     // location:     /system/framework/boot.art
675     // isa:          arm64
676     // basename:     boot.art
677     // original:     /system/framework/arm64/boot.art
678     // relocation:   /system/framework/arm64/boot.art.rel
679     std::string original_image_filename =
680         GetSystemImageFilename(space->GetImageLocation().c_str(), isa);
681 
682     if (!CheckImageIdenticalToOriginalExceptForRelocation(
683             relocated_image_filename, original_image_filename, &error_msg)) {
684       LOG(ERROR) << error_msg;
685       success = false;
686       break;
687     }
688 
689     if (!VerifyVdexAndOatSymlinks(original_image_filename, relocated_image_filename)) {
690       LOG(ERROR) << "Verification of vdex and oat symlinks for "
691                  << space->GetImageLocation() << " failed.";
692       success = false;
693       break;
694     }
695   }
696 
697   if (!kIsDebugBuild && !(RUNNING_ON_MEMORY_TOOL && kMemoryToolDetectsLeaks)) {
698     // We want to just exit on non-debug builds, not bringing the runtime down
699     // in an orderly fashion. So release the following fields.
700     runtime.release();
701   }
702 
703   return success;
704 }
705 
WriteImage(File * out)706 bool PatchOat::WriteImage(File* out) {
707   TimingLogger::ScopedTiming t("Writing image File", timings_);
708   std::string error_msg;
709 
710   // No error checking here, this is best effort. The locking may or may not
711   // succeed and we don't really care either way.
712   ScopedFlock img_flock = LockedFile::DupOf(out->Fd(), out->GetPath(),
713                                             true /* read_only_mode */, &error_msg);
714 
715   CHECK(image_ != nullptr);
716   CHECK(out != nullptr);
717   size_t expect = image_->Size();
718   if (out->WriteFully(reinterpret_cast<char*>(image_->Begin()), expect) &&
719       out->SetLength(expect) == 0) {
720     return true;
721   } else {
722     LOG(ERROR) << "Writing to image file " << out->GetPath() << " failed.";
723     return false;
724   }
725 }
726 
IsImagePic(const ImageHeader & image_header,const std::string & image_path)727 bool PatchOat::IsImagePic(const ImageHeader& image_header, const std::string& image_path) {
728   if (!image_header.CompilePic()) {
729     if (kIsDebugBuild) {
730       LOG(INFO) << "image at location " << image_path << " was *not* compiled pic";
731     }
732     return false;
733   }
734 
735   if (kIsDebugBuild) {
736     LOG(INFO) << "image at location " << image_path << " was compiled PIC";
737   }
738 
739   return true;
740 }
741 
IsOatPic(const ElfFile * oat_in)742 PatchOat::MaybePic PatchOat::IsOatPic(const ElfFile* oat_in) {
743   if (oat_in == nullptr) {
744     LOG(ERROR) << "No ELF input oat fie available";
745     return ERROR_OAT_FILE;
746   }
747 
748   const std::string& file_path = oat_in->GetFilePath();
749 
750   const OatHeader* oat_header = GetOatHeader(oat_in);
751   if (oat_header == nullptr) {
752     LOG(ERROR) << "Failed to find oat header in oat file " << file_path;
753     return ERROR_OAT_FILE;
754   }
755 
756   if (!oat_header->IsValid()) {
757     LOG(ERROR) << "Elf file " << file_path << " has an invalid oat header";
758     return ERROR_OAT_FILE;
759   }
760 
761   bool is_pic = oat_header->IsPic();
762   if (kIsDebugBuild) {
763     LOG(INFO) << "Oat file at " << file_path << " is " << (is_pic ? "PIC" : "not pic");
764   }
765 
766   return is_pic ? PIC : NOT_PIC;
767 }
768 
769 class PatchOat::PatchOatArtFieldVisitor : public ArtFieldVisitor {
770  public:
PatchOatArtFieldVisitor(PatchOat * patch_oat)771   explicit PatchOatArtFieldVisitor(PatchOat* patch_oat) : patch_oat_(patch_oat) {}
772 
Visit(ArtField * field)773   void Visit(ArtField* field) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
774     ArtField* const dest = patch_oat_->RelocatedCopyOf(field);
775     dest->SetDeclaringClass(
776         patch_oat_->RelocatedAddressOfPointer(field->GetDeclaringClass().Ptr()));
777   }
778 
779  private:
780   PatchOat* const patch_oat_;
781 };
782 
PatchArtFields(const ImageHeader * image_header)783 void PatchOat::PatchArtFields(const ImageHeader* image_header) {
784   PatchOatArtFieldVisitor visitor(this);
785   image_header->VisitPackedArtFields(&visitor, heap_->Begin());
786 }
787 
788 class PatchOat::PatchOatArtMethodVisitor : public ArtMethodVisitor {
789  public:
PatchOatArtMethodVisitor(PatchOat * patch_oat)790   explicit PatchOatArtMethodVisitor(PatchOat* patch_oat) : patch_oat_(patch_oat) {}
791 
Visit(ArtMethod * method)792   void Visit(ArtMethod* method) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
793     ArtMethod* const dest = patch_oat_->RelocatedCopyOf(method);
794     patch_oat_->FixupMethod(method, dest);
795   }
796 
797  private:
798   PatchOat* const patch_oat_;
799 };
800 
PatchArtMethods(const ImageHeader * image_header)801 void PatchOat::PatchArtMethods(const ImageHeader* image_header) {
802   const PointerSize pointer_size = InstructionSetPointerSize(isa_);
803   PatchOatArtMethodVisitor visitor(this);
804   image_header->VisitPackedArtMethods(&visitor, heap_->Begin(), pointer_size);
805 }
806 
PatchImTables(const ImageHeader * image_header)807 void PatchOat::PatchImTables(const ImageHeader* image_header) {
808   const PointerSize pointer_size = InstructionSetPointerSize(isa_);
809   // We can safely walk target image since the conflict tables are independent.
810   image_header->VisitPackedImTables(
811       [this](ArtMethod* method) {
812         return RelocatedAddressOfPointer(method);
813       },
814       image_->Begin(),
815       pointer_size);
816 }
817 
PatchImtConflictTables(const ImageHeader * image_header)818 void PatchOat::PatchImtConflictTables(const ImageHeader* image_header) {
819   const PointerSize pointer_size = InstructionSetPointerSize(isa_);
820   // We can safely walk target image since the conflict tables are independent.
821   image_header->VisitPackedImtConflictTables(
822       [this](ArtMethod* method) {
823         return RelocatedAddressOfPointer(method);
824       },
825       image_->Begin(),
826       pointer_size);
827 }
828 
829 class PatchOat::FixupRootVisitor : public RootVisitor {
830  public:
FixupRootVisitor(const PatchOat * patch_oat)831   explicit FixupRootVisitor(const PatchOat* patch_oat) : patch_oat_(patch_oat) {
832   }
833 
VisitRoots(mirror::Object *** roots,size_t count,const RootInfo & info ATTRIBUTE_UNUSED)834   void VisitRoots(mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED)
835       OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
836     for (size_t i = 0; i < count; ++i) {
837       *roots[i] = patch_oat_->RelocatedAddressOfPointer(*roots[i]);
838     }
839   }
840 
VisitRoots(mirror::CompressedReference<mirror::Object> ** roots,size_t count,const RootInfo & info ATTRIBUTE_UNUSED)841   void VisitRoots(mirror::CompressedReference<mirror::Object>** roots, size_t count,
842                   const RootInfo& info ATTRIBUTE_UNUSED)
843       OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) {
844     for (size_t i = 0; i < count; ++i) {
845       roots[i]->Assign(patch_oat_->RelocatedAddressOfPointer(roots[i]->AsMirrorPtr()));
846     }
847   }
848 
849  private:
850   const PatchOat* const patch_oat_;
851 };
852 
PatchInternedStrings(const ImageHeader * image_header)853 void PatchOat::PatchInternedStrings(const ImageHeader* image_header) {
854   const auto& section = image_header->GetInternedStringsSection();
855   if (section.Size() == 0) {
856     return;
857   }
858   InternTable temp_table;
859   // Note that we require that ReadFromMemory does not make an internal copy of the elements.
860   // This also relies on visit roots not doing any verification which could fail after we update
861   // the roots to be the image addresses.
862   temp_table.AddTableFromMemory(image_->Begin() + section.Offset());
863   FixupRootVisitor visitor(this);
864   temp_table.VisitRoots(&visitor, kVisitRootFlagAllRoots);
865 }
866 
PatchClassTable(const ImageHeader * image_header)867 void PatchOat::PatchClassTable(const ImageHeader* image_header) {
868   const auto& section = image_header->GetClassTableSection();
869   if (section.Size() == 0) {
870     return;
871   }
872   // Note that we require that ReadFromMemory does not make an internal copy of the elements.
873   // This also relies on visit roots not doing any verification which could fail after we update
874   // the roots to be the image addresses.
875   WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
876   ClassTable temp_table;
877   temp_table.ReadFromMemory(image_->Begin() + section.Offset());
878   FixupRootVisitor visitor(this);
879   temp_table.VisitRoots(UnbufferedRootVisitor(&visitor, RootInfo(kRootUnknown)));
880 }
881 
882 
883 class PatchOat::RelocatedPointerVisitor {
884  public:
RelocatedPointerVisitor(PatchOat * patch_oat)885   explicit RelocatedPointerVisitor(PatchOat* patch_oat) : patch_oat_(patch_oat) {}
886 
887   template <typename T>
operator ()(T * ptr,void ** dest_addr ATTRIBUTE_UNUSED=0) const888   T* operator()(T* ptr, void** dest_addr ATTRIBUTE_UNUSED = 0) const {
889     return patch_oat_->RelocatedAddressOfPointer(ptr);
890   }
891 
892  private:
893   PatchOat* const patch_oat_;
894 };
895 
PatchDexFileArrays(mirror::ObjectArray<mirror::Object> * img_roots)896 void PatchOat::PatchDexFileArrays(mirror::ObjectArray<mirror::Object>* img_roots) {
897   auto* dex_caches = down_cast<mirror::ObjectArray<mirror::DexCache>*>(
898       img_roots->Get(ImageHeader::kDexCaches));
899   const PointerSize pointer_size = InstructionSetPointerSize(isa_);
900   for (size_t i = 0, count = dex_caches->GetLength(); i < count; ++i) {
901     auto* orig_dex_cache = dex_caches->GetWithoutChecks(i);
902     auto* copy_dex_cache = RelocatedCopyOf(orig_dex_cache);
903     // Though the DexCache array fields are usually treated as native pointers, we set the full
904     // 64-bit values here, clearing the top 32 bits for 32-bit targets. The zero-extension is
905     // done by casting to the unsigned type uintptr_t before casting to int64_t, i.e.
906     //     static_cast<int64_t>(reinterpret_cast<uintptr_t>(image_begin_ + offset))).
907     mirror::StringDexCacheType* orig_strings = orig_dex_cache->GetStrings();
908     mirror::StringDexCacheType* relocated_strings = RelocatedAddressOfPointer(orig_strings);
909     copy_dex_cache->SetField64<false>(
910         mirror::DexCache::StringsOffset(),
911         static_cast<int64_t>(reinterpret_cast<uintptr_t>(relocated_strings)));
912     if (orig_strings != nullptr) {
913       orig_dex_cache->FixupStrings(RelocatedCopyOf(orig_strings), RelocatedPointerVisitor(this));
914     }
915     mirror::TypeDexCacheType* orig_types = orig_dex_cache->GetResolvedTypes();
916     mirror::TypeDexCacheType* relocated_types = RelocatedAddressOfPointer(orig_types);
917     copy_dex_cache->SetField64<false>(
918         mirror::DexCache::ResolvedTypesOffset(),
919         static_cast<int64_t>(reinterpret_cast<uintptr_t>(relocated_types)));
920     if (orig_types != nullptr) {
921       orig_dex_cache->FixupResolvedTypes(RelocatedCopyOf(orig_types),
922                                          RelocatedPointerVisitor(this));
923     }
924     mirror::MethodDexCacheType* orig_methods = orig_dex_cache->GetResolvedMethods();
925     mirror::MethodDexCacheType* relocated_methods = RelocatedAddressOfPointer(orig_methods);
926     copy_dex_cache->SetField64<false>(
927         mirror::DexCache::ResolvedMethodsOffset(),
928         static_cast<int64_t>(reinterpret_cast<uintptr_t>(relocated_methods)));
929     if (orig_methods != nullptr) {
930       mirror::MethodDexCacheType* copy_methods = RelocatedCopyOf(orig_methods);
931       for (size_t j = 0, num = orig_dex_cache->NumResolvedMethods(); j != num; ++j) {
932         mirror::MethodDexCachePair orig =
933             mirror::DexCache::GetNativePairPtrSize(orig_methods, j, pointer_size);
934         mirror::MethodDexCachePair copy(RelocatedAddressOfPointer(orig.object), orig.index);
935         mirror::DexCache::SetNativePairPtrSize(copy_methods, j, copy, pointer_size);
936       }
937     }
938     mirror::FieldDexCacheType* orig_fields = orig_dex_cache->GetResolvedFields();
939     mirror::FieldDexCacheType* relocated_fields = RelocatedAddressOfPointer(orig_fields);
940     copy_dex_cache->SetField64<false>(
941         mirror::DexCache::ResolvedFieldsOffset(),
942         static_cast<int64_t>(reinterpret_cast<uintptr_t>(relocated_fields)));
943     if (orig_fields != nullptr) {
944       mirror::FieldDexCacheType* copy_fields = RelocatedCopyOf(orig_fields);
945       for (size_t j = 0, num = orig_dex_cache->NumResolvedFields(); j != num; ++j) {
946         mirror::FieldDexCachePair orig =
947             mirror::DexCache::GetNativePairPtrSize(orig_fields, j, pointer_size);
948         mirror::FieldDexCachePair copy(RelocatedAddressOfPointer(orig.object), orig.index);
949         mirror::DexCache::SetNativePairPtrSize(copy_fields, j, copy, pointer_size);
950       }
951     }
952     mirror::MethodTypeDexCacheType* orig_method_types = orig_dex_cache->GetResolvedMethodTypes();
953     mirror::MethodTypeDexCacheType* relocated_method_types =
954         RelocatedAddressOfPointer(orig_method_types);
955     copy_dex_cache->SetField64<false>(
956         mirror::DexCache::ResolvedMethodTypesOffset(),
957         static_cast<int64_t>(reinterpret_cast<uintptr_t>(relocated_method_types)));
958     if (orig_method_types != nullptr) {
959       orig_dex_cache->FixupResolvedMethodTypes(RelocatedCopyOf(orig_method_types),
960                                                RelocatedPointerVisitor(this));
961     }
962 
963     GcRoot<mirror::CallSite>* orig_call_sites = orig_dex_cache->GetResolvedCallSites();
964     GcRoot<mirror::CallSite>* relocated_call_sites = RelocatedAddressOfPointer(orig_call_sites);
965     copy_dex_cache->SetField64<false>(
966         mirror::DexCache::ResolvedCallSitesOffset(),
967         static_cast<int64_t>(reinterpret_cast<uintptr_t>(relocated_call_sites)));
968     if (orig_call_sites != nullptr) {
969       orig_dex_cache->FixupResolvedCallSites(RelocatedCopyOf(orig_call_sites),
970                                              RelocatedPointerVisitor(this));
971     }
972   }
973 }
974 
PatchImage(bool primary_image)975 bool PatchOat::PatchImage(bool primary_image) {
976   ImageHeader* image_header = reinterpret_cast<ImageHeader*>(image_->Begin());
977   CHECK_GT(image_->Size(), sizeof(ImageHeader));
978   // These are the roots from the original file.
979   auto* img_roots = image_header->GetImageRoots();
980   image_header->RelocateImage(delta_);
981 
982   PatchArtFields(image_header);
983   PatchArtMethods(image_header);
984   PatchImTables(image_header);
985   PatchImtConflictTables(image_header);
986   PatchInternedStrings(image_header);
987   PatchClassTable(image_header);
988   // Patch dex file int/long arrays which point to ArtFields.
989   PatchDexFileArrays(img_roots);
990 
991   if (primary_image) {
992     VisitObject(img_roots);
993   }
994 
995   if (!image_header->IsValid()) {
996     LOG(ERROR) << "relocation renders image header invalid";
997     return false;
998   }
999 
1000   {
1001     TimingLogger::ScopedTiming t("Walk Bitmap", timings_);
1002     // Walk the bitmap.
1003     WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
1004     auto visitor = [&](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
1005       VisitObject(obj);
1006     };
1007     bitmap_->Walk(visitor);
1008   }
1009   return true;
1010 }
1011 
1012 
operator ()(ObjPtr<mirror::Object> obj,MemberOffset off,bool is_static_unused ATTRIBUTE_UNUSED) const1013 void PatchOat::PatchVisitor::operator() (ObjPtr<mirror::Object> obj,
1014                                          MemberOffset off,
1015                                          bool is_static_unused ATTRIBUTE_UNUSED) const {
1016   mirror::Object* referent = obj->GetFieldObject<mirror::Object, kVerifyNone>(off);
1017   mirror::Object* moved_object = patcher_->RelocatedAddressOfPointer(referent);
1018   copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(off, moved_object);
1019 }
1020 
operator ()(ObjPtr<mirror::Class> cls ATTRIBUTE_UNUSED,ObjPtr<mirror::Reference> ref) const1021 void PatchOat::PatchVisitor::operator() (ObjPtr<mirror::Class> cls ATTRIBUTE_UNUSED,
1022                                          ObjPtr<mirror::Reference> ref) const {
1023   MemberOffset off = mirror::Reference::ReferentOffset();
1024   mirror::Object* referent = ref->GetReferent();
1025   DCHECK(referent == nullptr ||
1026          Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(referent)) << referent;
1027   mirror::Object* moved_object = patcher_->RelocatedAddressOfPointer(referent);
1028   copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(off, moved_object);
1029 }
1030 
1031 // Called by PatchImage.
VisitObject(mirror::Object * object)1032 void PatchOat::VisitObject(mirror::Object* object) {
1033   mirror::Object* copy = RelocatedCopyOf(object);
1034   CHECK(copy != nullptr);
1035   if (kUseBakerReadBarrier) {
1036     object->AssertReadBarrierState();
1037   }
1038   PatchOat::PatchVisitor visitor(this, copy);
1039   object->VisitReferences<kVerifyNone>(visitor, visitor);
1040   if (object->IsClass<kVerifyNone>()) {
1041     const PointerSize pointer_size = InstructionSetPointerSize(isa_);
1042     mirror::Class* klass = object->AsClass();
1043     mirror::Class* copy_klass = down_cast<mirror::Class*>(copy);
1044     RelocatedPointerVisitor native_visitor(this);
1045     klass->FixupNativePointers(copy_klass, pointer_size, native_visitor);
1046     auto* vtable = klass->GetVTable();
1047     if (vtable != nullptr) {
1048       vtable->Fixup(RelocatedCopyOfFollowImages(vtable), pointer_size, native_visitor);
1049     }
1050     mirror::IfTable* iftable = klass->GetIfTable();
1051     for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
1052       if (iftable->GetMethodArrayCount(i) > 0) {
1053         auto* method_array = iftable->GetMethodArray(i);
1054         CHECK(method_array != nullptr);
1055         method_array->Fixup(RelocatedCopyOfFollowImages(method_array),
1056                             pointer_size,
1057                             native_visitor);
1058       }
1059     }
1060   } else if (object->GetClass() == mirror::Method::StaticClass() ||
1061              object->GetClass() == mirror::Constructor::StaticClass()) {
1062     // Need to go update the ArtMethod.
1063     auto* dest = down_cast<mirror::Executable*>(copy);
1064     auto* src = down_cast<mirror::Executable*>(object);
1065     dest->SetArtMethod(RelocatedAddressOfPointer(src->GetArtMethod()));
1066   }
1067 }
1068 
FixupMethod(ArtMethod * object,ArtMethod * copy)1069 void PatchOat::FixupMethod(ArtMethod* object, ArtMethod* copy) {
1070   const PointerSize pointer_size = InstructionSetPointerSize(isa_);
1071   copy->CopyFrom(object, pointer_size);
1072   // Just update the entry points if it looks like we should.
1073   // TODO: sanity check all the pointers' values
1074   copy->SetDeclaringClass(RelocatedAddressOfPointer(object->GetDeclaringClass()));
1075   copy->SetEntryPointFromQuickCompiledCodePtrSize(RelocatedAddressOfPointer(
1076       object->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size)), pointer_size);
1077   // No special handling for IMT conflict table since all pointers are moved by the same offset.
1078   copy->SetDataPtrSize(RelocatedAddressOfPointer(
1079       object->GetDataPtrSize(pointer_size)), pointer_size);
1080 }
1081 
1082 static int orig_argc;
1083 static char** orig_argv;
1084 
CommandLine()1085 static std::string CommandLine() {
1086   std::vector<std::string> command;
1087   for (int i = 0; i < orig_argc; ++i) {
1088     command.push_back(orig_argv[i]);
1089   }
1090   return android::base::Join(command, ' ');
1091 }
1092 
UsageErrorV(const char * fmt,va_list ap)1093 static void UsageErrorV(const char* fmt, va_list ap) {
1094   std::string error;
1095   android::base::StringAppendV(&error, fmt, ap);
1096   LOG(ERROR) << error;
1097 }
1098 
UsageError(const char * fmt,...)1099 static void UsageError(const char* fmt, ...) {
1100   va_list ap;
1101   va_start(ap, fmt);
1102   UsageErrorV(fmt, ap);
1103   va_end(ap);
1104 }
1105 
Usage(const char * fmt,...)1106 NO_RETURN static void Usage(const char *fmt, ...) {
1107   va_list ap;
1108   va_start(ap, fmt);
1109   UsageErrorV(fmt, ap);
1110   va_end(ap);
1111 
1112   UsageError("Command: %s", CommandLine().c_str());
1113   UsageError("Usage: patchoat [options]...");
1114   UsageError("");
1115   UsageError("  --instruction-set=<isa>: Specifies the instruction set the patched code is");
1116   UsageError("      compiled for (required).");
1117   UsageError("");
1118   UsageError("  --input-image-location=<file.art>: Specifies the 'location' of the image file to");
1119   UsageError("      be patched.");
1120   UsageError("");
1121   UsageError("  --output-image-directory=<dir>: Specifies the directory to write the patched");
1122   UsageError("      image file(s) to.");
1123   UsageError("");
1124   UsageError("  --output-image-relocation-directory=<dir>: Specifies the directory to write");
1125   UsageError("      the image relocation information to.");
1126   UsageError("");
1127   UsageError("  --base-offset-delta=<delta>: Specify the amount to change the old base-offset by.");
1128   UsageError("      This value may be negative.");
1129   UsageError("");
1130   UsageError("  --verify: Verify an existing patched file instead of creating one.");
1131   UsageError("");
1132   UsageError("  --dump-timings: dump out patch timing information");
1133   UsageError("");
1134   UsageError("  --no-dump-timings: do not dump out patch timing information");
1135   UsageError("");
1136 
1137   exit(EXIT_FAILURE);
1138 }
1139 
patchoat_patch_image(TimingLogger & timings,InstructionSet isa,const std::string & input_image_location,const std::string & output_image_directory,const std::string & output_image_relocation_directory,off_t base_delta,bool base_delta_set,bool debug)1140 static int patchoat_patch_image(TimingLogger& timings,
1141                                 InstructionSet isa,
1142                                 const std::string& input_image_location,
1143                                 const std::string& output_image_directory,
1144                                 const std::string& output_image_relocation_directory,
1145                                 off_t base_delta,
1146                                 bool base_delta_set,
1147                                 bool debug) {
1148   CHECK(!input_image_location.empty());
1149   if ((output_image_directory.empty()) && (output_image_relocation_directory.empty())) {
1150     Usage("Image patching requires --output-image-directory or --output-image-relocation-directory");
1151   }
1152 
1153   if (!base_delta_set) {
1154     Usage("Must supply a desired new offset or delta.");
1155   }
1156 
1157   if (!IsAligned<kPageSize>(base_delta)) {
1158     Usage("Base offset/delta must be aligned to a pagesize (0x%08x) boundary.", kPageSize);
1159   }
1160 
1161   if (debug) {
1162     LOG(INFO) << "moving offset by " << base_delta
1163         << " (0x" << std::hex << base_delta << ") bytes or "
1164         << std::dec << (base_delta/kPageSize) << " pages.";
1165   }
1166 
1167   TimingLogger::ScopedTiming pt("patch image and oat", &timings);
1168 
1169   bool ret =
1170       PatchOat::Patch(
1171           input_image_location,
1172           base_delta,
1173           output_image_directory,
1174           output_image_relocation_directory,
1175           isa,
1176           &timings);
1177 
1178   if (kIsDebugBuild) {
1179     LOG(INFO) << "Exiting with return ... " << ret;
1180   }
1181   return ret ? EXIT_SUCCESS : EXIT_FAILURE;
1182 }
1183 
patchoat_verify_image(TimingLogger & timings,InstructionSet isa,const std::string & input_image_location,const std::string & output_image_directory)1184 static int patchoat_verify_image(TimingLogger& timings,
1185                                  InstructionSet isa,
1186                                  const std::string& input_image_location,
1187                                  const std::string& output_image_directory) {
1188   CHECK(!input_image_location.empty());
1189   TimingLogger::ScopedTiming pt("verify image and oat", &timings);
1190 
1191   bool ret =
1192       PatchOat::Verify(
1193           input_image_location,
1194           output_image_directory,
1195           isa,
1196           &timings);
1197 
1198   if (kIsDebugBuild) {
1199     LOG(INFO) << "Exiting with return ... " << ret;
1200   }
1201   return ret ? EXIT_SUCCESS : EXIT_FAILURE;
1202 }
1203 
patchoat(int argc,char ** argv)1204 static int patchoat(int argc, char **argv) {
1205   Locks::Init();
1206   InitLogging(argv, Runtime::Abort);
1207   MemMap::Init();
1208   const bool debug = kIsDebugBuild;
1209   orig_argc = argc;
1210   orig_argv = argv;
1211   TimingLogger timings("patcher", false, false);
1212 
1213   // Skip over the command name.
1214   argv++;
1215   argc--;
1216 
1217   if (argc == 0) {
1218     Usage("No arguments specified");
1219   }
1220 
1221   timings.StartTiming("Patchoat");
1222 
1223   // cmd line args
1224   bool isa_set = false;
1225   InstructionSet isa = InstructionSet::kNone;
1226   std::string input_image_location;
1227   std::string output_image_directory;
1228   std::string output_image_relocation_directory;
1229   off_t base_delta = 0;
1230   bool base_delta_set = false;
1231   bool dump_timings = kIsDebugBuild;
1232   bool verify = false;
1233 
1234   for (int i = 0; i < argc; ++i) {
1235     const StringPiece option(argv[i]);
1236     const bool log_options = false;
1237     if (log_options) {
1238       LOG(INFO) << "patchoat: option[" << i << "]=" << argv[i];
1239     }
1240     if (option.starts_with("--instruction-set=")) {
1241       isa_set = true;
1242       const char* isa_str = option.substr(strlen("--instruction-set=")).data();
1243       isa = GetInstructionSetFromString(isa_str);
1244       if (isa == InstructionSet::kNone) {
1245         Usage("Unknown or invalid instruction set %s", isa_str);
1246       }
1247     } else if (option.starts_with("--input-image-location=")) {
1248       input_image_location = option.substr(strlen("--input-image-location=")).data();
1249     } else if (option.starts_with("--output-image-directory=")) {
1250       output_image_directory = option.substr(strlen("--output-image-directory=")).data();
1251     } else if (option.starts_with("--output-image-relocation-directory=")) {
1252       output_image_relocation_directory =
1253           option.substr(strlen("--output-image-relocation-directory=")).data();
1254     } else if (option.starts_with("--base-offset-delta=")) {
1255       const char* base_delta_str = option.substr(strlen("--base-offset-delta=")).data();
1256       base_delta_set = true;
1257       if (!ParseInt(base_delta_str, &base_delta)) {
1258         Usage("Failed to parse --base-offset-delta argument '%s' as an off_t", base_delta_str);
1259       }
1260     } else if (option == "--dump-timings") {
1261       dump_timings = true;
1262     } else if (option == "--no-dump-timings") {
1263       dump_timings = false;
1264     } else if (option == "--verify") {
1265       verify = true;
1266     } else {
1267       Usage("Unknown argument %s", option.data());
1268     }
1269   }
1270 
1271   // The instruction set is mandatory. This simplifies things...
1272   if (!isa_set) {
1273     Usage("Instruction set must be set.");
1274   }
1275 
1276   int ret;
1277   if (verify) {
1278     ret = patchoat_verify_image(timings,
1279                                 isa,
1280                                 input_image_location,
1281                                 output_image_directory);
1282   } else {
1283     ret = patchoat_patch_image(timings,
1284                                isa,
1285                                input_image_location,
1286                                output_image_directory,
1287                                output_image_relocation_directory,
1288                                base_delta,
1289                                base_delta_set,
1290                                debug);
1291   }
1292 
1293   timings.EndTiming();
1294   if (dump_timings) {
1295     LOG(INFO) << Dumpable<TimingLogger>(timings);
1296   }
1297 
1298   return ret;
1299 }
1300 
1301 }  // namespace art
1302 
main(int argc,char ** argv)1303 int main(int argc, char **argv) {
1304   return art::patchoat(argc, argv);
1305 }
1306