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