• 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 "base/scoped_flock.h"
28 #include "base/stringpiece.h"
29 #include "base/stringprintf.h"
30 #include "elf_utils.h"
31 #include "elf_file.h"
32 #include "gc/space/image_space.h"
33 #include "image.h"
34 #include "instruction_set.h"
35 #include "mirror/art_field.h"
36 #include "mirror/art_field-inl.h"
37 #include "mirror/art_method.h"
38 #include "mirror/art_method-inl.h"
39 #include "mirror/object.h"
40 #include "mirror/object-inl.h"
41 #include "mirror/reference.h"
42 #include "noop_compiler_callbacks.h"
43 #include "offsets.h"
44 #include "os.h"
45 #include "runtime.h"
46 #include "scoped_thread_state_change.h"
47 #include "thread.h"
48 #include "utils.h"
49 
50 namespace art {
51 
ElfISAToInstructionSet(Elf32_Word isa)52 static InstructionSet ElfISAToInstructionSet(Elf32_Word isa) {
53   switch (isa) {
54     case EM_ARM:
55       return kArm;
56     case EM_AARCH64:
57       return kArm64;
58     case EM_386:
59       return kX86;
60     case EM_X86_64:
61       return kX86_64;
62     case EM_MIPS:
63       return kMips;
64     default:
65       return kNone;
66   }
67 }
68 
LocationToFilename(const std::string & location,InstructionSet isa,std::string * filename)69 static bool LocationToFilename(const std::string& location, InstructionSet isa,
70                                std::string* filename) {
71   bool has_system = false;
72   bool has_cache = false;
73   // image_location = /system/framework/boot.art
74   // system_image_location = /system/framework/<image_isa>/boot.art
75   std::string system_filename(GetSystemImageFilename(location.c_str(), isa));
76   if (OS::FileExists(system_filename.c_str())) {
77     has_system = true;
78   }
79 
80   bool have_android_data = false;
81   bool dalvik_cache_exists = false;
82   bool is_global_cache = false;
83   std::string dalvik_cache;
84   GetDalvikCache(GetInstructionSetString(isa), false, &dalvik_cache,
85                  &have_android_data, &dalvik_cache_exists, &is_global_cache);
86 
87   std::string cache_filename;
88   if (have_android_data && dalvik_cache_exists) {
89     // Always set output location even if it does not exist,
90     // so that the caller knows where to create the image.
91     //
92     // image_location = /system/framework/boot.art
93     // *image_filename = /data/dalvik-cache/<image_isa>/boot.art
94     std::string error_msg;
95     if (GetDalvikCacheFilename(location.c_str(), dalvik_cache.c_str(),
96                                &cache_filename, &error_msg)) {
97       has_cache = true;
98     }
99   }
100   if (has_system) {
101     *filename = system_filename;
102     return true;
103   } else if (has_cache) {
104     *filename = cache_filename;
105     return true;
106   } else {
107     return false;
108   }
109 }
110 
Patch(const std::string & image_location,off_t delta,File * output_image,InstructionSet isa,TimingLogger * timings)111 bool PatchOat::Patch(const std::string& image_location, off_t delta,
112                      File* output_image, InstructionSet isa,
113                      TimingLogger* timings) {
114   CHECK(Runtime::Current() == nullptr);
115   CHECK(output_image != nullptr);
116   CHECK_GE(output_image->Fd(), 0);
117   CHECK(!image_location.empty()) << "image file must have a filename.";
118   CHECK_NE(isa, kNone);
119 
120   TimingLogger::ScopedTiming t("Runtime Setup", timings);
121   const char *isa_name = GetInstructionSetString(isa);
122   std::string image_filename;
123   if (!LocationToFilename(image_location, isa, &image_filename)) {
124     LOG(ERROR) << "Unable to find image at location " << image_location;
125     return false;
126   }
127   std::unique_ptr<File> input_image(OS::OpenFileForReading(image_filename.c_str()));
128   if (input_image.get() == nullptr) {
129     LOG(ERROR) << "unable to open input image file at " << image_filename
130                << " for location " << image_location;
131     return false;
132   }
133   int64_t image_len = input_image->GetLength();
134   if (image_len < 0) {
135     LOG(ERROR) << "Error while getting image length";
136     return false;
137   }
138   ImageHeader image_header;
139   if (sizeof(image_header) != input_image->Read(reinterpret_cast<char*>(&image_header),
140                                               sizeof(image_header), 0)) {
141     LOG(ERROR) << "Unable to read image header from image file " << input_image->GetPath();
142     return false;
143   }
144 
145   // Set up the runtime
146   RuntimeOptions options;
147   NoopCompilerCallbacks callbacks;
148   options.push_back(std::make_pair("compilercallbacks", &callbacks));
149   std::string img = "-Ximage:" + image_location;
150   options.push_back(std::make_pair(img.c_str(), nullptr));
151   options.push_back(std::make_pair("imageinstructionset", reinterpret_cast<const void*>(isa_name)));
152   if (!Runtime::Create(options, false)) {
153     LOG(ERROR) << "Unable to initialize runtime";
154     return false;
155   }
156   // Runtime::Create acquired the mutator_lock_ that is normally given away when we Runtime::Start,
157   // give it away now and then switch to a more manageable ScopedObjectAccess.
158   Thread::Current()->TransitionFromRunnableToSuspended(kNative);
159   ScopedObjectAccess soa(Thread::Current());
160 
161   t.NewTiming("Image and oat Patching setup");
162   // Create the map where we will write the image patches to.
163   std::string error_msg;
164   std::unique_ptr<MemMap> image(MemMap::MapFile(image_len, PROT_READ | PROT_WRITE, MAP_PRIVATE,
165                                                 input_image->Fd(), 0,
166                                                 input_image->GetPath().c_str(),
167                                                 &error_msg));
168   if (image.get() == nullptr) {
169     LOG(ERROR) << "unable to map image file " << input_image->GetPath() << " : " << error_msg;
170     return false;
171   }
172   gc::space::ImageSpace* ispc = Runtime::Current()->GetHeap()->GetImageSpace();
173 
174   PatchOat p(image.release(), ispc->GetLiveBitmap(), ispc->GetMemMap(),
175              delta, timings);
176   t.NewTiming("Patching files");
177   if (!p.PatchImage()) {
178     LOG(ERROR) << "Failed to patch image file " << input_image->GetPath();
179     return false;
180   }
181 
182   t.NewTiming("Writing files");
183   if (!p.WriteImage(output_image)) {
184     return false;
185   }
186   return true;
187 }
188 
Patch(const File * input_oat,const std::string & image_location,off_t delta,File * output_oat,File * output_image,InstructionSet isa,TimingLogger * timings)189 bool PatchOat::Patch(const File* input_oat, const std::string& image_location, off_t delta,
190                      File* output_oat, File* output_image, InstructionSet isa,
191                      TimingLogger* timings) {
192   CHECK(Runtime::Current() == nullptr);
193   CHECK(output_image != nullptr);
194   CHECK_GE(output_image->Fd(), 0);
195   CHECK(input_oat != nullptr);
196   CHECK(output_oat != nullptr);
197   CHECK_GE(input_oat->Fd(), 0);
198   CHECK_GE(output_oat->Fd(), 0);
199   CHECK(!image_location.empty()) << "image file must have a filename.";
200 
201   TimingLogger::ScopedTiming t("Runtime Setup", timings);
202 
203   if (isa == kNone) {
204     Elf32_Ehdr elf_hdr;
205     if (sizeof(elf_hdr) != input_oat->Read(reinterpret_cast<char*>(&elf_hdr), sizeof(elf_hdr), 0)) {
206       LOG(ERROR) << "unable to read elf header";
207       return false;
208     }
209     isa = ElfISAToInstructionSet(elf_hdr.e_machine);
210   }
211   const char* isa_name = GetInstructionSetString(isa);
212   std::string image_filename;
213   if (!LocationToFilename(image_location, isa, &image_filename)) {
214     LOG(ERROR) << "Unable to find image at location " << image_location;
215     return false;
216   }
217   std::unique_ptr<File> input_image(OS::OpenFileForReading(image_filename.c_str()));
218   if (input_image.get() == nullptr) {
219     LOG(ERROR) << "unable to open input image file at " << image_filename
220                << " for location " << image_location;
221     return false;
222   }
223   int64_t image_len = input_image->GetLength();
224   if (image_len < 0) {
225     LOG(ERROR) << "Error while getting image length";
226     return false;
227   }
228   ImageHeader image_header;
229   if (sizeof(image_header) != input_image->Read(reinterpret_cast<char*>(&image_header),
230                                               sizeof(image_header), 0)) {
231     LOG(ERROR) << "Unable to read image header from image file " << input_image->GetPath();
232   }
233 
234   // Set up the runtime
235   RuntimeOptions options;
236   NoopCompilerCallbacks callbacks;
237   options.push_back(std::make_pair("compilercallbacks", &callbacks));
238   std::string img = "-Ximage:" + image_location;
239   options.push_back(std::make_pair(img.c_str(), nullptr));
240   options.push_back(std::make_pair("imageinstructionset", reinterpret_cast<const void*>(isa_name)));
241   if (!Runtime::Create(options, false)) {
242     LOG(ERROR) << "Unable to initialize runtime";
243     return false;
244   }
245   // Runtime::Create acquired the mutator_lock_ that is normally given away when we Runtime::Start,
246   // give it away now and then switch to a more manageable ScopedObjectAccess.
247   Thread::Current()->TransitionFromRunnableToSuspended(kNative);
248   ScopedObjectAccess soa(Thread::Current());
249 
250   t.NewTiming("Image and oat Patching setup");
251   // Create the map where we will write the image patches to.
252   std::string error_msg;
253   std::unique_ptr<MemMap> image(MemMap::MapFile(image_len, PROT_READ | PROT_WRITE, MAP_PRIVATE,
254                                                 input_image->Fd(), 0,
255                                                 input_image->GetPath().c_str(),
256                                                 &error_msg));
257   if (image.get() == nullptr) {
258     LOG(ERROR) << "unable to map image file " << input_image->GetPath() << " : " << error_msg;
259     return false;
260   }
261   gc::space::ImageSpace* ispc = Runtime::Current()->GetHeap()->GetImageSpace();
262 
263   std::unique_ptr<ElfFile> elf(ElfFile::Open(const_cast<File*>(input_oat),
264                                              PROT_READ | PROT_WRITE, MAP_PRIVATE, &error_msg));
265   if (elf.get() == nullptr) {
266     LOG(ERROR) << "unable to open oat file " << input_oat->GetPath() << " : " << error_msg;
267     return false;
268   }
269 
270   PatchOat p(elf.release(), image.release(), ispc->GetLiveBitmap(), ispc->GetMemMap(),
271              delta, timings);
272   t.NewTiming("Patching files");
273   if (!p.PatchElf()) {
274     LOG(ERROR) << "Failed to patch oat file " << input_oat->GetPath();
275     return false;
276   }
277   if (!p.PatchImage()) {
278     LOG(ERROR) << "Failed to patch image file " << input_image->GetPath();
279     return false;
280   }
281 
282   t.NewTiming("Writing files");
283   if (!p.WriteElf(output_oat)) {
284     return false;
285   }
286   if (!p.WriteImage(output_image)) {
287     return false;
288   }
289   return true;
290 }
291 
WriteElf(File * out)292 bool PatchOat::WriteElf(File* out) {
293   TimingLogger::ScopedTiming t("Writing Elf File", timings_);
294 
295   CHECK(oat_file_.get() != nullptr);
296   CHECK(out != nullptr);
297   size_t expect = oat_file_->Size();
298   if (out->WriteFully(reinterpret_cast<char*>(oat_file_->Begin()), expect) &&
299       out->SetLength(expect) == 0) {
300     return true;
301   } else {
302     LOG(ERROR) << "Writing to oat file " << out->GetPath() << " failed.";
303     return false;
304   }
305 }
306 
WriteImage(File * out)307 bool PatchOat::WriteImage(File* out) {
308   TimingLogger::ScopedTiming t("Writing image File", timings_);
309   std::string error_msg;
310 
311   ScopedFlock img_flock;
312   img_flock.Init(out, &error_msg);
313 
314   CHECK(image_ != nullptr);
315   CHECK(out != nullptr);
316   size_t expect = image_->Size();
317   if (out->WriteFully(reinterpret_cast<char*>(image_->Begin()), expect) &&
318       out->SetLength(expect) == 0) {
319     return true;
320   } else {
321     LOG(ERROR) << "Writing to image file " << out->GetPath() << " failed.";
322     return false;
323   }
324 }
325 
PatchImage()326 bool PatchOat::PatchImage() {
327   ImageHeader* image_header = reinterpret_cast<ImageHeader*>(image_->Begin());
328   CHECK_GT(image_->Size(), sizeof(ImageHeader));
329   // These are the roots from the original file.
330   mirror::Object* img_roots = image_header->GetImageRoots();
331   image_header->RelocateImage(delta_);
332 
333   VisitObject(img_roots);
334   if (!image_header->IsValid()) {
335     LOG(ERROR) << "reloction renders image header invalid";
336     return false;
337   }
338 
339   {
340     TimingLogger::ScopedTiming t("Walk Bitmap", timings_);
341     // Walk the bitmap.
342     WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
343     bitmap_->Walk(PatchOat::BitmapCallback, this);
344   }
345   return true;
346 }
347 
InHeap(mirror::Object * o)348 bool PatchOat::InHeap(mirror::Object* o) {
349   uintptr_t begin = reinterpret_cast<uintptr_t>(heap_->Begin());
350   uintptr_t end = reinterpret_cast<uintptr_t>(heap_->End());
351   uintptr_t obj = reinterpret_cast<uintptr_t>(o);
352   return o == nullptr || (begin <= obj && obj < end);
353 }
354 
operator ()(mirror::Object * obj,MemberOffset off,bool is_static_unused) const355 void PatchOat::PatchVisitor::operator() (mirror::Object* obj, MemberOffset off,
356                                          bool is_static_unused) const {
357   mirror::Object* referent = obj->GetFieldObject<mirror::Object, kVerifyNone>(off);
358   DCHECK(patcher_->InHeap(referent)) << "Referent is not in the heap.";
359   mirror::Object* moved_object = patcher_->RelocatedAddressOf(referent);
360   copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(off, moved_object);
361 }
362 
operator ()(mirror::Class * cls,mirror::Reference * ref) const363 void PatchOat::PatchVisitor::operator() (mirror::Class* cls, mirror::Reference* ref) const {
364   MemberOffset off = mirror::Reference::ReferentOffset();
365   mirror::Object* referent = ref->GetReferent();
366   DCHECK(patcher_->InHeap(referent)) << "Referent is not in the heap.";
367   mirror::Object* moved_object = patcher_->RelocatedAddressOf(referent);
368   copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(off, moved_object);
369 }
370 
RelocatedCopyOf(mirror::Object * obj)371 mirror::Object* PatchOat::RelocatedCopyOf(mirror::Object* obj) {
372   if (obj == nullptr) {
373     return nullptr;
374   }
375   DCHECK_GT(reinterpret_cast<uintptr_t>(obj), reinterpret_cast<uintptr_t>(heap_->Begin()));
376   DCHECK_LT(reinterpret_cast<uintptr_t>(obj), reinterpret_cast<uintptr_t>(heap_->End()));
377   uintptr_t heap_off =
378       reinterpret_cast<uintptr_t>(obj) - reinterpret_cast<uintptr_t>(heap_->Begin());
379   DCHECK_LT(heap_off, image_->Size());
380   return reinterpret_cast<mirror::Object*>(image_->Begin() + heap_off);
381 }
382 
RelocatedAddressOf(mirror::Object * obj)383 mirror::Object* PatchOat::RelocatedAddressOf(mirror::Object* obj) {
384   if (obj == nullptr) {
385     return nullptr;
386   } else {
387     return reinterpret_cast<mirror::Object*>(reinterpret_cast<byte*>(obj) + delta_);
388   }
389 }
390 
391 // Called by BitmapCallback
VisitObject(mirror::Object * object)392 void PatchOat::VisitObject(mirror::Object* object) {
393   mirror::Object* copy = RelocatedCopyOf(object);
394   CHECK(copy != nullptr);
395   if (kUseBakerOrBrooksReadBarrier) {
396     object->AssertReadBarrierPointer();
397     if (kUseBrooksReadBarrier) {
398       mirror::Object* moved_to = RelocatedAddressOf(object);
399       copy->SetReadBarrierPointer(moved_to);
400       DCHECK_EQ(copy->GetReadBarrierPointer(), moved_to);
401     }
402   }
403   PatchOat::PatchVisitor visitor(this, copy);
404   object->VisitReferences<true, kVerifyNone>(visitor, visitor);
405   if (object->IsArtMethod<kVerifyNone>()) {
406     FixupMethod(static_cast<mirror::ArtMethod*>(object),
407                 static_cast<mirror::ArtMethod*>(copy));
408   }
409 }
410 
FixupMethod(mirror::ArtMethod * object,mirror::ArtMethod * copy)411 void PatchOat::FixupMethod(mirror::ArtMethod* object, mirror::ArtMethod* copy) {
412   // Just update the entry points if it looks like we should.
413   // TODO: sanity check all the pointers' values
414 #if defined(ART_USE_PORTABLE_COMPILER)
415   uintptr_t portable = reinterpret_cast<uintptr_t>(
416       object->GetEntryPointFromPortableCompiledCode<kVerifyNone>());
417   if (portable != 0) {
418     copy->SetEntryPointFromPortableCompiledCode(reinterpret_cast<void*>(portable + delta_));
419   }
420 #endif
421   uintptr_t quick= reinterpret_cast<uintptr_t>(
422       object->GetEntryPointFromQuickCompiledCode<kVerifyNone>());
423   if (quick != 0) {
424     copy->SetEntryPointFromQuickCompiledCode(reinterpret_cast<void*>(quick + delta_));
425   }
426   uintptr_t interpreter = reinterpret_cast<uintptr_t>(
427       object->GetEntryPointFromInterpreter<kVerifyNone>());
428   if (interpreter != 0) {
429     copy->SetEntryPointFromInterpreter(
430         reinterpret_cast<mirror::EntryPointFromInterpreter*>(interpreter + delta_));
431   }
432 
433   uintptr_t native_method = reinterpret_cast<uintptr_t>(object->GetNativeMethod());
434   if (native_method != 0) {
435     copy->SetNativeMethod(reinterpret_cast<void*>(native_method + delta_));
436   }
437 
438   uintptr_t native_gc_map = reinterpret_cast<uintptr_t>(object->GetNativeGcMap());
439   if (native_gc_map != 0) {
440     copy->SetNativeGcMap(reinterpret_cast<uint8_t*>(native_gc_map + delta_));
441   }
442 }
443 
Patch(File * input_oat,off_t delta,File * output_oat,TimingLogger * timings)444 bool PatchOat::Patch(File* input_oat, off_t delta, File* output_oat, TimingLogger* timings) {
445   CHECK(input_oat != nullptr);
446   CHECK(output_oat != nullptr);
447   CHECK_GE(input_oat->Fd(), 0);
448   CHECK_GE(output_oat->Fd(), 0);
449   TimingLogger::ScopedTiming t("Setup Oat File Patching", timings);
450 
451   std::string error_msg;
452   std::unique_ptr<ElfFile> elf(ElfFile::Open(const_cast<File*>(input_oat),
453                                              PROT_READ | PROT_WRITE, MAP_PRIVATE, &error_msg));
454   if (elf.get() == nullptr) {
455     LOG(ERROR) << "unable to open oat file " << input_oat->GetPath() << " : " << error_msg;
456     return false;
457   }
458 
459   PatchOat p(elf.release(), delta, timings);
460   t.NewTiming("Patch Oat file");
461   if (!p.PatchElf()) {
462     return false;
463   }
464 
465   t.NewTiming("Writing oat file");
466   if (!p.WriteElf(output_oat)) {
467     return false;
468   }
469   return true;
470 }
471 
CheckOatFile()472 bool PatchOat::CheckOatFile() {
473   Elf32_Shdr* patches_sec = oat_file_->FindSectionByName(".oat_patches");
474   if (patches_sec == nullptr) {
475     return false;
476   }
477   if (patches_sec->sh_type != SHT_OAT_PATCH) {
478     return false;
479   }
480   uintptr_t* patches = reinterpret_cast<uintptr_t*>(oat_file_->Begin() + patches_sec->sh_offset);
481   uintptr_t* patches_end = patches + (patches_sec->sh_size/sizeof(uintptr_t));
482   Elf32_Shdr* oat_data_sec = oat_file_->FindSectionByName(".rodata");
483   Elf32_Shdr* oat_text_sec = oat_file_->FindSectionByName(".text");
484   if (oat_data_sec == nullptr) {
485     return false;
486   }
487   if (oat_text_sec == nullptr) {
488     return false;
489   }
490   if (oat_text_sec->sh_offset <= oat_data_sec->sh_offset) {
491     return false;
492   }
493 
494   for (; patches < patches_end; patches++) {
495     if (oat_text_sec->sh_size <= *patches) {
496       return false;
497     }
498   }
499 
500   return true;
501 }
502 
PatchOatHeader()503 bool PatchOat::PatchOatHeader() {
504   Elf32_Shdr *rodata_sec = oat_file_->FindSectionByName(".rodata");
505   if (rodata_sec == nullptr) {
506     return false;
507   }
508   OatHeader* oat_header = reinterpret_cast<OatHeader*>(oat_file_->Begin() + rodata_sec->sh_offset);
509   if (!oat_header->IsValid()) {
510     LOG(ERROR) << "Elf file " << oat_file_->GetFile().GetPath() << " has an invalid oat header";
511     return false;
512   }
513   oat_header->RelocateOat(delta_);
514   return true;
515 }
516 
PatchElf()517 bool PatchOat::PatchElf() {
518   TimingLogger::ScopedTiming t("Fixup Elf Text Section", timings_);
519   if (!PatchTextSection()) {
520     return false;
521   }
522 
523   if (!PatchOatHeader()) {
524     return false;
525   }
526 
527   bool need_fixup = false;
528   t.NewTiming("Fixup Elf Headers");
529   // Fixup Phdr's
530   for (unsigned int i = 0; i < oat_file_->GetProgramHeaderNum(); i++) {
531     Elf32_Phdr* hdr = oat_file_->GetProgramHeader(i);
532     CHECK(hdr != nullptr);
533     if (hdr->p_vaddr != 0 && hdr->p_vaddr != hdr->p_offset) {
534       need_fixup = true;
535       hdr->p_vaddr += delta_;
536     }
537     if (hdr->p_paddr != 0 && hdr->p_paddr != hdr->p_offset) {
538       need_fixup = true;
539       hdr->p_paddr += delta_;
540     }
541   }
542   if (!need_fixup) {
543     // This was never passed through ElfFixup so all headers/symbols just have their offset as
544     // their addr. Therefore we do not need to update these parts.
545     return true;
546   }
547   t.NewTiming("Fixup Section Headers");
548   for (unsigned int i = 0; i < oat_file_->GetSectionHeaderNum(); i++) {
549     Elf32_Shdr* hdr = oat_file_->GetSectionHeader(i);
550     CHECK(hdr != nullptr);
551     if (hdr->sh_addr != 0) {
552       hdr->sh_addr += delta_;
553     }
554   }
555 
556   t.NewTiming("Fixup Dynamics");
557   for (Elf32_Word i = 0; i < oat_file_->GetDynamicNum(); i++) {
558     Elf32_Dyn& dyn = oat_file_->GetDynamic(i);
559     if (IsDynamicSectionPointer(dyn.d_tag, oat_file_->GetHeader().e_machine)) {
560       dyn.d_un.d_ptr += delta_;
561     }
562   }
563 
564   t.NewTiming("Fixup Elf Symbols");
565   // Fixup dynsym
566   Elf32_Shdr* dynsym_sec = oat_file_->FindSectionByName(".dynsym");
567   CHECK(dynsym_sec != nullptr);
568   if (!PatchSymbols(dynsym_sec)) {
569     return false;
570   }
571 
572   // Fixup symtab
573   Elf32_Shdr* symtab_sec = oat_file_->FindSectionByName(".symtab");
574   if (symtab_sec != nullptr) {
575     if (!PatchSymbols(symtab_sec)) {
576       return false;
577     }
578   }
579 
580   return true;
581 }
582 
PatchSymbols(Elf32_Shdr * section)583 bool PatchOat::PatchSymbols(Elf32_Shdr* section) {
584   Elf32_Sym* syms = reinterpret_cast<Elf32_Sym*>(oat_file_->Begin() + section->sh_offset);
585   const Elf32_Sym* last_sym =
586       reinterpret_cast<Elf32_Sym*>(oat_file_->Begin() + section->sh_offset + section->sh_size);
587   CHECK_EQ(section->sh_size % sizeof(Elf32_Sym), 0u)
588       << "Symtab section size is not multiple of symbol size";
589   for (; syms < last_sym; syms++) {
590     uint8_t sttype = ELF32_ST_TYPE(syms->st_info);
591     Elf32_Word shndx = syms->st_shndx;
592     if (shndx != SHN_ABS && shndx != SHN_COMMON && shndx != SHN_UNDEF &&
593         (sttype == STT_FUNC || sttype == STT_OBJECT)) {
594       CHECK_NE(syms->st_value, 0u);
595       syms->st_value += delta_;
596     }
597   }
598   return true;
599 }
600 
PatchTextSection()601 bool PatchOat::PatchTextSection() {
602   Elf32_Shdr* patches_sec = oat_file_->FindSectionByName(".oat_patches");
603   if (patches_sec == nullptr) {
604     LOG(ERROR) << ".oat_patches section not found. Aborting patch";
605     return false;
606   }
607   DCHECK(CheckOatFile()) << "Oat file invalid";
608   CHECK_EQ(patches_sec->sh_type, SHT_OAT_PATCH) << "Unexpected type of .oat_patches";
609   uintptr_t* patches = reinterpret_cast<uintptr_t*>(oat_file_->Begin() + patches_sec->sh_offset);
610   uintptr_t* patches_end = patches + (patches_sec->sh_size/sizeof(uintptr_t));
611   Elf32_Shdr* oat_text_sec = oat_file_->FindSectionByName(".text");
612   CHECK(oat_text_sec != nullptr);
613   byte* to_patch = oat_file_->Begin() + oat_text_sec->sh_offset;
614   uintptr_t to_patch_end = reinterpret_cast<uintptr_t>(to_patch) + oat_text_sec->sh_size;
615 
616   for (; patches < patches_end; patches++) {
617     CHECK_LT(*patches, oat_text_sec->sh_size) << "Bad Patch";
618     uint32_t* patch_loc = reinterpret_cast<uint32_t*>(to_patch + *patches);
619     CHECK_LT(reinterpret_cast<uintptr_t>(patch_loc), to_patch_end);
620     *patch_loc += delta_;
621   }
622 
623   return true;
624 }
625 
626 static int orig_argc;
627 static char** orig_argv;
628 
CommandLine()629 static std::string CommandLine() {
630   std::vector<std::string> command;
631   for (int i = 0; i < orig_argc; ++i) {
632     command.push_back(orig_argv[i]);
633   }
634   return Join(command, ' ');
635 }
636 
UsageErrorV(const char * fmt,va_list ap)637 static void UsageErrorV(const char* fmt, va_list ap) {
638   std::string error;
639   StringAppendV(&error, fmt, ap);
640   LOG(ERROR) << error;
641 }
642 
UsageError(const char * fmt,...)643 static void UsageError(const char* fmt, ...) {
644   va_list ap;
645   va_start(ap, fmt);
646   UsageErrorV(fmt, ap);
647   va_end(ap);
648 }
649 
Usage(const char * fmt,...)650 static void Usage(const char *fmt, ...) {
651   va_list ap;
652   va_start(ap, fmt);
653   UsageErrorV(fmt, ap);
654   va_end(ap);
655 
656   UsageError("Command: %s", CommandLine().c_str());
657   UsageError("Usage: patchoat [options]...");
658   UsageError("");
659   UsageError("  --instruction-set=<isa>: Specifies the instruction set the patched code is");
660   UsageError("      compiled for. Required if you use --input-oat-location");
661   UsageError("");
662   UsageError("  --input-oat-file=<file.oat>: Specifies the exact filename of the oat file to be");
663   UsageError("      patched.");
664   UsageError("");
665   UsageError("  --input-oat-fd=<file-descriptor>: Specifies the file-descriptor of the oat file");
666   UsageError("      to be patched.");
667   UsageError("");
668   UsageError("  --input-oat-location=<file.oat>: Specifies the 'location' to read the patched");
669   UsageError("      oat file from. If used one must also supply the --instruction-set");
670   UsageError("");
671   UsageError("  --input-image-location=<file.art>: Specifies the 'location' of the image file to");
672   UsageError("      be patched. If --instruction-set is not given it will use the instruction set");
673   UsageError("      extracted from the --input-oat-file.");
674   UsageError("");
675   UsageError("  --output-oat-file=<file.oat>: Specifies the exact file to write the patched oat");
676   UsageError("      file to.");
677   UsageError("");
678   UsageError("  --output-oat-fd=<file-descriptor>: Specifies the file-descriptor to write the");
679   UsageError("      the patched oat file to.");
680   UsageError("");
681   UsageError("  --output-image-file=<file.art>: Specifies the exact file to write the patched");
682   UsageError("      image file to.");
683   UsageError("");
684   UsageError("  --output-image-fd=<file-descriptor>: Specifies the file-descriptor to write the");
685   UsageError("      the patched image file to.");
686   UsageError("");
687   UsageError("  --orig-base-offset=<original-base-offset>: Specify the base offset the input file");
688   UsageError("      was compiled with. This is needed if one is specifying a --base-offset");
689   UsageError("");
690   UsageError("  --base-offset=<new-base-offset>: Specify the base offset we will repatch the");
691   UsageError("      given files to use. This requires that --orig-base-offset is also given.");
692   UsageError("");
693   UsageError("  --base-offset-delta=<delta>: Specify the amount to change the old base-offset by.");
694   UsageError("      This value may be negative.");
695   UsageError("");
696   UsageError("  --patched-image-file=<file.art>: Use the same patch delta as was used to patch");
697   UsageError("      the given image file.");
698   UsageError("");
699   UsageError("  --patched-image-location=<file.art>: Use the same patch delta as was used to");
700   UsageError("      patch the given image location. If used one must also specify the");
701   UsageError("      --instruction-set flag. It will search for this image in the same way that");
702   UsageError("      is done when loading one.");
703   UsageError("");
704   UsageError("  --lock-output: Obtain a flock on output oat file before starting.");
705   UsageError("");
706   UsageError("  --no-lock-output: Do not attempt to obtain a flock on output oat file.");
707   UsageError("");
708   UsageError("  --dump-timings: dump out patch timing information");
709   UsageError("");
710   UsageError("  --no-dump-timings: do not dump out patch timing information");
711   UsageError("");
712 
713   exit(EXIT_FAILURE);
714 }
715 
ReadBaseDelta(const char * name,off_t * delta,std::string * error_msg)716 static bool ReadBaseDelta(const char* name, off_t* delta, std::string* error_msg) {
717   CHECK(name != nullptr);
718   CHECK(delta != nullptr);
719   std::unique_ptr<File> file;
720   if (OS::FileExists(name)) {
721     file.reset(OS::OpenFileForReading(name));
722     if (file.get() == nullptr) {
723       *error_msg = "Failed to open file %s for reading";
724       return false;
725     }
726   } else {
727     *error_msg = "File %s does not exist";
728     return false;
729   }
730   CHECK(file.get() != nullptr);
731   ImageHeader hdr;
732   if (sizeof(hdr) != file->Read(reinterpret_cast<char*>(&hdr), sizeof(hdr), 0)) {
733     *error_msg = "Failed to read file %s";
734     return false;
735   }
736   if (!hdr.IsValid()) {
737     *error_msg = "%s does not contain a valid image header.";
738     return false;
739   }
740   *delta = hdr.GetPatchDelta();
741   return true;
742 }
743 
CreateOrOpen(const char * name,bool * created)744 static File* CreateOrOpen(const char* name, bool* created) {
745   if (OS::FileExists(name)) {
746     *created = false;
747     return OS::OpenFileReadWrite(name);
748   } else {
749     *created = true;
750     std::unique_ptr<File> f(OS::CreateEmptyFile(name));
751     if (f.get() != nullptr) {
752       if (fchmod(f->Fd(), 0644) != 0) {
753         PLOG(ERROR) << "Unable to make " << name << " world readable";
754         unlink(name);
755         return nullptr;
756       }
757     }
758     return f.release();
759   }
760 }
761 
patchoat(int argc,char ** argv)762 static int patchoat(int argc, char **argv) {
763   InitLogging(argv);
764   MemMap::Init();
765   const bool debug = kIsDebugBuild;
766   orig_argc = argc;
767   orig_argv = argv;
768   TimingLogger timings("patcher", false, false);
769 
770   InitLogging(argv);
771 
772   // Skip over the command name.
773   argv++;
774   argc--;
775 
776   if (argc == 0) {
777     Usage("No arguments specified");
778   }
779 
780   timings.StartTiming("Patchoat");
781 
782   // cmd line args
783   bool isa_set = false;
784   InstructionSet isa = kNone;
785   std::string input_oat_filename;
786   std::string input_oat_location;
787   int input_oat_fd = -1;
788   bool have_input_oat = false;
789   std::string input_image_location;
790   std::string output_oat_filename;
791   int output_oat_fd = -1;
792   bool have_output_oat = false;
793   std::string output_image_filename;
794   int output_image_fd = -1;
795   bool have_output_image = false;
796   uintptr_t base_offset = 0;
797   bool base_offset_set = false;
798   uintptr_t orig_base_offset = 0;
799   bool orig_base_offset_set = false;
800   off_t base_delta = 0;
801   bool base_delta_set = false;
802   std::string patched_image_filename;
803   std::string patched_image_location;
804   bool dump_timings = kIsDebugBuild;
805   bool lock_output = true;
806 
807   for (int i = 0; i < argc; i++) {
808     const StringPiece option(argv[i]);
809     const bool log_options = false;
810     if (log_options) {
811       LOG(INFO) << "patchoat: option[" << i << "]=" << argv[i];
812     }
813     if (option.starts_with("--instruction-set=")) {
814       isa_set = true;
815       const char* isa_str = option.substr(strlen("--instruction-set=")).data();
816       isa = GetInstructionSetFromString(isa_str);
817       if (isa == kNone) {
818         Usage("Unknown or invalid instruction set %s", isa_str);
819       }
820     } else if (option.starts_with("--input-oat-location=")) {
821       if (have_input_oat) {
822         Usage("Only one of --input-oat-file, --input-oat-location and --input-oat-fd may be used.");
823       }
824       have_input_oat = true;
825       input_oat_location = option.substr(strlen("--input-oat-location=")).data();
826     } else if (option.starts_with("--input-oat-file=")) {
827       if (have_input_oat) {
828         Usage("Only one of --input-oat-file, --input-oat-location and --input-oat-fd may be used.");
829       }
830       have_input_oat = true;
831       input_oat_filename = option.substr(strlen("--input-oat-file=")).data();
832     } else if (option.starts_with("--input-oat-fd=")) {
833       if (have_input_oat) {
834         Usage("Only one of --input-oat-file, --input-oat-location and --input-oat-fd may be used.");
835       }
836       have_input_oat = true;
837       const char* oat_fd_str = option.substr(strlen("--input-oat-fd=")).data();
838       if (!ParseInt(oat_fd_str, &input_oat_fd)) {
839         Usage("Failed to parse --input-oat-fd argument '%s' as an integer", oat_fd_str);
840       }
841       if (input_oat_fd < 0) {
842         Usage("--input-oat-fd pass a negative value %d", input_oat_fd);
843       }
844     } else if (option.starts_with("--input-image-location=")) {
845       input_image_location = option.substr(strlen("--input-image-location=")).data();
846     } else if (option.starts_with("--output-oat-file=")) {
847       if (have_output_oat) {
848         Usage("Only one of --output-oat-file, and --output-oat-fd may be used.");
849       }
850       have_output_oat = true;
851       output_oat_filename = option.substr(strlen("--output-oat-file=")).data();
852     } else if (option.starts_with("--output-oat-fd=")) {
853       if (have_output_oat) {
854         Usage("Only one of --output-oat-file, --output-oat-fd may be used.");
855       }
856       have_output_oat = true;
857       const char* oat_fd_str = option.substr(strlen("--output-oat-fd=")).data();
858       if (!ParseInt(oat_fd_str, &output_oat_fd)) {
859         Usage("Failed to parse --output-oat-fd argument '%s' as an integer", oat_fd_str);
860       }
861       if (output_oat_fd < 0) {
862         Usage("--output-oat-fd pass a negative value %d", output_oat_fd);
863       }
864     } else if (option.starts_with("--output-image-file=")) {
865       if (have_output_image) {
866         Usage("Only one of --output-image-file, and --output-image-fd may be used.");
867       }
868       have_output_image = true;
869       output_image_filename = option.substr(strlen("--output-image-file=")).data();
870     } else if (option.starts_with("--output-image-fd=")) {
871       if (have_output_image) {
872         Usage("Only one of --output-image-file, and --output-image-fd may be used.");
873       }
874       have_output_image = true;
875       const char* image_fd_str = option.substr(strlen("--output-image-fd=")).data();
876       if (!ParseInt(image_fd_str, &output_image_fd)) {
877         Usage("Failed to parse --output-image-fd argument '%s' as an integer", image_fd_str);
878       }
879       if (output_image_fd < 0) {
880         Usage("--output-image-fd pass a negative value %d", output_image_fd);
881       }
882     } else if (option.starts_with("--orig-base-offset=")) {
883       const char* orig_base_offset_str = option.substr(strlen("--orig-base-offset=")).data();
884       orig_base_offset_set = true;
885       if (!ParseUint(orig_base_offset_str, &orig_base_offset)) {
886         Usage("Failed to parse --orig-base-offset argument '%s' as an uintptr_t",
887               orig_base_offset_str);
888       }
889     } else if (option.starts_with("--base-offset=")) {
890       const char* base_offset_str = option.substr(strlen("--base-offset=")).data();
891       base_offset_set = true;
892       if (!ParseUint(base_offset_str, &base_offset)) {
893         Usage("Failed to parse --base-offset argument '%s' as an uintptr_t", base_offset_str);
894       }
895     } else if (option.starts_with("--base-offset-delta=")) {
896       const char* base_delta_str = option.substr(strlen("--base-offset-delta=")).data();
897       base_delta_set = true;
898       if (!ParseInt(base_delta_str, &base_delta)) {
899         Usage("Failed to parse --base-offset-delta argument '%s' as an off_t", base_delta_str);
900       }
901     } else if (option.starts_with("--patched-image-location=")) {
902       patched_image_location = option.substr(strlen("--patched-image-location=")).data();
903     } else if (option.starts_with("--patched-image-file=")) {
904       patched_image_filename = option.substr(strlen("--patched-image-file=")).data();
905     } else if (option == "--lock-output") {
906       lock_output = true;
907     } else if (option == "--no-lock-output") {
908       lock_output = false;
909     } else if (option == "--dump-timings") {
910       dump_timings = true;
911     } else if (option == "--no-dump-timings") {
912       dump_timings = false;
913     } else {
914       Usage("Unknown argument %s", option.data());
915     }
916   }
917 
918   {
919     // Only 1 of these may be set.
920     uint32_t cnt = 0;
921     cnt += (base_delta_set) ? 1 : 0;
922     cnt += (base_offset_set && orig_base_offset_set) ? 1 : 0;
923     cnt += (!patched_image_filename.empty()) ? 1 : 0;
924     cnt += (!patched_image_location.empty()) ? 1 : 0;
925     if (cnt > 1) {
926       Usage("Only one of --base-offset/--orig-base-offset, --base-offset-delta, "
927             "--patched-image-filename or --patched-image-location may be used.");
928     } else if (cnt == 0) {
929       Usage("Must specify --base-offset-delta, --base-offset and --orig-base-offset, "
930             "--patched-image-location or --patched-image-file");
931     }
932   }
933 
934   if (have_input_oat != have_output_oat) {
935     Usage("Either both input and output oat must be supplied or niether must be.");
936   }
937 
938   if ((!input_image_location.empty()) != have_output_image) {
939     Usage("Either both input and output image must be supplied or niether must be.");
940   }
941 
942   // We know we have both the input and output so rename for clarity.
943   bool have_image_files = have_output_image;
944   bool have_oat_files = have_output_oat;
945 
946   if (!have_oat_files && !have_image_files) {
947     Usage("Must be patching either an oat or an image file or both.");
948   }
949 
950   if (!have_oat_files && !isa_set) {
951     Usage("Must include ISA if patching an image file without an oat file.");
952   }
953 
954   if (!input_oat_location.empty()) {
955     if (!isa_set) {
956       Usage("specifying a location requires specifying an instruction set");
957     }
958     if (!LocationToFilename(input_oat_location, isa, &input_oat_filename)) {
959       Usage("Unable to find filename for input oat location %s", input_oat_location.c_str());
960     }
961     if (debug) {
962       LOG(INFO) << "Using input-oat-file " << input_oat_filename;
963     }
964   }
965   if (!patched_image_location.empty()) {
966     if (!isa_set) {
967       Usage("specifying a location requires specifying an instruction set");
968     }
969     std::string system_filename;
970     bool has_system = false;
971     std::string cache_filename;
972     bool has_cache = false;
973     bool has_android_data_unused = false;
974     bool is_global_cache = false;
975     if (!gc::space::ImageSpace::FindImageFilename(patched_image_location.c_str(), isa,
976                                                   &system_filename, &has_system, &cache_filename,
977                                                   &has_android_data_unused, &has_cache,
978                                                   &is_global_cache)) {
979       Usage("Unable to determine image file for location %s", patched_image_location.c_str());
980     }
981     if (has_cache) {
982       patched_image_filename = cache_filename;
983     } else if (has_system) {
984       LOG(WARNING) << "Only image file found was in /system for image location "
985                    << patched_image_location;
986       patched_image_filename = system_filename;
987     } else {
988       Usage("Unable to determine image file for location %s", patched_image_location.c_str());
989     }
990     if (debug) {
991       LOG(INFO) << "Using patched-image-file " << patched_image_filename;
992     }
993   }
994 
995   if (!base_delta_set) {
996     if (orig_base_offset_set && base_offset_set) {
997       base_delta_set = true;
998       base_delta = base_offset - orig_base_offset;
999     } else if (!patched_image_filename.empty()) {
1000       base_delta_set = true;
1001       std::string error_msg;
1002       if (!ReadBaseDelta(patched_image_filename.c_str(), &base_delta, &error_msg)) {
1003         Usage(error_msg.c_str(), patched_image_filename.c_str());
1004       }
1005     } else {
1006       if (base_offset_set) {
1007         Usage("Unable to determine original base offset.");
1008       } else {
1009         Usage("Must supply a desired new offset or delta.");
1010       }
1011     }
1012   }
1013 
1014   if (!IsAligned<kPageSize>(base_delta)) {
1015     Usage("Base offset/delta must be alligned to a pagesize (0x%08x) boundary.", kPageSize);
1016   }
1017 
1018   // Do we need to cleanup output files if we fail?
1019   bool new_image_out = false;
1020   bool new_oat_out = false;
1021 
1022   std::unique_ptr<File> input_oat;
1023   std::unique_ptr<File> output_oat;
1024   std::unique_ptr<File> output_image;
1025 
1026   if (have_image_files) {
1027     CHECK(!input_image_location.empty());
1028 
1029     if (output_image_fd != -1) {
1030       if (output_image_filename.empty()) {
1031         output_image_filename = "output-image-file";
1032       }
1033       output_image.reset(new File(output_image_fd, output_image_filename));
1034     } else {
1035       CHECK(!output_image_filename.empty());
1036       output_image.reset(CreateOrOpen(output_image_filename.c_str(), &new_image_out));
1037     }
1038   } else {
1039     CHECK(output_image_filename.empty() && output_image_fd == -1 && input_image_location.empty());
1040   }
1041 
1042   if (have_oat_files) {
1043     if (input_oat_fd != -1) {
1044       if (input_oat_filename.empty()) {
1045         input_oat_filename = "input-oat-file";
1046       }
1047       input_oat.reset(new File(input_oat_fd, input_oat_filename));
1048     } else {
1049       CHECK(!input_oat_filename.empty());
1050       input_oat.reset(OS::OpenFileForReading(input_oat_filename.c_str()));
1051       if (input_oat.get() == nullptr) {
1052         LOG(ERROR) << "Could not open input oat file: " << strerror(errno);
1053       }
1054     }
1055 
1056     if (output_oat_fd != -1) {
1057       if (output_oat_filename.empty()) {
1058         output_oat_filename = "output-oat-file";
1059       }
1060       output_oat.reset(new File(output_oat_fd, output_oat_filename));
1061     } else {
1062       CHECK(!output_oat_filename.empty());
1063       output_oat.reset(CreateOrOpen(output_oat_filename.c_str(), &new_oat_out));
1064     }
1065   }
1066 
1067   auto cleanup = [&output_image_filename, &output_oat_filename,
1068                   &new_oat_out, &new_image_out, &timings, &dump_timings](bool success) {
1069     timings.EndTiming();
1070     if (!success) {
1071       if (new_oat_out) {
1072         CHECK(!output_oat_filename.empty());
1073         unlink(output_oat_filename.c_str());
1074       }
1075       if (new_image_out) {
1076         CHECK(!output_image_filename.empty());
1077         unlink(output_image_filename.c_str());
1078       }
1079     }
1080     if (dump_timings) {
1081       LOG(INFO) << Dumpable<TimingLogger>(timings);
1082     }
1083   };
1084 
1085   if ((have_oat_files && (input_oat.get() == nullptr || output_oat.get() == nullptr)) ||
1086       (have_image_files && output_image.get() == nullptr)) {
1087     cleanup(false);
1088     return EXIT_FAILURE;
1089   }
1090 
1091   ScopedFlock output_oat_lock;
1092   if (lock_output) {
1093     std::string error_msg;
1094     if (have_oat_files && !output_oat_lock.Init(output_oat.get(), &error_msg)) {
1095       LOG(ERROR) << "Unable to lock output oat " << output_image->GetPath() << ": " << error_msg;
1096       cleanup(false);
1097       return EXIT_FAILURE;
1098     }
1099   }
1100 
1101   if (debug) {
1102     LOG(INFO) << "moving offset by " << base_delta
1103               << " (0x" << std::hex << base_delta << ") bytes or "
1104               << std::dec << (base_delta/kPageSize) << " pages.";
1105   }
1106 
1107   bool ret;
1108   if (have_image_files && have_oat_files) {
1109     TimingLogger::ScopedTiming pt("patch image and oat", &timings);
1110     ret = PatchOat::Patch(input_oat.get(), input_image_location, base_delta,
1111                           output_oat.get(), output_image.get(), isa, &timings);
1112   } else if (have_oat_files) {
1113     TimingLogger::ScopedTiming pt("patch oat", &timings);
1114     ret = PatchOat::Patch(input_oat.get(), base_delta, output_oat.get(), &timings);
1115   } else {
1116     TimingLogger::ScopedTiming pt("patch image", &timings);
1117     CHECK(have_image_files);
1118     ret = PatchOat::Patch(input_image_location, base_delta, output_image.get(), isa, &timings);
1119   }
1120   cleanup(ret);
1121   return (ret) ? EXIT_SUCCESS : EXIT_FAILURE;
1122 }
1123 
1124 }  // namespace art
1125 
main(int argc,char ** argv)1126 int main(int argc, char **argv) {
1127   return art::patchoat(argc, argv);
1128 }
1129