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