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