image_writer.cc revision 8b2c0b9abc3f520495f4387ea040132ba85cae69
1/*
2 * Copyright (C) 2011 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
17#include "image_writer.h"
18
19#include <sys/stat.h>
20
21#include <vector>
22
23#include "base/logging.h"
24#include "base/unix_file/fd_file.h"
25#include "class_linker.h"
26#include "compiled_method.h"
27#include "dex_file-inl.h"
28#include "driver/compiler_driver.h"
29#include "elf_writer.h"
30#include "gc/accounting/card_table-inl.h"
31#include "gc/accounting/heap_bitmap.h"
32#include "gc/accounting/space_bitmap-inl.h"
33#include "gc/heap.h"
34#include "gc/space/large_object_space.h"
35#include "gc/space/space-inl.h"
36#include "globals.h"
37#include "image.h"
38#include "intern_table.h"
39#include "mirror/art_field-inl.h"
40#include "mirror/art_method-inl.h"
41#include "mirror/array-inl.h"
42#include "mirror/class-inl.h"
43#include "mirror/class_loader.h"
44#include "mirror/dex_cache-inl.h"
45#include "mirror/object-inl.h"
46#include "mirror/object_array-inl.h"
47#include "oat.h"
48#include "oat_file.h"
49#include "object_utils.h"
50#include "runtime.h"
51#include "scoped_thread_state_change.h"
52#include "sirt_ref.h"
53#include "UniquePtr.h"
54#include "utils.h"
55
56using ::art::mirror::ArtField;
57using ::art::mirror::ArtMethod;
58using ::art::mirror::Class;
59using ::art::mirror::DexCache;
60using ::art::mirror::EntryPointFromInterpreter;
61using ::art::mirror::Object;
62using ::art::mirror::ObjectArray;
63using ::art::mirror::String;
64
65namespace art {
66
67bool ImageWriter::Write(const std::string& image_filename,
68                        uintptr_t image_begin,
69                        const std::string& oat_filename,
70                        const std::string& oat_location) {
71  CHECK(!image_filename.empty());
72
73  CHECK_NE(image_begin, 0U);
74  image_begin_ = reinterpret_cast<byte*>(image_begin);
75
76  ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
77  const std::vector<DexCache*>& all_dex_caches = class_linker->GetDexCaches();
78  dex_caches_.insert(all_dex_caches.begin(), all_dex_caches.end());
79
80  UniquePtr<File> oat_file(OS::OpenFileReadWrite(oat_filename.c_str()));
81  if (oat_file.get() == NULL) {
82    LOG(ERROR) << "Failed to open oat file " << oat_filename << " for " << oat_location;
83    return false;
84  }
85  oat_file_ = OatFile::OpenWritable(oat_file.get(), oat_location);
86  if (oat_file_ == NULL) {
87    LOG(ERROR) << "Failed to open writable oat file " << oat_filename << " for " << oat_location;
88    return false;
89  }
90  class_linker->RegisterOatFile(*oat_file_);
91
92  interpreter_to_interpreter_bridge_offset_ =
93      oat_file_->GetOatHeader().GetInterpreterToInterpreterBridgeOffset();
94  interpreter_to_compiled_code_bridge_offset_ =
95      oat_file_->GetOatHeader().GetInterpreterToCompiledCodeBridgeOffset();
96
97  jni_dlsym_lookup_offset_ = oat_file_->GetOatHeader().GetJniDlsymLookupOffset();
98
99  portable_resolution_trampoline_offset_ =
100      oat_file_->GetOatHeader().GetPortableResolutionTrampolineOffset();
101  portable_to_interpreter_bridge_offset_ =
102      oat_file_->GetOatHeader().GetPortableToInterpreterBridgeOffset();
103
104  quick_resolution_trampoline_offset_ =
105      oat_file_->GetOatHeader().GetQuickResolutionTrampolineOffset();
106  quick_to_interpreter_bridge_offset_ =
107      oat_file_->GetOatHeader().GetQuickToInterpreterBridgeOffset();
108  {
109    Thread::Current()->TransitionFromSuspendedToRunnable();
110    PruneNonImageClasses();  // Remove junk
111    ComputeLazyFieldsForImageClasses();  // Add useful information
112    ComputeEagerResolvedStrings();
113    Thread::Current()->TransitionFromRunnableToSuspended(kNative);
114  }
115  gc::Heap* heap = Runtime::Current()->GetHeap();
116  heap->CollectGarbage(false);  // Remove garbage.
117  // Trim size of alloc spaces.
118  for (const auto& space : heap->GetContinuousSpaces()) {
119    if (space->IsDlMallocSpace()) {
120      space->AsDlMallocSpace()->Trim();
121    }
122  }
123
124  if (!AllocMemory()) {
125    return false;
126  }
127#ifndef NDEBUG
128  {  // NOLINT(whitespace/braces)
129    ScopedObjectAccess soa(Thread::Current());
130    CheckNonImageClassesRemoved();
131  }
132#endif
133  Thread::Current()->TransitionFromSuspendedToRunnable();
134  size_t oat_loaded_size = 0;
135  size_t oat_data_offset = 0;
136  ElfWriter::GetOatElfInformation(oat_file.get(), oat_loaded_size, oat_data_offset);
137  CalculateNewObjectOffsets(oat_loaded_size, oat_data_offset);
138  CopyAndFixupObjects();
139  PatchOatCodeAndMethods();
140  // Record allocations into the image bitmap.
141  RecordImageAllocations();
142  Thread::Current()->TransitionFromRunnableToSuspended(kNative);
143
144  UniquePtr<File> image_file(OS::CreateEmptyFile(image_filename.c_str()));
145  ImageHeader* image_header = reinterpret_cast<ImageHeader*>(image_->Begin());
146  if (image_file.get() == NULL) {
147    LOG(ERROR) << "Failed to open image file " << image_filename;
148    return false;
149  }
150  if (fchmod(image_file->Fd(), 0644) != 0) {
151    PLOG(ERROR) << "Failed to make image file world readable: " << image_filename;
152    return EXIT_FAILURE;
153  }
154
155  // Write out the image.
156  CHECK_EQ(image_end_, image_header->GetImageSize());
157  if (!image_file->WriteFully(image_->Begin(), image_end_)) {
158    PLOG(ERROR) << "Failed to write image file " << image_filename;
159    return false;
160  }
161
162  // Write out the image bitmap at the page aligned start of the image end.
163  CHECK_ALIGNED(image_header->GetImageBitmapOffset(), kPageSize);
164  if (!image_file->Write(reinterpret_cast<char*>(image_bitmap_->Begin()),
165                         image_header->GetImageBitmapSize(),
166                         image_header->GetImageBitmapOffset())) {
167    PLOG(ERROR) << "Failed to write image file " << image_filename;
168    return false;
169  }
170
171  return true;
172}
173
174void ImageWriter::RecordImageAllocations() {
175  uint64_t start_time = NanoTime();
176  CHECK(image_bitmap_.get() != nullptr);
177  for (const auto& it : offsets_) {
178    mirror::Object* obj = reinterpret_cast<mirror::Object*>(image_->Begin() + it.second);
179    DCHECK_ALIGNED(obj, kObjectAlignment);
180    image_bitmap_->Set(obj);
181  }
182  LOG(INFO) << "RecordImageAllocations took " << PrettyDuration(NanoTime() - start_time);
183}
184
185bool ImageWriter::AllocMemory() {
186  size_t size = 0;
187  for (const auto& space : Runtime::Current()->GetHeap()->GetContinuousSpaces()) {
188    if (space->IsDlMallocSpace()) {
189      size += space->Size();
190    }
191  }
192
193  int prot = PROT_READ | PROT_WRITE;
194  size_t length = RoundUp(size, kPageSize);
195  image_.reset(MemMap::MapAnonymous("image writer image", NULL, length, prot));
196  if (image_.get() == NULL) {
197    LOG(ERROR) << "Failed to allocate memory for image file generation";
198    return false;
199  }
200  return true;
201}
202
203void ImageWriter::ComputeLazyFieldsForImageClasses() {
204  Runtime* runtime = Runtime::Current();
205  ClassLinker* class_linker = runtime->GetClassLinker();
206  class_linker->VisitClassesWithoutClassesLock(ComputeLazyFieldsForClassesVisitor, NULL);
207}
208
209bool ImageWriter::ComputeLazyFieldsForClassesVisitor(Class* c, void* /*arg*/) {
210  c->ComputeName();
211  return true;
212}
213
214void ImageWriter::ComputeEagerResolvedStringsCallback(Object* obj, void* arg) {
215  if (!obj->GetClass()->IsStringClass()) {
216    return;
217  }
218  String* string = obj->AsString();
219  const uint16_t* utf16_string = string->GetCharArray()->GetData() + string->GetOffset();
220  ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
221  for (DexCache* dex_cache : writer->dex_caches_) {
222    const DexFile& dex_file = *dex_cache->GetDexFile();
223    const DexFile::StringId* string_id = dex_file.FindStringId(utf16_string);
224    if (string_id != NULL) {
225      // This string occurs in this dex file, assign the dex cache entry.
226      uint32_t string_idx = dex_file.GetIndexForStringId(*string_id);
227      if (dex_cache->GetResolvedString(string_idx) == NULL) {
228        dex_cache->SetResolvedString(string_idx, string);
229      }
230    }
231  }
232}
233
234void ImageWriter::ComputeEagerResolvedStrings()
235    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
236  // TODO: Check image spaces only?
237  gc::Heap* heap = Runtime::Current()->GetHeap();
238  WriterMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
239  heap->FlushAllocStack();
240  heap->GetLiveBitmap()->Walk(ComputeEagerResolvedStringsCallback, this);
241}
242
243bool ImageWriter::IsImageClass(const Class* klass) {
244  return compiler_driver_.IsImageClass(ClassHelper(klass).GetDescriptor());
245}
246
247struct NonImageClasses {
248  ImageWriter* image_writer;
249  std::set<std::string>* non_image_classes;
250};
251
252void ImageWriter::PruneNonImageClasses() {
253  if (compiler_driver_.GetImageClasses() == NULL) {
254    return;
255  }
256  Runtime* runtime = Runtime::Current();
257  ClassLinker* class_linker = runtime->GetClassLinker();
258
259  // Make a list of classes we would like to prune.
260  std::set<std::string> non_image_classes;
261  NonImageClasses context;
262  context.image_writer = this;
263  context.non_image_classes = &non_image_classes;
264  class_linker->VisitClasses(NonImageClassesVisitor, &context);
265
266  // Remove the undesired classes from the class roots.
267  for (const std::string& it : non_image_classes) {
268    class_linker->RemoveClass(it.c_str(), NULL);
269  }
270
271  // Clear references to removed classes from the DexCaches.
272  ArtMethod* resolution_method = runtime->GetResolutionMethod();
273  for (DexCache* dex_cache : dex_caches_) {
274    for (size_t i = 0; i < dex_cache->NumResolvedTypes(); i++) {
275      Class* klass = dex_cache->GetResolvedType(i);
276      if (klass != NULL && !IsImageClass(klass)) {
277        dex_cache->SetResolvedType(i, NULL);
278        dex_cache->GetInitializedStaticStorage()->Set(i, NULL);
279      }
280    }
281    for (size_t i = 0; i < dex_cache->NumResolvedMethods(); i++) {
282      ArtMethod* method = dex_cache->GetResolvedMethod(i);
283      if (method != NULL && !IsImageClass(method->GetDeclaringClass())) {
284        dex_cache->SetResolvedMethod(i, resolution_method);
285      }
286    }
287    for (size_t i = 0; i < dex_cache->NumResolvedFields(); i++) {
288      ArtField* field = dex_cache->GetResolvedField(i);
289      if (field != NULL && !IsImageClass(field->GetDeclaringClass())) {
290        dex_cache->SetResolvedField(i, NULL);
291      }
292    }
293  }
294}
295
296bool ImageWriter::NonImageClassesVisitor(Class* klass, void* arg) {
297  NonImageClasses* context = reinterpret_cast<NonImageClasses*>(arg);
298  if (!context->image_writer->IsImageClass(klass)) {
299    context->non_image_classes->insert(ClassHelper(klass).GetDescriptor());
300  }
301  return true;
302}
303
304void ImageWriter::CheckNonImageClassesRemoved()
305    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
306  if (compiler_driver_.GetImageClasses() == NULL) {
307    return;
308  }
309
310  gc::Heap* heap = Runtime::Current()->GetHeap();
311  Thread* self = Thread::Current();
312  {
313    WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
314    heap->FlushAllocStack();
315  }
316
317  ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
318  heap->GetLiveBitmap()->Walk(CheckNonImageClassesRemovedCallback, this);
319}
320
321void ImageWriter::CheckNonImageClassesRemovedCallback(Object* obj, void* arg) {
322  ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg);
323  if (!obj->IsClass()) {
324    return;
325  }
326  Class* klass = obj->AsClass();
327  if (!image_writer->IsImageClass(klass)) {
328    image_writer->DumpImageClasses();
329    CHECK(image_writer->IsImageClass(klass)) << ClassHelper(klass).GetDescriptor()
330                                             << " " << PrettyDescriptor(klass);
331  }
332}
333
334void ImageWriter::DumpImageClasses() {
335  CompilerDriver::DescriptorSet* image_classes = compiler_driver_.GetImageClasses();
336  CHECK(image_classes != NULL);
337  for (const std::string& image_class : *image_classes) {
338    LOG(INFO) << " " << image_class;
339  }
340}
341
342void ImageWriter::CalculateNewObjectOffsetsCallback(Object* obj, void* arg) {
343  DCHECK(obj != NULL);
344  DCHECK(arg != NULL);
345  ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg);
346
347  // if it is a string, we want to intern it if its not interned.
348  if (obj->GetClass()->IsStringClass()) {
349    // we must be an interned string that was forward referenced and already assigned
350    if (image_writer->IsImageOffsetAssigned(obj)) {
351      DCHECK_EQ(obj, obj->AsString()->Intern());
352      return;
353    }
354    SirtRef<String> interned(Thread::Current(), obj->AsString()->Intern());
355    if (obj != interned.get()) {
356      if (!image_writer->IsImageOffsetAssigned(interned.get())) {
357        // interned obj is after us, allocate its location early
358        image_writer->AssignImageOffset(interned.get());
359      }
360      // point those looking for this object to the interned version.
361      image_writer->SetImageOffset(obj, image_writer->GetImageOffset(interned.get()));
362      return;
363    }
364    // else (obj == interned), nothing to do but fall through to the normal case
365  }
366
367  image_writer->AssignImageOffset(obj);
368}
369
370ObjectArray<Object>* ImageWriter::CreateImageRoots() const {
371  Runtime* runtime = Runtime::Current();
372  ClassLinker* class_linker = runtime->GetClassLinker();
373  Class* object_array_class = class_linker->FindSystemClass("[Ljava/lang/Object;");
374  Thread* self = Thread::Current();
375
376  // build an Object[] of all the DexCaches used in the source_space_
377  ObjectArray<Object>* dex_caches = ObjectArray<Object>::Alloc(self, object_array_class,
378                                                               dex_caches_.size());
379  int i = 0;
380  for (DexCache* dex_cache : dex_caches_) {
381    dex_caches->Set(i++, dex_cache);
382  }
383
384  // build an Object[] of the roots needed to restore the runtime
385  SirtRef<ObjectArray<Object> >
386      image_roots(self,
387                  ObjectArray<Object>::Alloc(self, object_array_class,
388                                             ImageHeader::kImageRootsMax));
389  image_roots->Set(ImageHeader::kResolutionMethod, runtime->GetResolutionMethod());
390  image_roots->Set(ImageHeader::kCalleeSaveMethod,
391                   runtime->GetCalleeSaveMethod(Runtime::kSaveAll));
392  image_roots->Set(ImageHeader::kRefsOnlySaveMethod,
393                   runtime->GetCalleeSaveMethod(Runtime::kRefsOnly));
394  image_roots->Set(ImageHeader::kRefsAndArgsSaveMethod,
395                   runtime->GetCalleeSaveMethod(Runtime::kRefsAndArgs));
396  image_roots->Set(ImageHeader::kOatLocation,
397                   String::AllocFromModifiedUtf8(self, oat_file_->GetLocation().c_str()));
398  image_roots->Set(ImageHeader::kDexCaches,
399                   dex_caches);
400  image_roots->Set(ImageHeader::kClassRoots,
401                   class_linker->GetClassRoots());
402  for (int i = 0; i < ImageHeader::kImageRootsMax; i++) {
403    CHECK(image_roots->Get(i) != NULL);
404  }
405  return image_roots.get();
406}
407
408void ImageWriter::CalculateNewObjectOffsets(size_t oat_loaded_size, size_t oat_data_offset) {
409  CHECK_NE(0U, oat_loaded_size);
410  Thread* self = Thread::Current();
411  SirtRef<ObjectArray<Object> > image_roots(self, CreateImageRoots());
412
413  gc::Heap* heap = Runtime::Current()->GetHeap();
414  const auto& spaces = heap->GetContinuousSpaces();
415  DCHECK(!spaces.empty());
416  DCHECK_EQ(0U, image_end_);
417
418  // Leave space for the header, but do not write it yet, we need to
419  // know where image_roots is going to end up
420  image_end_ += RoundUp(sizeof(ImageHeader), 8);  // 64-bit-alignment
421
422  {
423    WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
424    heap->FlushAllocStack();
425    // TODO: Image spaces only?
426    // TODO: Add InOrderWalk to heap bitmap.
427    const char* old = self->StartAssertNoThreadSuspension("ImageWriter");
428    DCHECK(heap->GetLargeObjectsSpace()->GetLiveObjects()->IsEmpty());
429    for (const auto& space : spaces) {
430      space->GetLiveBitmap()->InOrderWalk(CalculateNewObjectOffsetsCallback, this);
431      DCHECK_LT(image_end_, image_->Size());
432    }
433    self->EndAssertNoThreadSuspension(old);
434  }
435
436  // Create the image bitmap.
437  image_bitmap_.reset(gc::accounting::SpaceBitmap::Create("image bitmap", image_->Begin(),
438                                                          image_end_));
439  const byte* oat_file_begin = image_begin_ + RoundUp(image_end_, kPageSize);
440  const byte* oat_file_end = oat_file_begin + oat_loaded_size;
441  oat_data_begin_ = oat_file_begin + oat_data_offset;
442  const byte* oat_data_end = oat_data_begin_ + oat_file_->Size();
443
444  // Return to write header at start of image with future location of image_roots. At this point,
445  // image_end_ is the size of the image (excluding bitmaps).
446  ImageHeader image_header(reinterpret_cast<uint32_t>(image_begin_),
447                           static_cast<uint32_t>(image_end_),
448                           RoundUp(image_end_, kPageSize),
449                           image_bitmap_->Size(),
450                           reinterpret_cast<uint32_t>(GetImageAddress(image_roots.get())),
451                           oat_file_->GetOatHeader().GetChecksum(),
452                           reinterpret_cast<uint32_t>(oat_file_begin),
453                           reinterpret_cast<uint32_t>(oat_data_begin_),
454                           reinterpret_cast<uint32_t>(oat_data_end),
455                           reinterpret_cast<uint32_t>(oat_file_end));
456  memcpy(image_->Begin(), &image_header, sizeof(image_header));
457
458  // Note that image_end_ is left at end of used space
459}
460
461void ImageWriter::CopyAndFixupObjects()
462    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
463  Thread* self = Thread::Current();
464  const char* old_cause = self->StartAssertNoThreadSuspension("ImageWriter");
465  gc::Heap* heap = Runtime::Current()->GetHeap();
466  // TODO: heap validation can't handle this fix up pass
467  heap->DisableObjectValidation();
468  // TODO: Image spaces only?
469  WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
470  heap->FlushAllocStack();
471  heap->GetLiveBitmap()->Walk(CopyAndFixupObjectsCallback, this);
472  self->EndAssertNoThreadSuspension(old_cause);
473}
474
475void ImageWriter::CopyAndFixupObjectsCallback(Object* object, void* arg) {
476  DCHECK(object != NULL);
477  DCHECK(arg != NULL);
478  const Object* obj = object;
479  ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg);
480
481  // see GetLocalAddress for similar computation
482  size_t offset = image_writer->GetImageOffset(obj);
483  byte* dst = image_writer->image_->Begin() + offset;
484  const byte* src = reinterpret_cast<const byte*>(obj);
485  size_t n = obj->SizeOf();
486  DCHECK_LT(offset + n, image_writer->image_->Size());
487  memcpy(dst, src, n);
488  Object* copy = reinterpret_cast<Object*>(dst);
489  copy->SetField32(Object::MonitorOffset(), 0, false);  // We may have inflated the lock during compilation.
490  image_writer->FixupObject(obj, copy);
491}
492
493void ImageWriter::FixupObject(const Object* orig, Object* copy) {
494  DCHECK(orig != NULL);
495  DCHECK(copy != NULL);
496  copy->SetClass(down_cast<Class*>(GetImageAddress(orig->GetClass())));
497  // TODO: special case init of pointers to malloc data (or removal of these pointers)
498  if (orig->IsClass()) {
499    FixupClass(orig->AsClass(), down_cast<Class*>(copy));
500  } else if (orig->IsObjectArray()) {
501    FixupObjectArray(orig->AsObjectArray<Object>(), down_cast<ObjectArray<Object>*>(copy));
502  } else if (orig->IsArtMethod()) {
503    FixupMethod(orig->AsArtMethod(), down_cast<ArtMethod*>(copy));
504  } else {
505    FixupInstanceFields(orig, copy);
506  }
507}
508
509void ImageWriter::FixupClass(const Class* orig, Class* copy) {
510  FixupInstanceFields(orig, copy);
511  FixupStaticFields(orig, copy);
512}
513
514void ImageWriter::FixupMethod(const ArtMethod* orig, ArtMethod* copy) {
515  FixupInstanceFields(orig, copy);
516
517  // OatWriter replaces the code_ with an offset value. Here we re-adjust to a pointer relative to
518  // oat_begin_
519
520  // The resolution method has a special trampoline to call.
521  if (UNLIKELY(orig == Runtime::Current()->GetResolutionMethod())) {
522#if defined(ART_USE_PORTABLE_COMPILER)
523    copy->SetEntryPointFromCompiledCode(GetOatAddress(portable_resolution_trampoline_offset_));
524#else
525    copy->SetEntryPointFromCompiledCode(GetOatAddress(quick_resolution_trampoline_offset_));
526#endif
527  } else {
528    // We assume all methods have code. If they don't currently then we set them to the use the
529    // resolution trampoline. Abstract methods never have code and so we need to make sure their
530    // use results in an AbstractMethodError. We use the interpreter to achieve this.
531    if (UNLIKELY(orig->IsAbstract())) {
532#if defined(ART_USE_PORTABLE_COMPILER)
533      copy->SetEntryPointFromCompiledCode(GetOatAddress(portable_to_interpreter_bridge_offset_));
534#else
535      copy->SetEntryPointFromCompiledCode(GetOatAddress(quick_to_interpreter_bridge_offset_));
536#endif
537      copy->SetEntryPointFromInterpreter(reinterpret_cast<EntryPointFromInterpreter*>
538      (GetOatAddress(interpreter_to_interpreter_bridge_offset_)));
539    } else {
540      copy->SetEntryPointFromInterpreter(reinterpret_cast<EntryPointFromInterpreter*>
541      (GetOatAddress(interpreter_to_compiled_code_bridge_offset_)));
542      // Use original code if it exists. Otherwise, set the code pointer to the resolution
543      // trampoline.
544      const byte* code = GetOatAddress(orig->GetOatCodeOffset());
545      if (code != NULL) {
546        copy->SetEntryPointFromCompiledCode(code);
547      } else {
548#if defined(ART_USE_PORTABLE_COMPILER)
549        copy->SetEntryPointFromCompiledCode(GetOatAddress(portable_resolution_trampoline_offset_));
550#else
551        copy->SetEntryPointFromCompiledCode(GetOatAddress(quick_resolution_trampoline_offset_));
552#endif
553      }
554      if (orig->IsNative()) {
555        // The native method's pointer is set to a stub to lookup via dlsym.
556        // Note this is not the code_ pointer, that is handled above.
557        copy->SetNativeMethod(GetOatAddress(jni_dlsym_lookup_offset_));
558      } else {
559        // Normal (non-abstract non-native) methods have various tables to relocate.
560        uint32_t mapping_table_off = orig->GetOatMappingTableOffset();
561        const byte* mapping_table = GetOatAddress(mapping_table_off);
562        copy->SetMappingTable(mapping_table);
563
564        uint32_t vmap_table_offset = orig->GetOatVmapTableOffset();
565        const byte* vmap_table = GetOatAddress(vmap_table_offset);
566        copy->SetVmapTable(vmap_table);
567
568        uint32_t native_gc_map_offset = orig->GetOatNativeGcMapOffset();
569        const byte* native_gc_map = GetOatAddress(native_gc_map_offset);
570        copy->SetNativeGcMap(reinterpret_cast<const uint8_t*>(native_gc_map));
571      }
572    }
573  }
574}
575
576void ImageWriter::FixupObjectArray(const ObjectArray<Object>* orig, ObjectArray<Object>* copy) {
577  for (int32_t i = 0; i < orig->GetLength(); ++i) {
578    const Object* element = orig->Get(i);
579    copy->SetPtrWithoutChecks(i, GetImageAddress(element));
580  }
581}
582
583void ImageWriter::FixupInstanceFields(const Object* orig, Object* copy) {
584  DCHECK(orig != NULL);
585  DCHECK(copy != NULL);
586  Class* klass = orig->GetClass();
587  DCHECK(klass != NULL);
588  FixupFields(orig,
589              copy,
590              klass->GetReferenceInstanceOffsets(),
591              false);
592}
593
594void ImageWriter::FixupStaticFields(const Class* orig, Class* copy) {
595  DCHECK(orig != NULL);
596  DCHECK(copy != NULL);
597  FixupFields(orig,
598              copy,
599              orig->GetReferenceStaticOffsets(),
600              true);
601}
602
603void ImageWriter::FixupFields(const Object* orig,
604                              Object* copy,
605                              uint32_t ref_offsets,
606                              bool is_static) {
607  if (ref_offsets != CLASS_WALK_SUPER) {
608    // Found a reference offset bitmap.  Fixup the specified offsets.
609    while (ref_offsets != 0) {
610      size_t right_shift = CLZ(ref_offsets);
611      MemberOffset byte_offset = CLASS_OFFSET_FROM_CLZ(right_shift);
612      const Object* ref = orig->GetFieldObject<const Object*>(byte_offset, false);
613      // Use SetFieldPtr to avoid card marking since we are writing to the image.
614      copy->SetFieldPtr(byte_offset, GetImageAddress(ref), false);
615      ref_offsets &= ~(CLASS_HIGH_BIT >> right_shift);
616    }
617  } else {
618    // There is no reference offset bitmap.  In the non-static case,
619    // walk up the class inheritance hierarchy and find reference
620    // offsets the hard way. In the static case, just consider this
621    // class.
622    for (const Class *klass = is_static ? orig->AsClass() : orig->GetClass();
623         klass != NULL;
624         klass = is_static ? NULL : klass->GetSuperClass()) {
625      size_t num_reference_fields = (is_static
626                                     ? klass->NumReferenceStaticFields()
627                                     : klass->NumReferenceInstanceFields());
628      for (size_t i = 0; i < num_reference_fields; ++i) {
629        ArtField* field = (is_static
630                           ? klass->GetStaticField(i)
631                           : klass->GetInstanceField(i));
632        MemberOffset field_offset = field->GetOffset();
633        const Object* ref = orig->GetFieldObject<const Object*>(field_offset, false);
634        // Use SetFieldPtr to avoid card marking since we are writing to the image.
635        copy->SetFieldPtr(field_offset, GetImageAddress(ref), false);
636      }
637    }
638  }
639  if (!is_static && orig->IsReferenceInstance()) {
640    // Fix-up referent, that isn't marked as an object field, for References.
641    ArtField* field = orig->GetClass()->FindInstanceField("referent", "Ljava/lang/Object;");
642    MemberOffset field_offset = field->GetOffset();
643    const Object* ref = orig->GetFieldObject<const Object*>(field_offset, false);
644    // Use SetFieldPtr to avoid card marking since we are writing to the image.
645    copy->SetFieldPtr(field_offset, GetImageAddress(ref), false);
646  }
647}
648
649static ArtMethod* GetTargetMethod(const CompilerDriver::PatchInformation* patch)
650    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
651  ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
652  DexCache* dex_cache = class_linker->FindDexCache(patch->GetDexFile());
653  ArtMethod* method = class_linker->ResolveMethod(patch->GetDexFile(),
654                                                  patch->GetTargetMethodIdx(),
655                                                  dex_cache,
656                                                  NULL,
657                                                  NULL,
658                                                  patch->GetTargetInvokeType());
659  CHECK(method != NULL)
660    << patch->GetDexFile().GetLocation() << " " << patch->GetTargetMethodIdx();
661  CHECK(!method->IsRuntimeMethod())
662    << patch->GetDexFile().GetLocation() << " " << patch->GetTargetMethodIdx();
663  CHECK(dex_cache->GetResolvedMethods()->Get(patch->GetTargetMethodIdx()) == method)
664    << patch->GetDexFile().GetLocation() << " " << patch->GetReferrerMethodIdx() << " "
665    << PrettyMethod(dex_cache->GetResolvedMethods()->Get(patch->GetTargetMethodIdx())) << " "
666    << PrettyMethod(method);
667  return method;
668}
669
670void ImageWriter::PatchOatCodeAndMethods() {
671  Thread* self = Thread::Current();
672  ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
673  const char* old_cause = self->StartAssertNoThreadSuspension("ImageWriter");
674
675  typedef std::vector<const CompilerDriver::PatchInformation*> Patches;
676  const Patches& code_to_patch = compiler_driver_.GetCodeToPatch();
677  for (size_t i = 0; i < code_to_patch.size(); i++) {
678    const CompilerDriver::PatchInformation* patch = code_to_patch[i];
679    ArtMethod* target = GetTargetMethod(patch);
680    uint32_t code = reinterpret_cast<uint32_t>(class_linker->GetOatCodeFor(target));
681    uint32_t code_base = reinterpret_cast<uint32_t>(&oat_file_->GetOatHeader());
682    uint32_t code_offset = code - code_base;
683    SetPatchLocation(patch, reinterpret_cast<uint32_t>(GetOatAddress(code_offset)));
684  }
685
686  const Patches& methods_to_patch = compiler_driver_.GetMethodsToPatch();
687  for (size_t i = 0; i < methods_to_patch.size(); i++) {
688    const CompilerDriver::PatchInformation* patch = methods_to_patch[i];
689    ArtMethod* target = GetTargetMethod(patch);
690    SetPatchLocation(patch, reinterpret_cast<uint32_t>(GetImageAddress(target)));
691  }
692
693  // Update the image header with the new checksum after patching
694  ImageHeader* image_header = reinterpret_cast<ImageHeader*>(image_->Begin());
695  image_header->SetOatChecksum(oat_file_->GetOatHeader().GetChecksum());
696  self->EndAssertNoThreadSuspension(old_cause);
697}
698
699void ImageWriter::SetPatchLocation(const CompilerDriver::PatchInformation* patch, uint32_t value) {
700  ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
701  const void* oat_code = class_linker->GetOatCodeFor(patch->GetDexFile(),
702                                                     patch->GetReferrerClassDefIdx(),
703                                                     patch->GetReferrerMethodIdx());
704  OatHeader& oat_header = const_cast<OatHeader&>(oat_file_->GetOatHeader());
705  // TODO: make this Thumb2 specific
706  uint8_t* base = reinterpret_cast<uint8_t*>(reinterpret_cast<uint32_t>(oat_code) & ~0x1);
707  uint32_t* patch_location = reinterpret_cast<uint32_t*>(base + patch->GetLiteralOffset());
708#ifndef NDEBUG
709  const DexFile::MethodId& id = patch->GetDexFile().GetMethodId(patch->GetTargetMethodIdx());
710  uint32_t expected = reinterpret_cast<uint32_t>(&id);
711  uint32_t actual = *patch_location;
712  CHECK(actual == expected || actual == value) << std::hex
713    << "actual=" << actual
714    << "expected=" << expected
715    << "value=" << value;
716#endif
717  *patch_location = value;
718  oat_header.UpdateChecksum(patch_location, sizeof(value));
719}
720
721}  // namespace art
722