• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 <stdio.h>
19 #include <stdlib.h>
20 #include <sys/file.h>
21 #include <sys/stat.h>
22 #include <unistd.h>
23 
24 #include <string>
25 #include <vector>
26 
27 #include "art_field-inl.h"
28 #include "art_method-inl.h"
29 #include "base/dumpable.h"
30 #include "base/scoped_flock.h"
31 #include "base/stringpiece.h"
32 #include "base/stringprintf.h"
33 #include "base/unix_file/fd_file.h"
34 #include "elf_utils.h"
35 #include "elf_file.h"
36 #include "elf_file_impl.h"
37 #include "gc/space/image_space.h"
38 #include "image-inl.h"
39 #include "mirror/abstract_method.h"
40 #include "mirror/object-inl.h"
41 #include "mirror/method.h"
42 #include "mirror/reference.h"
43 #include "noop_compiler_callbacks.h"
44 #include "offsets.h"
45 #include "os.h"
46 #include "runtime.h"
47 #include "scoped_thread_state_change.h"
48 #include "thread.h"
49 #include "utils.h"
50 
51 namespace art {
52 
LocationToFilename(const std::string & location,InstructionSet isa,std::string * filename)53 static bool LocationToFilename(const std::string& location, InstructionSet isa,
54                                std::string* filename) {
55   bool has_system = false;
56   bool has_cache = false;
57   // image_location = /system/framework/boot.art
58   // system_image_filename = /system/framework/<image_isa>/boot.art
59   std::string system_filename(GetSystemImageFilename(location.c_str(), isa));
60   if (OS::FileExists(system_filename.c_str())) {
61     has_system = true;
62   }
63 
64   bool have_android_data = false;
65   bool dalvik_cache_exists = false;
66   bool is_global_cache = false;
67   std::string dalvik_cache;
68   GetDalvikCache(GetInstructionSetString(isa), false, &dalvik_cache,
69                  &have_android_data, &dalvik_cache_exists, &is_global_cache);
70 
71   std::string cache_filename;
72   if (have_android_data && dalvik_cache_exists) {
73     // Always set output location even if it does not exist,
74     // so that the caller knows where to create the image.
75     //
76     // image_location = /system/framework/boot.art
77     // *image_filename = /data/dalvik-cache/<image_isa>/boot.art
78     std::string error_msg;
79     if (GetDalvikCacheFilename(location.c_str(), dalvik_cache.c_str(),
80                                &cache_filename, &error_msg)) {
81       has_cache = true;
82     }
83   }
84   if (has_system) {
85     *filename = system_filename;
86     return true;
87   } else if (has_cache) {
88     *filename = cache_filename;
89     return true;
90   } else {
91     return false;
92   }
93 }
94 
GetOatHeader(const ElfFile * elf_file)95 static const OatHeader* GetOatHeader(const ElfFile* elf_file) {
96   uint64_t off = 0;
97   if (!elf_file->GetSectionOffsetAndSize(".rodata", &off, nullptr)) {
98     return nullptr;
99   }
100 
101   OatHeader* oat_header = reinterpret_cast<OatHeader*>(elf_file->Begin() + off);
102   return oat_header;
103 }
104 
105 // This function takes an elf file and reads the current patch delta value
106 // encoded in its oat header value
ReadOatPatchDelta(const ElfFile * elf_file,off_t * delta,std::string * error_msg)107 static bool ReadOatPatchDelta(const ElfFile* elf_file, off_t* delta, std::string* error_msg) {
108   const OatHeader* oat_header = GetOatHeader(elf_file);
109   if (oat_header == nullptr) {
110     *error_msg = "Unable to get oat header from elf file.";
111     return false;
112   }
113   if (!oat_header->IsValid()) {
114     *error_msg = "Elf file has an invalid oat header";
115     return false;
116   }
117   *delta = oat_header->GetImagePatchDelta();
118   return true;
119 }
120 
CreateOrOpen(const char * name,bool * created)121 static File* CreateOrOpen(const char* name, bool* created) {
122   if (OS::FileExists(name)) {
123     *created = false;
124     return OS::OpenFileReadWrite(name);
125   } else {
126     *created = true;
127     std::unique_ptr<File> f(OS::CreateEmptyFile(name));
128     if (f.get() != nullptr) {
129       if (fchmod(f->Fd(), 0644) != 0) {
130         PLOG(ERROR) << "Unable to make " << name << " world readable";
131         unlink(name);
132         return nullptr;
133       }
134     }
135     return f.release();
136   }
137 }
138 
139 // Either try to close the file (close=true), or erase it.
FinishFile(File * file,bool close)140 static bool FinishFile(File* file, bool close) {
141   if (close) {
142     if (file->FlushCloseOrErase() != 0) {
143       PLOG(ERROR) << "Failed to flush and close file.";
144       return false;
145     }
146     return true;
147   } else {
148     file->Erase();
149     return false;
150   }
151 }
152 
Patch(const std::string & image_location,off_t delta,const std::string & output_directory,InstructionSet isa,TimingLogger * timings)153 bool PatchOat::Patch(const std::string& image_location,
154                      off_t delta,
155                      const std::string& output_directory,
156                      InstructionSet isa,
157                      TimingLogger* timings) {
158   CHECK(Runtime::Current() == nullptr);
159   CHECK(!image_location.empty()) << "image file must have a filename.";
160 
161   TimingLogger::ScopedTiming t("Runtime Setup", timings);
162 
163   CHECK_NE(isa, kNone);
164   const char* isa_name = GetInstructionSetString(isa);
165 
166   // Set up the runtime
167   RuntimeOptions options;
168   NoopCompilerCallbacks callbacks;
169   options.push_back(std::make_pair("compilercallbacks", &callbacks));
170   std::string img = "-Ximage:" + image_location;
171   options.push_back(std::make_pair(img.c_str(), nullptr));
172   options.push_back(std::make_pair("imageinstructionset", reinterpret_cast<const void*>(isa_name)));
173   options.push_back(std::make_pair("-Xno-sig-chain", nullptr));
174   if (!Runtime::Create(options, false)) {
175     LOG(ERROR) << "Unable to initialize runtime";
176     return false;
177   }
178   // Runtime::Create acquired the mutator_lock_ that is normally given away when we Runtime::Start,
179   // give it away now and then switch to a more manageable ScopedObjectAccess.
180   Thread::Current()->TransitionFromRunnableToSuspended(kNative);
181   ScopedObjectAccess soa(Thread::Current());
182 
183   t.NewTiming("Image and oat Patching setup");
184   std::vector<gc::space::ImageSpace*> spaces = Runtime::Current()->GetHeap()->GetBootImageSpaces();
185   std::map<gc::space::ImageSpace*, std::unique_ptr<File>> space_to_file_map;
186   std::map<gc::space::ImageSpace*, std::unique_ptr<MemMap>> space_to_memmap_map;
187   std::map<gc::space::ImageSpace*, PatchOat> space_to_patchoat_map;
188   std::map<gc::space::ImageSpace*, bool> space_to_skip_patching_map;
189 
190   for (size_t i = 0; i < spaces.size(); ++i) {
191     gc::space::ImageSpace* space = spaces[i];
192     std::string input_image_filename = space->GetImageFilename();
193     std::unique_ptr<File> input_image(OS::OpenFileForReading(input_image_filename.c_str()));
194     if (input_image.get() == nullptr) {
195       LOG(ERROR) << "Unable to open input image file at " << input_image_filename;
196       return false;
197     }
198 
199     int64_t image_len = input_image->GetLength();
200     if (image_len < 0) {
201       LOG(ERROR) << "Error while getting image length";
202       return false;
203     }
204     ImageHeader image_header;
205     if (sizeof(image_header) != input_image->Read(reinterpret_cast<char*>(&image_header),
206                                                   sizeof(image_header), 0)) {
207       LOG(ERROR) << "Unable to read image header from image file " << input_image->GetPath();
208     }
209 
210     /*bool is_image_pic = */IsImagePic(image_header, input_image->GetPath());
211     // Nothing special to do right now since the image always needs to get patched.
212     // Perhaps in some far-off future we may have images with relative addresses that are true-PIC.
213 
214     // Create the map where we will write the image patches to.
215     std::string error_msg;
216     std::unique_ptr<MemMap> image(MemMap::MapFile(image_len,
217                                                   PROT_READ | PROT_WRITE,
218                                                   MAP_PRIVATE,
219                                                   input_image->Fd(),
220                                                   0,
221                                                   /*low_4gb*/false,
222                                                   input_image->GetPath().c_str(),
223                                                   &error_msg));
224     if (image.get() == nullptr) {
225       LOG(ERROR) << "Unable to map image file " << input_image->GetPath() << " : " << error_msg;
226       return false;
227     }
228     space_to_file_map.emplace(space, std::move(input_image));
229     space_to_memmap_map.emplace(space, std::move(image));
230   }
231 
232   for (size_t i = 0; i < spaces.size(); ++i) {
233     gc::space::ImageSpace* space = spaces[i];
234     std::string input_image_filename = space->GetImageFilename();
235     std::string input_oat_filename =
236         ImageHeader::GetOatLocationFromImageLocation(input_image_filename);
237     std::unique_ptr<File> input_oat_file(OS::OpenFileForReading(input_oat_filename.c_str()));
238     if (input_oat_file.get() == nullptr) {
239       LOG(ERROR) << "Unable to open input oat file at " << input_oat_filename;
240       return false;
241     }
242     std::string error_msg;
243     std::unique_ptr<ElfFile> elf(ElfFile::Open(input_oat_file.get(),
244                                                PROT_READ | PROT_WRITE, MAP_PRIVATE, &error_msg));
245     if (elf.get() == nullptr) {
246       LOG(ERROR) << "Unable to open oat file " << input_oat_file->GetPath() << " : " << error_msg;
247       return false;
248     }
249 
250     bool skip_patching_oat = false;
251     MaybePic is_oat_pic = IsOatPic(elf.get());
252     if (is_oat_pic >= ERROR_FIRST) {
253       // Error logged by IsOatPic
254       return false;
255     } else if (is_oat_pic == PIC) {
256       // Do not need to do ELF-file patching. Create a symlink and skip the ELF patching.
257 
258       std::string converted_image_filename = space->GetImageLocation();
259       std::replace(converted_image_filename.begin() + 1, converted_image_filename.end(), '/', '@');
260       std::string output_image_filename = output_directory +
261                                           (StartsWith(converted_image_filename, "/") ? "" : "/") +
262                                           converted_image_filename;
263       std::string output_oat_filename =
264           ImageHeader::GetOatLocationFromImageLocation(output_image_filename);
265 
266       if (!ReplaceOatFileWithSymlink(input_oat_file->GetPath(),
267                                      output_oat_filename,
268                                      false,
269                                      true)) {
270         // Errors already logged by above call.
271         return false;
272       }
273       // Don't patch the OAT, since we just symlinked it. Image still needs patching.
274       skip_patching_oat = true;
275     } else {
276       CHECK(is_oat_pic == NOT_PIC);
277     }
278 
279     PatchOat& p = space_to_patchoat_map.emplace(space,
280                                                 PatchOat(
281                                                     isa,
282                                                     elf.release(),
283                                                     space_to_memmap_map.find(space)->second.get(),
284                                                     space->GetLiveBitmap(),
285                                                     space->GetMemMap(),
286                                                     delta,
287                                                     &space_to_memmap_map,
288                                                     timings)).first->second;
289 
290     t.NewTiming("Patching files");
291     if (!skip_patching_oat && !p.PatchElf()) {
292       LOG(ERROR) << "Failed to patch oat file " << input_oat_file->GetPath();
293       return false;
294     }
295     if (!p.PatchImage(i == 0)) {
296       LOG(ERROR) << "Failed to patch image file " << input_image_filename;
297       return false;
298     }
299 
300     space_to_skip_patching_map.emplace(space, skip_patching_oat);
301   }
302 
303   for (size_t i = 0; i < spaces.size(); ++i) {
304     gc::space::ImageSpace* space = spaces[i];
305     std::string input_image_filename = space->GetImageFilename();
306 
307     t.NewTiming("Writing files");
308     std::string converted_image_filename = space->GetImageLocation();
309     std::replace(converted_image_filename.begin() + 1, converted_image_filename.end(), '/', '@');
310     std::string output_image_filename = output_directory +
311                                         (StartsWith(converted_image_filename, "/") ? "" : "/") +
312                                         converted_image_filename;
313     bool new_oat_out;
314     std::unique_ptr<File>
315         output_image_file(CreateOrOpen(output_image_filename.c_str(), &new_oat_out));
316     if (output_image_file.get() == nullptr) {
317       LOG(ERROR) << "Failed to open output image file at " << output_image_filename;
318       return false;
319     }
320 
321     PatchOat& p = space_to_patchoat_map.find(space)->second;
322 
323     bool success = p.WriteImage(output_image_file.get());
324     success = FinishFile(output_image_file.get(), success);
325     if (!success) {
326       return false;
327     }
328 
329     bool skip_patching_oat = space_to_skip_patching_map.find(space)->second;
330     if (!skip_patching_oat) {
331       std::string output_oat_filename =
332           ImageHeader::GetOatLocationFromImageLocation(output_image_filename);
333       std::unique_ptr<File>
334           output_oat_file(CreateOrOpen(output_oat_filename.c_str(), &new_oat_out));
335       if (output_oat_file.get() == nullptr) {
336         LOG(ERROR) << "Failed to open output oat file at " << output_oat_filename;
337         return false;
338       }
339       success = p.WriteElf(output_oat_file.get());
340       success = FinishFile(output_oat_file.get(), success);
341       if (!success) {
342         return false;
343       }
344     }
345   }
346   return true;
347 }
348 
WriteElf(File * out)349 bool PatchOat::WriteElf(File* out) {
350   TimingLogger::ScopedTiming t("Writing Elf File", timings_);
351 
352   CHECK(oat_file_.get() != nullptr);
353   CHECK(out != nullptr);
354   size_t expect = oat_file_->Size();
355   if (out->WriteFully(reinterpret_cast<char*>(oat_file_->Begin()), expect) &&
356       out->SetLength(expect) == 0) {
357     return true;
358   } else {
359     LOG(ERROR) << "Writing to oat file " << out->GetPath() << " failed.";
360     return false;
361   }
362 }
363 
WriteImage(File * out)364 bool PatchOat::WriteImage(File* out) {
365   TimingLogger::ScopedTiming t("Writing image File", timings_);
366   std::string error_msg;
367 
368   ScopedFlock img_flock;
369   img_flock.Init(out, &error_msg);
370 
371   CHECK(image_ != nullptr);
372   CHECK(out != nullptr);
373   size_t expect = image_->Size();
374   if (out->WriteFully(reinterpret_cast<char*>(image_->Begin()), expect) &&
375       out->SetLength(expect) == 0) {
376     return true;
377   } else {
378     LOG(ERROR) << "Writing to image file " << out->GetPath() << " failed.";
379     return false;
380   }
381 }
382 
IsImagePic(const ImageHeader & image_header,const std::string & image_path)383 bool PatchOat::IsImagePic(const ImageHeader& image_header, const std::string& image_path) {
384   if (!image_header.CompilePic()) {
385     if (kIsDebugBuild) {
386       LOG(INFO) << "image at location " << image_path << " was *not* compiled pic";
387     }
388     return false;
389   }
390 
391   if (kIsDebugBuild) {
392     LOG(INFO) << "image at location " << image_path << " was compiled PIC";
393   }
394 
395   return true;
396 }
397 
IsOatPic(const ElfFile * oat_in)398 PatchOat::MaybePic PatchOat::IsOatPic(const ElfFile* oat_in) {
399   if (oat_in == nullptr) {
400     LOG(ERROR) << "No ELF input oat fie available";
401     return ERROR_OAT_FILE;
402   }
403 
404   const std::string& file_path = oat_in->GetFile().GetPath();
405 
406   const OatHeader* oat_header = GetOatHeader(oat_in);
407   if (oat_header == nullptr) {
408     LOG(ERROR) << "Failed to find oat header in oat file " << file_path;
409     return ERROR_OAT_FILE;
410   }
411 
412   if (!oat_header->IsValid()) {
413     LOG(ERROR) << "Elf file " << file_path << " has an invalid oat header";
414     return ERROR_OAT_FILE;
415   }
416 
417   bool is_pic = oat_header->IsPic();
418   if (kIsDebugBuild) {
419     LOG(INFO) << "Oat file at " << file_path << " is " << (is_pic ? "PIC" : "not pic");
420   }
421 
422   return is_pic ? PIC : NOT_PIC;
423 }
424 
ReplaceOatFileWithSymlink(const std::string & input_oat_filename,const std::string & output_oat_filename,bool output_oat_opened_from_fd,bool new_oat_out)425 bool PatchOat::ReplaceOatFileWithSymlink(const std::string& input_oat_filename,
426                                          const std::string& output_oat_filename,
427                                          bool output_oat_opened_from_fd,
428                                          bool new_oat_out) {
429   // Need a file when we are PIC, since we symlink over it. Refusing to symlink into FD.
430   if (output_oat_opened_from_fd) {
431     // TODO: installd uses --output-oat-fd. Should we change class linking logic for PIC?
432     LOG(ERROR) << "No output oat filename specified, needs filename for when we are PIC";
433     return false;
434   }
435 
436   // Image was PIC. Create symlink where the oat is supposed to go.
437   if (!new_oat_out) {
438     LOG(ERROR) << "Oat file " << output_oat_filename << " already exists, refusing to overwrite";
439     return false;
440   }
441 
442   // Delete the original file, since we won't need it.
443   unlink(output_oat_filename.c_str());
444 
445   // Create a symlink from the old oat to the new oat
446   if (symlink(input_oat_filename.c_str(), output_oat_filename.c_str()) < 0) {
447     int err = errno;
448     LOG(ERROR) << "Failed to create symlink at " << output_oat_filename
449                << " error(" << err << "): " << strerror(err);
450     return false;
451   }
452 
453   if (kIsDebugBuild) {
454     LOG(INFO) << "Created symlink " << output_oat_filename << " -> " << input_oat_filename;
455   }
456 
457   return true;
458 }
459 
460 class PatchOatArtFieldVisitor : public ArtFieldVisitor {
461  public:
PatchOatArtFieldVisitor(PatchOat * patch_oat)462   explicit PatchOatArtFieldVisitor(PatchOat* patch_oat) : patch_oat_(patch_oat) {}
463 
Visit(ArtField * field)464   void Visit(ArtField* field) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
465     ArtField* const dest = patch_oat_->RelocatedCopyOf(field);
466     dest->SetDeclaringClass(patch_oat_->RelocatedAddressOfPointer(field->GetDeclaringClass()));
467   }
468 
469  private:
470   PatchOat* const patch_oat_;
471 };
472 
PatchArtFields(const ImageHeader * image_header)473 void PatchOat::PatchArtFields(const ImageHeader* image_header) {
474   PatchOatArtFieldVisitor visitor(this);
475   image_header->VisitPackedArtFields(&visitor, heap_->Begin());
476 }
477 
478 class PatchOatArtMethodVisitor : public ArtMethodVisitor {
479  public:
PatchOatArtMethodVisitor(PatchOat * patch_oat)480   explicit PatchOatArtMethodVisitor(PatchOat* patch_oat) : patch_oat_(patch_oat) {}
481 
Visit(ArtMethod * method)482   void Visit(ArtMethod* method) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
483     ArtMethod* const dest = patch_oat_->RelocatedCopyOf(method);
484     patch_oat_->FixupMethod(method, dest);
485   }
486 
487  private:
488   PatchOat* const patch_oat_;
489 };
490 
PatchArtMethods(const ImageHeader * image_header)491 void PatchOat::PatchArtMethods(const ImageHeader* image_header) {
492   const size_t pointer_size = InstructionSetPointerSize(isa_);
493   PatchOatArtMethodVisitor visitor(this);
494   image_header->VisitPackedArtMethods(&visitor, heap_->Begin(), pointer_size);
495 }
496 
PatchImTables(const ImageHeader * image_header)497 void PatchOat::PatchImTables(const ImageHeader* image_header) {
498   const size_t pointer_size = InstructionSetPointerSize(isa_);
499   // We can safely walk target image since the conflict tables are independent.
500   image_header->VisitPackedImTables(
501       [this](ArtMethod* method) {
502         return RelocatedAddressOfPointer(method);
503       },
504       image_->Begin(),
505       pointer_size);
506 }
507 
PatchImtConflictTables(const ImageHeader * image_header)508 void PatchOat::PatchImtConflictTables(const ImageHeader* image_header) {
509   const size_t pointer_size = InstructionSetPointerSize(isa_);
510   // We can safely walk target image since the conflict tables are independent.
511   image_header->VisitPackedImtConflictTables(
512       [this](ArtMethod* method) {
513         return RelocatedAddressOfPointer(method);
514       },
515       image_->Begin(),
516       pointer_size);
517 }
518 
519 class FixupRootVisitor : public RootVisitor {
520  public:
FixupRootVisitor(const PatchOat * patch_oat)521   explicit FixupRootVisitor(const PatchOat* patch_oat) : patch_oat_(patch_oat) {
522   }
523 
VisitRoots(mirror::Object *** roots,size_t count,const RootInfo & info ATTRIBUTE_UNUSED)524   void VisitRoots(mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED)
525       OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
526     for (size_t i = 0; i < count; ++i) {
527       *roots[i] = patch_oat_->RelocatedAddressOfPointer(*roots[i]);
528     }
529   }
530 
VisitRoots(mirror::CompressedReference<mirror::Object> ** roots,size_t count,const RootInfo & info ATTRIBUTE_UNUSED)531   void VisitRoots(mirror::CompressedReference<mirror::Object>** roots, size_t count,
532                   const RootInfo& info ATTRIBUTE_UNUSED)
533       OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
534     for (size_t i = 0; i < count; ++i) {
535       roots[i]->Assign(patch_oat_->RelocatedAddressOfPointer(roots[i]->AsMirrorPtr()));
536     }
537   }
538 
539  private:
540   const PatchOat* const patch_oat_;
541 };
542 
PatchInternedStrings(const ImageHeader * image_header)543 void PatchOat::PatchInternedStrings(const ImageHeader* image_header) {
544   const auto& section = image_header->GetImageSection(ImageHeader::kSectionInternedStrings);
545   InternTable temp_table;
546   // Note that we require that ReadFromMemory does not make an internal copy of the elements.
547   // This also relies on visit roots not doing any verification which could fail after we update
548   // the roots to be the image addresses.
549   temp_table.AddTableFromMemory(image_->Begin() + section.Offset());
550   FixupRootVisitor visitor(this);
551   temp_table.VisitRoots(&visitor, kVisitRootFlagAllRoots);
552 }
553 
PatchClassTable(const ImageHeader * image_header)554 void PatchOat::PatchClassTable(const ImageHeader* image_header) {
555   const auto& section = image_header->GetImageSection(ImageHeader::kSectionClassTable);
556   if (section.Size() == 0) {
557     return;
558   }
559   // Note that we require that ReadFromMemory does not make an internal copy of the elements.
560   // This also relies on visit roots not doing any verification which could fail after we update
561   // the roots to be the image addresses.
562   WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
563   ClassTable temp_table;
564   temp_table.ReadFromMemory(image_->Begin() + section.Offset());
565   FixupRootVisitor visitor(this);
566   BufferedRootVisitor<kDefaultBufferedRootCount> buffered_visitor(&visitor, RootInfo(kRootUnknown));
567   temp_table.VisitRoots(buffered_visitor);
568 }
569 
570 
571 class RelocatedPointerVisitor {
572  public:
RelocatedPointerVisitor(PatchOat * patch_oat)573   explicit RelocatedPointerVisitor(PatchOat* patch_oat) : patch_oat_(patch_oat) {}
574 
575   template <typename T>
operator ()(T * ptr) const576   T* operator()(T* ptr) const {
577     return patch_oat_->RelocatedAddressOfPointer(ptr);
578   }
579 
580  private:
581   PatchOat* const patch_oat_;
582 };
583 
PatchDexFileArrays(mirror::ObjectArray<mirror::Object> * img_roots)584 void PatchOat::PatchDexFileArrays(mirror::ObjectArray<mirror::Object>* img_roots) {
585   auto* dex_caches = down_cast<mirror::ObjectArray<mirror::DexCache>*>(
586       img_roots->Get(ImageHeader::kDexCaches));
587   const size_t pointer_size = InstructionSetPointerSize(isa_);
588   for (size_t i = 0, count = dex_caches->GetLength(); i < count; ++i) {
589     auto* orig_dex_cache = dex_caches->GetWithoutChecks(i);
590     auto* copy_dex_cache = RelocatedCopyOf(orig_dex_cache);
591     // Though the DexCache array fields are usually treated as native pointers, we set the full
592     // 64-bit values here, clearing the top 32 bits for 32-bit targets. The zero-extension is
593     // done by casting to the unsigned type uintptr_t before casting to int64_t, i.e.
594     //     static_cast<int64_t>(reinterpret_cast<uintptr_t>(image_begin_ + offset))).
595     GcRoot<mirror::String>* orig_strings = orig_dex_cache->GetStrings();
596     GcRoot<mirror::String>* relocated_strings = RelocatedAddressOfPointer(orig_strings);
597     copy_dex_cache->SetField64<false>(
598         mirror::DexCache::StringsOffset(),
599         static_cast<int64_t>(reinterpret_cast<uintptr_t>(relocated_strings)));
600     if (orig_strings != nullptr) {
601       orig_dex_cache->FixupStrings(RelocatedCopyOf(orig_strings), RelocatedPointerVisitor(this));
602     }
603     GcRoot<mirror::Class>* orig_types = orig_dex_cache->GetResolvedTypes();
604     GcRoot<mirror::Class>* relocated_types = RelocatedAddressOfPointer(orig_types);
605     copy_dex_cache->SetField64<false>(
606         mirror::DexCache::ResolvedTypesOffset(),
607         static_cast<int64_t>(reinterpret_cast<uintptr_t>(relocated_types)));
608     if (orig_types != nullptr) {
609       orig_dex_cache->FixupResolvedTypes(RelocatedCopyOf(orig_types),
610                                          RelocatedPointerVisitor(this));
611     }
612     ArtMethod** orig_methods = orig_dex_cache->GetResolvedMethods();
613     ArtMethod** relocated_methods = RelocatedAddressOfPointer(orig_methods);
614     copy_dex_cache->SetField64<false>(
615         mirror::DexCache::ResolvedMethodsOffset(),
616         static_cast<int64_t>(reinterpret_cast<uintptr_t>(relocated_methods)));
617     if (orig_methods != nullptr) {
618       ArtMethod** copy_methods = RelocatedCopyOf(orig_methods);
619       for (size_t j = 0, num = orig_dex_cache->NumResolvedMethods(); j != num; ++j) {
620         ArtMethod* orig = mirror::DexCache::GetElementPtrSize(orig_methods, j, pointer_size);
621         ArtMethod* copy = RelocatedAddressOfPointer(orig);
622         mirror::DexCache::SetElementPtrSize(copy_methods, j, copy, pointer_size);
623       }
624     }
625     ArtField** orig_fields = orig_dex_cache->GetResolvedFields();
626     ArtField** relocated_fields = RelocatedAddressOfPointer(orig_fields);
627     copy_dex_cache->SetField64<false>(
628         mirror::DexCache::ResolvedFieldsOffset(),
629         static_cast<int64_t>(reinterpret_cast<uintptr_t>(relocated_fields)));
630     if (orig_fields != nullptr) {
631       ArtField** copy_fields = RelocatedCopyOf(orig_fields);
632       for (size_t j = 0, num = orig_dex_cache->NumResolvedFields(); j != num; ++j) {
633         ArtField* orig = mirror::DexCache::GetElementPtrSize(orig_fields, j, pointer_size);
634         ArtField* copy = RelocatedAddressOfPointer(orig);
635         mirror::DexCache::SetElementPtrSize(copy_fields, j, copy, pointer_size);
636       }
637     }
638   }
639 }
640 
PatchImage(bool primary_image)641 bool PatchOat::PatchImage(bool primary_image) {
642   ImageHeader* image_header = reinterpret_cast<ImageHeader*>(image_->Begin());
643   CHECK_GT(image_->Size(), sizeof(ImageHeader));
644   // These are the roots from the original file.
645   auto* img_roots = image_header->GetImageRoots();
646   image_header->RelocateImage(delta_);
647 
648   PatchArtFields(image_header);
649   PatchArtMethods(image_header);
650   PatchImTables(image_header);
651   PatchImtConflictTables(image_header);
652   PatchInternedStrings(image_header);
653   PatchClassTable(image_header);
654   // Patch dex file int/long arrays which point to ArtFields.
655   PatchDexFileArrays(img_roots);
656 
657   if (primary_image) {
658     VisitObject(img_roots);
659   }
660 
661   if (!image_header->IsValid()) {
662     LOG(ERROR) << "relocation renders image header invalid";
663     return false;
664   }
665 
666   {
667     TimingLogger::ScopedTiming t("Walk Bitmap", timings_);
668     // Walk the bitmap.
669     WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
670     bitmap_->Walk(PatchOat::BitmapCallback, this);
671   }
672   return true;
673 }
674 
675 
operator ()(mirror::Object * obj,MemberOffset off,bool is_static_unused ATTRIBUTE_UNUSED) const676 void PatchOat::PatchVisitor::operator() (mirror::Object* obj, MemberOffset off,
677                                          bool is_static_unused ATTRIBUTE_UNUSED) const {
678   mirror::Object* referent = obj->GetFieldObject<mirror::Object, kVerifyNone>(off);
679   mirror::Object* moved_object = patcher_->RelocatedAddressOfPointer(referent);
680   copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(off, moved_object);
681 }
682 
operator ()(mirror::Class * cls ATTRIBUTE_UNUSED,mirror::Reference * ref) const683 void PatchOat::PatchVisitor::operator() (mirror::Class* cls ATTRIBUTE_UNUSED,
684                                          mirror::Reference* ref) const {
685   MemberOffset off = mirror::Reference::ReferentOffset();
686   mirror::Object* referent = ref->GetReferent();
687   DCHECK(referent == nullptr ||
688          Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(referent)) << referent;
689   mirror::Object* moved_object = patcher_->RelocatedAddressOfPointer(referent);
690   copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(off, moved_object);
691 }
692 
693 // Called by BitmapCallback
VisitObject(mirror::Object * object)694 void PatchOat::VisitObject(mirror::Object* object) {
695   mirror::Object* copy = RelocatedCopyOf(object);
696   CHECK(copy != nullptr);
697   if (kUseBakerOrBrooksReadBarrier) {
698     object->AssertReadBarrierPointer();
699     if (kUseBrooksReadBarrier) {
700       mirror::Object* moved_to = RelocatedAddressOfPointer(object);
701       copy->SetReadBarrierPointer(moved_to);
702       DCHECK_EQ(copy->GetReadBarrierPointer(), moved_to);
703     }
704   }
705   PatchOat::PatchVisitor visitor(this, copy);
706   object->VisitReferences<kVerifyNone>(visitor, visitor);
707   if (object->IsClass<kVerifyNone>()) {
708     const size_t pointer_size = InstructionSetPointerSize(isa_);
709     mirror::Class* klass = object->AsClass();
710     mirror::Class* copy_klass = down_cast<mirror::Class*>(copy);
711     RelocatedPointerVisitor native_visitor(this);
712     klass->FixupNativePointers(copy_klass, pointer_size, native_visitor);
713     auto* vtable = klass->GetVTable();
714     if (vtable != nullptr) {
715       vtable->Fixup(RelocatedCopyOfFollowImages(vtable), pointer_size, native_visitor);
716     }
717     auto* iftable = klass->GetIfTable();
718     if (iftable != nullptr) {
719       for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
720         if (iftable->GetMethodArrayCount(i) > 0) {
721           auto* method_array = iftable->GetMethodArray(i);
722           CHECK(method_array != nullptr);
723           method_array->Fixup(RelocatedCopyOfFollowImages(method_array),
724                               pointer_size,
725                               native_visitor);
726         }
727       }
728     }
729   } else if (object->GetClass() == mirror::Method::StaticClass() ||
730              object->GetClass() == mirror::Constructor::StaticClass()) {
731     // Need to go update the ArtMethod.
732     auto* dest = down_cast<mirror::AbstractMethod*>(copy);
733     auto* src = down_cast<mirror::AbstractMethod*>(object);
734     dest->SetArtMethod(RelocatedAddressOfPointer(src->GetArtMethod()));
735   }
736 }
737 
FixupMethod(ArtMethod * object,ArtMethod * copy)738 void PatchOat::FixupMethod(ArtMethod* object, ArtMethod* copy) {
739   const size_t pointer_size = InstructionSetPointerSize(isa_);
740   copy->CopyFrom(object, pointer_size);
741   // Just update the entry points if it looks like we should.
742   // TODO: sanity check all the pointers' values
743   copy->SetDeclaringClass(RelocatedAddressOfPointer(object->GetDeclaringClass()));
744   copy->SetDexCacheResolvedMethods(
745       RelocatedAddressOfPointer(object->GetDexCacheResolvedMethods(pointer_size)), pointer_size);
746   copy->SetDexCacheResolvedTypes(
747       RelocatedAddressOfPointer(object->GetDexCacheResolvedTypes(pointer_size)), pointer_size);
748   copy->SetEntryPointFromQuickCompiledCodePtrSize(RelocatedAddressOfPointer(
749       object->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size)), pointer_size);
750   // No special handling for IMT conflict table since all pointers are moved by the same offset.
751   copy->SetEntryPointFromJniPtrSize(RelocatedAddressOfPointer(
752       object->GetEntryPointFromJniPtrSize(pointer_size)), pointer_size);
753 }
754 
Patch(File * input_oat,off_t delta,File * output_oat,TimingLogger * timings,bool output_oat_opened_from_fd,bool new_oat_out)755 bool PatchOat::Patch(File* input_oat, off_t delta, File* output_oat, TimingLogger* timings,
756                      bool output_oat_opened_from_fd, bool new_oat_out) {
757   CHECK(input_oat != nullptr);
758   CHECK(output_oat != nullptr);
759   CHECK_GE(input_oat->Fd(), 0);
760   CHECK_GE(output_oat->Fd(), 0);
761   TimingLogger::ScopedTiming t("Setup Oat File Patching", timings);
762 
763   std::string error_msg;
764   std::unique_ptr<ElfFile> elf(ElfFile::Open(input_oat,
765                                              PROT_READ | PROT_WRITE, MAP_PRIVATE, &error_msg));
766   if (elf.get() == nullptr) {
767     LOG(ERROR) << "unable to open oat file " << input_oat->GetPath() << " : " << error_msg;
768     return false;
769   }
770 
771   MaybePic is_oat_pic = IsOatPic(elf.get());
772   if (is_oat_pic >= ERROR_FIRST) {
773     // Error logged by IsOatPic
774     return false;
775   } else if (is_oat_pic == PIC) {
776     // Do not need to do ELF-file patching. Create a symlink and skip the rest.
777     // Any errors will be logged by the function call.
778     return ReplaceOatFileWithSymlink(input_oat->GetPath(),
779                                      output_oat->GetPath(),
780                                      output_oat_opened_from_fd,
781                                      new_oat_out);
782   } else {
783     CHECK(is_oat_pic == NOT_PIC);
784   }
785 
786   PatchOat p(elf.release(), delta, timings);
787   t.NewTiming("Patch Oat file");
788   if (!p.PatchElf()) {
789     return false;
790   }
791 
792   t.NewTiming("Writing oat file");
793   if (!p.WriteElf(output_oat)) {
794     return false;
795   }
796   return true;
797 }
798 
799 template <typename ElfFileImpl>
PatchOatHeader(ElfFileImpl * oat_file)800 bool PatchOat::PatchOatHeader(ElfFileImpl* oat_file) {
801   auto rodata_sec = oat_file->FindSectionByName(".rodata");
802   if (rodata_sec == nullptr) {
803     return false;
804   }
805   OatHeader* oat_header = reinterpret_cast<OatHeader*>(oat_file->Begin() + rodata_sec->sh_offset);
806   if (!oat_header->IsValid()) {
807     LOG(ERROR) << "Elf file " << oat_file->GetFile().GetPath() << " has an invalid oat header";
808     return false;
809   }
810   oat_header->RelocateOat(delta_);
811   return true;
812 }
813 
PatchElf()814 bool PatchOat::PatchElf() {
815   if (oat_file_->Is64Bit())
816     return PatchElf<ElfFileImpl64>(oat_file_->GetImpl64());
817   else
818     return PatchElf<ElfFileImpl32>(oat_file_->GetImpl32());
819 }
820 
821 template <typename ElfFileImpl>
PatchElf(ElfFileImpl * oat_file)822 bool PatchOat::PatchElf(ElfFileImpl* oat_file) {
823   TimingLogger::ScopedTiming t("Fixup Elf Text Section", timings_);
824 
825   // Fix up absolute references to locations within the boot image.
826   if (!oat_file->ApplyOatPatchesTo(".text", delta_)) {
827     return false;
828   }
829 
830   // Update the OatHeader fields referencing the boot image.
831   if (!PatchOatHeader<ElfFileImpl>(oat_file)) {
832     return false;
833   }
834 
835   bool need_boot_oat_fixup = true;
836   for (unsigned int i = 0; i < oat_file->GetProgramHeaderNum(); ++i) {
837     auto hdr = oat_file->GetProgramHeader(i);
838     if (hdr->p_type == PT_LOAD && hdr->p_vaddr == 0u) {
839       need_boot_oat_fixup = false;
840       break;
841     }
842   }
843   if (!need_boot_oat_fixup) {
844     // This is an app oat file that can be loaded at an arbitrary address in memory.
845     // Boot image references were patched above and there's nothing else to do.
846     return true;
847   }
848 
849   // This is a boot oat file that's loaded at a particular address and we need
850   // to patch all absolute addresses, starting with ELF program headers.
851 
852   t.NewTiming("Fixup Elf Headers");
853   // Fixup Phdr's
854   oat_file->FixupProgramHeaders(delta_);
855 
856   t.NewTiming("Fixup Section Headers");
857   // Fixup Shdr's
858   oat_file->FixupSectionHeaders(delta_);
859 
860   t.NewTiming("Fixup Dynamics");
861   oat_file->FixupDynamic(delta_);
862 
863   t.NewTiming("Fixup Elf Symbols");
864   // Fixup dynsym
865   if (!oat_file->FixupSymbols(delta_, true)) {
866     return false;
867   }
868   // Fixup symtab
869   if (!oat_file->FixupSymbols(delta_, false)) {
870     return false;
871   }
872 
873   t.NewTiming("Fixup Debug Sections");
874   if (!oat_file->FixupDebugSections(delta_)) {
875     return false;
876   }
877 
878   return true;
879 }
880 
881 static int orig_argc;
882 static char** orig_argv;
883 
CommandLine()884 static std::string CommandLine() {
885   std::vector<std::string> command;
886   for (int i = 0; i < orig_argc; ++i) {
887     command.push_back(orig_argv[i]);
888   }
889   return Join(command, ' ');
890 }
891 
UsageErrorV(const char * fmt,va_list ap)892 static void UsageErrorV(const char* fmt, va_list ap) {
893   std::string error;
894   StringAppendV(&error, fmt, ap);
895   LOG(ERROR) << error;
896 }
897 
UsageError(const char * fmt,...)898 static void UsageError(const char* fmt, ...) {
899   va_list ap;
900   va_start(ap, fmt);
901   UsageErrorV(fmt, ap);
902   va_end(ap);
903 }
904 
Usage(const char * fmt,...)905 NO_RETURN static void Usage(const char *fmt, ...) {
906   va_list ap;
907   va_start(ap, fmt);
908   UsageErrorV(fmt, ap);
909   va_end(ap);
910 
911   UsageError("Command: %s", CommandLine().c_str());
912   UsageError("Usage: patchoat [options]...");
913   UsageError("");
914   UsageError("  --instruction-set=<isa>: Specifies the instruction set the patched code is");
915   UsageError("      compiled for. Required if you use --input-oat-location");
916   UsageError("");
917   UsageError("  --input-oat-file=<file.oat>: Specifies the exact filename of the oat file to be");
918   UsageError("      patched.");
919   UsageError("");
920   UsageError("  --input-oat-fd=<file-descriptor>: Specifies the file-descriptor of the oat file");
921   UsageError("      to be patched.");
922   UsageError("");
923   UsageError("  --input-oat-location=<file.oat>: Specifies the 'location' to read the patched");
924   UsageError("      oat file from. If used one must also supply the --instruction-set");
925   UsageError("");
926   UsageError("  --input-image-location=<file.art>: Specifies the 'location' of the image file to");
927   UsageError("      be patched. If --instruction-set is not given it will use the instruction set");
928   UsageError("      extracted from the --input-oat-file.");
929   UsageError("");
930   UsageError("  --output-oat-file=<file.oat>: Specifies the exact file to write the patched oat");
931   UsageError("      file to.");
932   UsageError("");
933   UsageError("  --output-oat-fd=<file-descriptor>: Specifies the file-descriptor to write the");
934   UsageError("      the patched oat file to.");
935   UsageError("");
936   UsageError("  --output-image-file=<file.art>: Specifies the exact file to write the patched");
937   UsageError("      image file to.");
938   UsageError("");
939   UsageError("  --base-offset-delta=<delta>: Specify the amount to change the old base-offset by.");
940   UsageError("      This value may be negative.");
941   UsageError("");
942   UsageError("  --patched-image-location=<file.art>: Relocate the oat file to be the same as the");
943   UsageError("      image at the given location. If used one must also specify the");
944   UsageError("      --instruction-set flag. It will search for this image in the same way that");
945   UsageError("      is done when loading one.");
946   UsageError("");
947   UsageError("  --lock-output: Obtain a flock on output oat file before starting.");
948   UsageError("");
949   UsageError("  --no-lock-output: Do not attempt to obtain a flock on output oat file.");
950   UsageError("");
951   UsageError("  --dump-timings: dump out patch timing information");
952   UsageError("");
953   UsageError("  --no-dump-timings: do not dump out patch timing information");
954   UsageError("");
955 
956   exit(EXIT_FAILURE);
957 }
958 
ReadBaseDelta(const char * name,off_t * delta,std::string * error_msg)959 static bool ReadBaseDelta(const char* name, off_t* delta, std::string* error_msg) {
960   CHECK(name != nullptr);
961   CHECK(delta != nullptr);
962   std::unique_ptr<File> file;
963   if (OS::FileExists(name)) {
964     file.reset(OS::OpenFileForReading(name));
965     if (file.get() == nullptr) {
966       *error_msg = "Failed to open file %s for reading";
967       return false;
968     }
969   } else {
970     *error_msg = "File %s does not exist";
971     return false;
972   }
973   CHECK(file.get() != nullptr);
974   ImageHeader hdr;
975   if (sizeof(hdr) != file->Read(reinterpret_cast<char*>(&hdr), sizeof(hdr), 0)) {
976     *error_msg = "Failed to read file %s";
977     return false;
978   }
979   if (!hdr.IsValid()) {
980     *error_msg = "%s does not contain a valid image header.";
981     return false;
982   }
983   *delta = hdr.GetPatchDelta();
984   return true;
985 }
986 
patchoat_image(TimingLogger & timings,InstructionSet isa,const std::string & input_image_location,const std::string & output_image_filename,off_t base_delta,bool base_delta_set,bool debug)987 static int patchoat_image(TimingLogger& timings,
988                           InstructionSet isa,
989                           const std::string& input_image_location,
990                           const std::string& output_image_filename,
991                           off_t base_delta,
992                           bool base_delta_set,
993                           bool debug) {
994   CHECK(!input_image_location.empty());
995   if (output_image_filename.empty()) {
996     Usage("Image patching requires --output-image-file");
997   }
998 
999   if (!base_delta_set) {
1000     Usage("Must supply a desired new offset or delta.");
1001   }
1002 
1003   if (!IsAligned<kPageSize>(base_delta)) {
1004     Usage("Base offset/delta must be aligned to a pagesize (0x%08x) boundary.", kPageSize);
1005   }
1006 
1007   if (debug) {
1008     LOG(INFO) << "moving offset by " << base_delta
1009         << " (0x" << std::hex << base_delta << ") bytes or "
1010         << std::dec << (base_delta/kPageSize) << " pages.";
1011   }
1012 
1013   TimingLogger::ScopedTiming pt("patch image and oat", &timings);
1014 
1015   std::string output_directory =
1016       output_image_filename.substr(0, output_image_filename.find_last_of("/"));
1017   bool ret = PatchOat::Patch(input_image_location, base_delta, output_directory, isa, &timings);
1018 
1019   if (kIsDebugBuild) {
1020     LOG(INFO) << "Exiting with return ... " << ret;
1021   }
1022   return ret ? EXIT_SUCCESS : EXIT_FAILURE;
1023 }
1024 
patchoat_oat(TimingLogger & timings,InstructionSet isa,const std::string & patched_image_location,off_t base_delta,bool base_delta_set,int input_oat_fd,const std::string & input_oat_location,std::string input_oat_filename,bool have_input_oat,int output_oat_fd,std::string output_oat_filename,bool have_output_oat,bool lock_output,bool debug)1025 static int patchoat_oat(TimingLogger& timings,
1026                         InstructionSet isa,
1027                         const std::string& patched_image_location,
1028                         off_t base_delta,
1029                         bool base_delta_set,
1030                         int input_oat_fd,
1031                         const std::string& input_oat_location,
1032                         std::string input_oat_filename,
1033                         bool have_input_oat,
1034                         int output_oat_fd,
1035                         std::string output_oat_filename,
1036                         bool have_output_oat,
1037                         bool lock_output,
1038                         bool debug) {
1039   {
1040     // Only 1 of these may be set.
1041     uint32_t cnt = 0;
1042     cnt += (base_delta_set) ? 1 : 0;
1043     cnt += (!patched_image_location.empty()) ? 1 : 0;
1044     if (cnt > 1) {
1045       Usage("Only one of --base-offset-delta or --patched-image-location may be used.");
1046     } else if (cnt == 0) {
1047       Usage("Must specify --base-offset-delta or --patched-image-location.");
1048     }
1049   }
1050 
1051   if (!have_input_oat || !have_output_oat) {
1052     Usage("Both input and output oat must be supplied to patch an app odex.");
1053   }
1054 
1055   if (!input_oat_location.empty()) {
1056     if (!LocationToFilename(input_oat_location, isa, &input_oat_filename)) {
1057       Usage("Unable to find filename for input oat location %s", input_oat_location.c_str());
1058     }
1059     if (debug) {
1060       LOG(INFO) << "Using input-oat-file " << input_oat_filename;
1061     }
1062   }
1063 
1064   bool match_delta = false;
1065   if (!patched_image_location.empty()) {
1066     std::string system_filename;
1067     bool has_system = false;
1068     std::string cache_filename;
1069     bool has_cache = false;
1070     bool has_android_data_unused = false;
1071     bool is_global_cache = false;
1072     if (!gc::space::ImageSpace::FindImageFilename(patched_image_location.c_str(), isa,
1073                                                   &system_filename, &has_system, &cache_filename,
1074                                                   &has_android_data_unused, &has_cache,
1075                                                   &is_global_cache)) {
1076       Usage("Unable to determine image file for location %s", patched_image_location.c_str());
1077     }
1078     std::string patched_image_filename;
1079     if (has_cache) {
1080       patched_image_filename = cache_filename;
1081     } else if (has_system) {
1082       LOG(WARNING) << "Only image file found was in /system for image location "
1083           << patched_image_location;
1084       patched_image_filename = system_filename;
1085     } else {
1086       Usage("Unable to determine image file for location %s", patched_image_location.c_str());
1087     }
1088     if (debug) {
1089       LOG(INFO) << "Using patched-image-file " << patched_image_filename;
1090     }
1091 
1092     base_delta_set = true;
1093     match_delta = true;
1094     std::string error_msg;
1095     if (!ReadBaseDelta(patched_image_filename.c_str(), &base_delta, &error_msg)) {
1096       Usage(error_msg.c_str(), patched_image_filename.c_str());
1097     }
1098   }
1099 
1100   if (!IsAligned<kPageSize>(base_delta)) {
1101     Usage("Base offset/delta must be alligned to a pagesize (0x%08x) boundary.", kPageSize);
1102   }
1103 
1104   // Do we need to cleanup output files if we fail?
1105   bool new_oat_out = false;
1106 
1107   std::unique_ptr<File> input_oat;
1108   std::unique_ptr<File> output_oat;
1109 
1110   if (input_oat_fd != -1) {
1111     if (input_oat_filename.empty()) {
1112       input_oat_filename = "input-oat-file";
1113     }
1114     input_oat.reset(new File(input_oat_fd, input_oat_filename, false));
1115     if (input_oat_fd == output_oat_fd) {
1116       input_oat.get()->DisableAutoClose();
1117     }
1118     if (input_oat == nullptr) {
1119       // Unlikely, but ensure exhaustive logging in non-0 exit code case
1120       LOG(ERROR) << "Failed to open input oat file by its FD" << input_oat_fd;
1121       return EXIT_FAILURE;
1122     }
1123   } else {
1124     CHECK(!input_oat_filename.empty());
1125     input_oat.reset(OS::OpenFileForReading(input_oat_filename.c_str()));
1126     if (input_oat == nullptr) {
1127       int err = errno;
1128       LOG(ERROR) << "Failed to open input oat file " << input_oat_filename
1129           << ": " << strerror(err) << "(" << err << ")";
1130       return EXIT_FAILURE;
1131     }
1132   }
1133 
1134   std::string error_msg;
1135   std::unique_ptr<ElfFile> elf(ElfFile::Open(input_oat.get(), PROT_READ, MAP_PRIVATE, &error_msg));
1136   if (elf.get() == nullptr) {
1137     LOG(ERROR) << "unable to open oat file " << input_oat->GetPath() << " : " << error_msg;
1138     return EXIT_FAILURE;
1139   }
1140   if (!elf->HasSection(".text.oat_patches")) {
1141     LOG(ERROR) << "missing oat patch section in input oat file " << input_oat->GetPath();
1142     return EXIT_FAILURE;
1143   }
1144 
1145   if (output_oat_fd != -1) {
1146     if (output_oat_filename.empty()) {
1147       output_oat_filename = "output-oat-file";
1148     }
1149     output_oat.reset(new File(output_oat_fd, output_oat_filename, true));
1150     if (output_oat == nullptr) {
1151       // Unlikely, but ensure exhaustive logging in non-0 exit code case
1152       LOG(ERROR) << "Failed to open output oat file by its FD" << output_oat_fd;
1153     }
1154   } else {
1155     CHECK(!output_oat_filename.empty());
1156     output_oat.reset(CreateOrOpen(output_oat_filename.c_str(), &new_oat_out));
1157     if (output_oat == nullptr) {
1158       int err = errno;
1159       LOG(ERROR) << "Failed to open output oat file " << output_oat_filename
1160           << ": " << strerror(err) << "(" << err << ")";
1161     }
1162   }
1163 
1164   // TODO: get rid of this.
1165   auto cleanup = [&output_oat_filename, &new_oat_out](bool success) {
1166     if (!success) {
1167       if (new_oat_out) {
1168         CHECK(!output_oat_filename.empty());
1169         unlink(output_oat_filename.c_str());
1170       }
1171     }
1172 
1173     if (kIsDebugBuild) {
1174       LOG(INFO) << "Cleaning up.. success? " << success;
1175     }
1176   };
1177 
1178   if (output_oat.get() == nullptr) {
1179     cleanup(false);
1180     return EXIT_FAILURE;
1181   }
1182 
1183   if (match_delta) {
1184     // Figure out what the current delta is so we can match it to the desired delta.
1185     off_t current_delta = 0;
1186     if (!ReadOatPatchDelta(elf.get(), &current_delta, &error_msg)) {
1187       LOG(ERROR) << "Unable to get current delta: " << error_msg;
1188       cleanup(false);
1189       return EXIT_FAILURE;
1190     }
1191     // Before this line base_delta is the desired final delta. We need it to be the actual amount to
1192     // change everything by. We subtract the current delta from it to make it this.
1193     base_delta -= current_delta;
1194     if (!IsAligned<kPageSize>(base_delta)) {
1195       LOG(ERROR) << "Given image file was relocated by an illegal delta";
1196       cleanup(false);
1197       return false;
1198     }
1199   }
1200 
1201   if (debug) {
1202     LOG(INFO) << "moving offset by " << base_delta
1203         << " (0x" << std::hex << base_delta << ") bytes or "
1204         << std::dec << (base_delta/kPageSize) << " pages.";
1205   }
1206 
1207   ScopedFlock output_oat_lock;
1208   if (lock_output) {
1209     if (!output_oat_lock.Init(output_oat.get(), &error_msg)) {
1210       LOG(ERROR) << "Unable to lock output oat " << output_oat->GetPath() << ": " << error_msg;
1211       cleanup(false);
1212       return EXIT_FAILURE;
1213     }
1214   }
1215 
1216   TimingLogger::ScopedTiming pt("patch oat", &timings);
1217   bool ret = PatchOat::Patch(input_oat.get(), base_delta, output_oat.get(), &timings,
1218                              output_oat_fd >= 0,  // was it opened from FD?
1219                              new_oat_out);
1220   ret = FinishFile(output_oat.get(), ret);
1221 
1222   if (kIsDebugBuild) {
1223     LOG(INFO) << "Exiting with return ... " << ret;
1224   }
1225   cleanup(ret);
1226   return ret ? EXIT_SUCCESS : EXIT_FAILURE;
1227 }
1228 
patchoat(int argc,char ** argv)1229 static int patchoat(int argc, char **argv) {
1230   InitLogging(argv);
1231   MemMap::Init();
1232   const bool debug = kIsDebugBuild;
1233   orig_argc = argc;
1234   orig_argv = argv;
1235   TimingLogger timings("patcher", false, false);
1236 
1237   InitLogging(argv);
1238 
1239   // Skip over the command name.
1240   argv++;
1241   argc--;
1242 
1243   if (argc == 0) {
1244     Usage("No arguments specified");
1245   }
1246 
1247   timings.StartTiming("Patchoat");
1248 
1249   // cmd line args
1250   bool isa_set = false;
1251   InstructionSet isa = kNone;
1252   std::string input_oat_filename;
1253   std::string input_oat_location;
1254   int input_oat_fd = -1;
1255   bool have_input_oat = false;
1256   std::string input_image_location;
1257   std::string output_oat_filename;
1258   int output_oat_fd = -1;
1259   bool have_output_oat = false;
1260   std::string output_image_filename;
1261   off_t base_delta = 0;
1262   bool base_delta_set = false;
1263   std::string patched_image_filename;
1264   std::string patched_image_location;
1265   bool dump_timings = kIsDebugBuild;
1266   bool lock_output = true;
1267 
1268   for (int i = 0; i < argc; ++i) {
1269     const StringPiece option(argv[i]);
1270     const bool log_options = false;
1271     if (log_options) {
1272       LOG(INFO) << "patchoat: option[" << i << "]=" << argv[i];
1273     }
1274     if (option.starts_with("--instruction-set=")) {
1275       isa_set = true;
1276       const char* isa_str = option.substr(strlen("--instruction-set=")).data();
1277       isa = GetInstructionSetFromString(isa_str);
1278       if (isa == kNone) {
1279         Usage("Unknown or invalid instruction set %s", isa_str);
1280       }
1281     } else if (option.starts_with("--input-oat-location=")) {
1282       if (have_input_oat) {
1283         Usage("Only one of --input-oat-file, --input-oat-location and --input-oat-fd may be used.");
1284       }
1285       have_input_oat = true;
1286       input_oat_location = option.substr(strlen("--input-oat-location=")).data();
1287     } else if (option.starts_with("--input-oat-file=")) {
1288       if (have_input_oat) {
1289         Usage("Only one of --input-oat-file, --input-oat-location and --input-oat-fd may be used.");
1290       }
1291       have_input_oat = true;
1292       input_oat_filename = option.substr(strlen("--input-oat-file=")).data();
1293     } else if (option.starts_with("--input-oat-fd=")) {
1294       if (have_input_oat) {
1295         Usage("Only one of --input-oat-file, --input-oat-location and --input-oat-fd may be used.");
1296       }
1297       have_input_oat = true;
1298       const char* oat_fd_str = option.substr(strlen("--input-oat-fd=")).data();
1299       if (!ParseInt(oat_fd_str, &input_oat_fd)) {
1300         Usage("Failed to parse --input-oat-fd argument '%s' as an integer", oat_fd_str);
1301       }
1302       if (input_oat_fd < 0) {
1303         Usage("--input-oat-fd pass a negative value %d", input_oat_fd);
1304       }
1305     } else if (option.starts_with("--input-image-location=")) {
1306       input_image_location = option.substr(strlen("--input-image-location=")).data();
1307     } else if (option.starts_with("--output-oat-file=")) {
1308       if (have_output_oat) {
1309         Usage("Only one of --output-oat-file, and --output-oat-fd may be used.");
1310       }
1311       have_output_oat = true;
1312       output_oat_filename = option.substr(strlen("--output-oat-file=")).data();
1313     } else if (option.starts_with("--output-oat-fd=")) {
1314       if (have_output_oat) {
1315         Usage("Only one of --output-oat-file, --output-oat-fd may be used.");
1316       }
1317       have_output_oat = true;
1318       const char* oat_fd_str = option.substr(strlen("--output-oat-fd=")).data();
1319       if (!ParseInt(oat_fd_str, &output_oat_fd)) {
1320         Usage("Failed to parse --output-oat-fd argument '%s' as an integer", oat_fd_str);
1321       }
1322       if (output_oat_fd < 0) {
1323         Usage("--output-oat-fd pass a negative value %d", output_oat_fd);
1324       }
1325     } else if (option.starts_with("--output-image-file=")) {
1326       output_image_filename = option.substr(strlen("--output-image-file=")).data();
1327     } else if (option.starts_with("--base-offset-delta=")) {
1328       const char* base_delta_str = option.substr(strlen("--base-offset-delta=")).data();
1329       base_delta_set = true;
1330       if (!ParseInt(base_delta_str, &base_delta)) {
1331         Usage("Failed to parse --base-offset-delta argument '%s' as an off_t", base_delta_str);
1332       }
1333     } else if (option.starts_with("--patched-image-location=")) {
1334       patched_image_location = option.substr(strlen("--patched-image-location=")).data();
1335     } else if (option == "--lock-output") {
1336       lock_output = true;
1337     } else if (option == "--no-lock-output") {
1338       lock_output = false;
1339     } else if (option == "--dump-timings") {
1340       dump_timings = true;
1341     } else if (option == "--no-dump-timings") {
1342       dump_timings = false;
1343     } else {
1344       Usage("Unknown argument %s", option.data());
1345     }
1346   }
1347 
1348   // The instruction set is mandatory. This simplifies things...
1349   if (!isa_set) {
1350     Usage("Instruction set must be set.");
1351   }
1352 
1353   int ret;
1354   if (!input_image_location.empty()) {
1355     ret = patchoat_image(timings,
1356                          isa,
1357                          input_image_location,
1358                          output_image_filename,
1359                          base_delta,
1360                          base_delta_set,
1361                          debug);
1362   } else {
1363     ret = patchoat_oat(timings,
1364                        isa,
1365                        patched_image_location,
1366                        base_delta,
1367                        base_delta_set,
1368                        input_oat_fd,
1369                        input_oat_location,
1370                        input_oat_filename,
1371                        have_input_oat,
1372                        output_oat_fd,
1373                        output_oat_filename,
1374                        have_output_oat,
1375                        lock_output,
1376                        debug);
1377   }
1378 
1379   timings.EndTiming();
1380   if (dump_timings) {
1381     LOG(INFO) << Dumpable<TimingLogger>(timings);
1382   }
1383 
1384   return ret;
1385 }
1386 
1387 }  // namespace art
1388 
main(int argc,char ** argv)1389 int main(int argc, char **argv) {
1390   return art::patchoat(argc, argv);
1391 }
1392