image_writer.cc revision 90ca5c0301651101de0e363842e5d08ae65233f7
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 <memory>
22#include <vector>
23
24#include "base/logging.h"
25#include "base/unix_file/fd_file.h"
26#include "class_linker.h"
27#include "compiled_method.h"
28#include "dex_file-inl.h"
29#include "driver/compiler_driver.h"
30#include "elf_file.h"
31#include "elf_utils.h"
32#include "elf_patcher.h"
33#include "elf_writer.h"
34#include "gc/accounting/card_table-inl.h"
35#include "gc/accounting/heap_bitmap.h"
36#include "gc/accounting/space_bitmap-inl.h"
37#include "gc/heap.h"
38#include "gc/space/large_object_space.h"
39#include "gc/space/space-inl.h"
40#include "globals.h"
41#include "image.h"
42#include "intern_table.h"
43#include "lock_word.h"
44#include "mirror/art_field-inl.h"
45#include "mirror/art_method-inl.h"
46#include "mirror/array-inl.h"
47#include "mirror/class-inl.h"
48#include "mirror/class_loader.h"
49#include "mirror/dex_cache-inl.h"
50#include "mirror/object-inl.h"
51#include "mirror/object_array-inl.h"
52#include "mirror/string-inl.h"
53#include "oat.h"
54#include "oat_file.h"
55#include "runtime.h"
56#include "scoped_thread_state_change.h"
57#include "handle_scope-inl.h"
58#include "utils.h"
59
60using ::art::mirror::ArtField;
61using ::art::mirror::ArtMethod;
62using ::art::mirror::Class;
63using ::art::mirror::DexCache;
64using ::art::mirror::EntryPointFromInterpreter;
65using ::art::mirror::Object;
66using ::art::mirror::ObjectArray;
67using ::art::mirror::String;
68
69namespace art {
70
71bool ImageWriter::Write(const std::string& image_filename,
72                        uintptr_t image_begin,
73                        const std::string& oat_filename,
74                        const std::string& oat_location,
75                        bool compile_pic) {
76  CHECK(!image_filename.empty());
77
78  CHECK_NE(image_begin, 0U);
79  image_begin_ = reinterpret_cast<byte*>(image_begin);
80  compile_pic_ = compile_pic;
81
82  ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
83
84  std::unique_ptr<File> oat_file(OS::OpenFileReadWrite(oat_filename.c_str()));
85  if (oat_file.get() == NULL) {
86    LOG(ERROR) << "Failed to open oat file " << oat_filename << " for " << oat_location;
87    return false;
88  }
89  std::string error_msg;
90  oat_file_ = OatFile::OpenReadable(oat_file.get(), oat_location, &error_msg);
91  if (oat_file_ == nullptr) {
92    LOG(ERROR) << "Failed to open writable oat file " << oat_filename << " for " << oat_location
93        << ": " << error_msg;
94    return false;
95  }
96  CHECK_EQ(class_linker->RegisterOatFile(oat_file_), oat_file_);
97
98  interpreter_to_interpreter_bridge_offset_ =
99      oat_file_->GetOatHeader().GetInterpreterToInterpreterBridgeOffset();
100  interpreter_to_compiled_code_bridge_offset_ =
101      oat_file_->GetOatHeader().GetInterpreterToCompiledCodeBridgeOffset();
102
103  jni_dlsym_lookup_offset_ = oat_file_->GetOatHeader().GetJniDlsymLookupOffset();
104
105  portable_imt_conflict_trampoline_offset_ =
106      oat_file_->GetOatHeader().GetPortableImtConflictTrampolineOffset();
107  portable_resolution_trampoline_offset_ =
108      oat_file_->GetOatHeader().GetPortableResolutionTrampolineOffset();
109  portable_to_interpreter_bridge_offset_ =
110      oat_file_->GetOatHeader().GetPortableToInterpreterBridgeOffset();
111
112  quick_generic_jni_trampoline_offset_ =
113      oat_file_->GetOatHeader().GetQuickGenericJniTrampolineOffset();
114  quick_imt_conflict_trampoline_offset_ =
115      oat_file_->GetOatHeader().GetQuickImtConflictTrampolineOffset();
116  quick_resolution_trampoline_offset_ =
117      oat_file_->GetOatHeader().GetQuickResolutionTrampolineOffset();
118  quick_to_interpreter_bridge_offset_ =
119      oat_file_->GetOatHeader().GetQuickToInterpreterBridgeOffset();
120  {
121    Thread::Current()->TransitionFromSuspendedToRunnable();
122    PruneNonImageClasses();  // Remove junk
123    ComputeLazyFieldsForImageClasses();  // Add useful information
124    ComputeEagerResolvedStrings();
125    Thread::Current()->TransitionFromRunnableToSuspended(kNative);
126  }
127  gc::Heap* heap = Runtime::Current()->GetHeap();
128  heap->CollectGarbage(false);  // Remove garbage.
129
130  if (!AllocMemory()) {
131    return false;
132  }
133
134  if (kIsDebugBuild) {
135    ScopedObjectAccess soa(Thread::Current());
136    CheckNonImageClassesRemoved();
137  }
138
139  Thread::Current()->TransitionFromSuspendedToRunnable();
140  size_t oat_loaded_size = 0;
141  size_t oat_data_offset = 0;
142  ElfWriter::GetOatElfInformation(oat_file.get(), oat_loaded_size, oat_data_offset);
143  CalculateNewObjectOffsets(oat_loaded_size, oat_data_offset);
144  CopyAndFixupObjects();
145
146  PatchOatCodeAndMethods(oat_file.get());
147  Thread::Current()->TransitionFromRunnableToSuspended(kNative);
148
149  std::unique_ptr<File> image_file(OS::CreateEmptyFile(image_filename.c_str()));
150  ImageHeader* image_header = reinterpret_cast<ImageHeader*>(image_->Begin());
151  if (image_file.get() == NULL) {
152    LOG(ERROR) << "Failed to open image file " << image_filename;
153    return false;
154  }
155  if (fchmod(image_file->Fd(), 0644) != 0) {
156    PLOG(ERROR) << "Failed to make image file world readable: " << image_filename;
157    return EXIT_FAILURE;
158  }
159
160  // Write out the image.
161  CHECK_EQ(image_end_, image_header->GetImageSize());
162  if (!image_file->WriteFully(image_->Begin(), image_end_)) {
163    PLOG(ERROR) << "Failed to write image file " << image_filename;
164    return false;
165  }
166
167  // Write out the image bitmap at the page aligned start of the image end.
168  CHECK_ALIGNED(image_header->GetImageBitmapOffset(), kPageSize);
169  if (!image_file->Write(reinterpret_cast<char*>(image_bitmap_->Begin()),
170                         image_header->GetImageBitmapSize(),
171                         image_header->GetImageBitmapOffset())) {
172    PLOG(ERROR) << "Failed to write image file " << image_filename;
173    return false;
174  }
175
176  return true;
177}
178
179void ImageWriter::SetImageOffset(mirror::Object* object, size_t offset) {
180  DCHECK(object != nullptr);
181  DCHECK_NE(offset, 0U);
182  DCHECK(!IsImageOffsetAssigned(object));
183  mirror::Object* obj = reinterpret_cast<mirror::Object*>(image_->Begin() + offset);
184  DCHECK_ALIGNED(obj, kObjectAlignment);
185  image_bitmap_->Set(obj);
186  // Before we stomp over the lock word, save the hash code for later.
187  Monitor::Deflate(Thread::Current(), object);;
188  LockWord lw(object->GetLockWord(false));
189  switch (lw.GetState()) {
190    case LockWord::kFatLocked: {
191      LOG(FATAL) << "Fat locked object " << obj << " found during object copy";
192      break;
193    }
194    case LockWord::kThinLocked: {
195      LOG(FATAL) << "Thin locked object " << obj << " found during object copy";
196      break;
197    }
198    case LockWord::kUnlocked:
199      // No hash, don't need to save it.
200      break;
201    case LockWord::kHashCode:
202      saved_hashes_.push_back(std::make_pair(obj, lw.GetHashCode()));
203      break;
204    default:
205      LOG(FATAL) << "Unreachable.";
206      break;
207  }
208  object->SetLockWord(LockWord::FromForwardingAddress(offset), false);
209  DCHECK(IsImageOffsetAssigned(object));
210}
211
212void ImageWriter::AssignImageOffset(mirror::Object* object) {
213  DCHECK(object != nullptr);
214  SetImageOffset(object, image_end_);
215  image_end_ += RoundUp(object->SizeOf(), 8);  // 64-bit alignment
216  DCHECK_LT(image_end_, image_->Size());
217}
218
219bool ImageWriter::IsImageOffsetAssigned(mirror::Object* object) const {
220  DCHECK(object != nullptr);
221  return object->GetLockWord(false).GetState() == LockWord::kForwardingAddress;
222}
223
224size_t ImageWriter::GetImageOffset(mirror::Object* object) const {
225  DCHECK(object != nullptr);
226  DCHECK(IsImageOffsetAssigned(object));
227  LockWord lock_word = object->GetLockWord(false);
228  size_t offset = lock_word.ForwardingAddress();
229  DCHECK_LT(offset, image_end_);
230  return offset;
231}
232
233bool ImageWriter::AllocMemory() {
234  size_t length = RoundUp(Runtime::Current()->GetHeap()->GetTotalMemory(), kPageSize);
235  std::string error_msg;
236  image_.reset(MemMap::MapAnonymous("image writer image", NULL, length, PROT_READ | PROT_WRITE,
237                                    true, &error_msg));
238  if (UNLIKELY(image_.get() == nullptr)) {
239    LOG(ERROR) << "Failed to allocate memory for image file generation: " << error_msg;
240    return false;
241  }
242
243  // Create the image bitmap.
244  image_bitmap_.reset(gc::accounting::ContinuousSpaceBitmap::Create("image bitmap", image_->Begin(),
245                                                                    length));
246  if (image_bitmap_.get() == nullptr) {
247    LOG(ERROR) << "Failed to allocate memory for image bitmap";
248    return false;
249  }
250  return true;
251}
252
253void ImageWriter::ComputeLazyFieldsForImageClasses() {
254  ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
255  class_linker->VisitClassesWithoutClassesLock(ComputeLazyFieldsForClassesVisitor, NULL);
256}
257
258bool ImageWriter::ComputeLazyFieldsForClassesVisitor(Class* c, void* /*arg*/) {
259  Thread* self = Thread::Current();
260  StackHandleScope<1> hs(self);
261  mirror::Class::ComputeName(hs.NewHandle(c));
262  return true;
263}
264
265void ImageWriter::ComputeEagerResolvedStringsCallback(Object* obj, void* arg) {
266  if (!obj->GetClass()->IsStringClass()) {
267    return;
268  }
269  mirror::String* string = obj->AsString();
270  const uint16_t* utf16_string = string->GetCharArray()->GetData() + string->GetOffset();
271  ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
272  ReaderMutexLock mu(Thread::Current(), *class_linker->DexLock());
273  size_t dex_cache_count = class_linker->GetDexCacheCount();
274  for (size_t i = 0; i < dex_cache_count; ++i) {
275    DexCache* dex_cache = class_linker->GetDexCache(i);
276    const DexFile& dex_file = *dex_cache->GetDexFile();
277    const DexFile::StringId* string_id;
278    if (UNLIKELY(string->GetLength() == 0)) {
279      string_id = dex_file.FindStringId("");
280    } else {
281      string_id = dex_file.FindStringId(utf16_string);
282    }
283    if (string_id != nullptr) {
284      // This string occurs in this dex file, assign the dex cache entry.
285      uint32_t string_idx = dex_file.GetIndexForStringId(*string_id);
286      if (dex_cache->GetResolvedString(string_idx) == NULL) {
287        dex_cache->SetResolvedString(string_idx, string);
288      }
289    }
290  }
291}
292
293void ImageWriter::ComputeEagerResolvedStrings() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
294  ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
295  Runtime::Current()->GetHeap()->VisitObjects(ComputeEagerResolvedStringsCallback, this);
296}
297
298bool ImageWriter::IsImageClass(Class* klass) {
299  std::string temp;
300  return compiler_driver_.IsImageClass(klass->GetDescriptor(&temp));
301}
302
303struct NonImageClasses {
304  ImageWriter* image_writer;
305  std::set<std::string>* non_image_classes;
306};
307
308void ImageWriter::PruneNonImageClasses() {
309  if (compiler_driver_.GetImageClasses() == NULL) {
310    return;
311  }
312  Runtime* runtime = Runtime::Current();
313  ClassLinker* class_linker = runtime->GetClassLinker();
314
315  // Make a list of classes we would like to prune.
316  std::set<std::string> non_image_classes;
317  NonImageClasses context;
318  context.image_writer = this;
319  context.non_image_classes = &non_image_classes;
320  class_linker->VisitClasses(NonImageClassesVisitor, &context);
321
322  // Remove the undesired classes from the class roots.
323  for (const std::string& it : non_image_classes) {
324    class_linker->RemoveClass(it.c_str(), NULL);
325  }
326
327  // Clear references to removed classes from the DexCaches.
328  ArtMethod* resolution_method = runtime->GetResolutionMethod();
329  ReaderMutexLock mu(Thread::Current(), *class_linker->DexLock());
330  size_t dex_cache_count = class_linker->GetDexCacheCount();
331  for (size_t idx = 0; idx < dex_cache_count; ++idx) {
332    DexCache* dex_cache = class_linker->GetDexCache(idx);
333    for (size_t i = 0; i < dex_cache->NumResolvedTypes(); i++) {
334      Class* klass = dex_cache->GetResolvedType(i);
335      if (klass != NULL && !IsImageClass(klass)) {
336        dex_cache->SetResolvedType(i, NULL);
337      }
338    }
339    for (size_t i = 0; i < dex_cache->NumResolvedMethods(); i++) {
340      ArtMethod* method = dex_cache->GetResolvedMethod(i);
341      if (method != NULL && !IsImageClass(method->GetDeclaringClass())) {
342        dex_cache->SetResolvedMethod(i, resolution_method);
343      }
344    }
345    for (size_t i = 0; i < dex_cache->NumResolvedFields(); i++) {
346      ArtField* field = dex_cache->GetResolvedField(i);
347      if (field != NULL && !IsImageClass(field->GetDeclaringClass())) {
348        dex_cache->SetResolvedField(i, NULL);
349      }
350    }
351  }
352}
353
354bool ImageWriter::NonImageClassesVisitor(Class* klass, void* arg) {
355  NonImageClasses* context = reinterpret_cast<NonImageClasses*>(arg);
356  if (!context->image_writer->IsImageClass(klass)) {
357    std::string temp;
358    context->non_image_classes->insert(klass->GetDescriptor(&temp));
359  }
360  return true;
361}
362
363void ImageWriter::CheckNonImageClassesRemoved()
364    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
365  if (compiler_driver_.GetImageClasses() != nullptr) {
366    gc::Heap* heap = Runtime::Current()->GetHeap();
367    ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
368    heap->VisitObjects(CheckNonImageClassesRemovedCallback, this);
369  }
370}
371
372void ImageWriter::CheckNonImageClassesRemovedCallback(Object* obj, void* arg) {
373  ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg);
374  if (obj->IsClass()) {
375    Class* klass = obj->AsClass();
376    if (!image_writer->IsImageClass(klass)) {
377      image_writer->DumpImageClasses();
378      std::string temp;
379      CHECK(image_writer->IsImageClass(klass)) << klass->GetDescriptor(&temp)
380                                               << " " << PrettyDescriptor(klass);
381    }
382  }
383}
384
385void ImageWriter::DumpImageClasses() {
386  const std::set<std::string>* image_classes = compiler_driver_.GetImageClasses();
387  CHECK(image_classes != NULL);
388  for (const std::string& image_class : *image_classes) {
389    LOG(INFO) << " " << image_class;
390  }
391}
392
393void ImageWriter::CalculateObjectOffsets(Object* obj) {
394  DCHECK(obj != NULL);
395  // if it is a string, we want to intern it if its not interned.
396  if (obj->GetClass()->IsStringClass()) {
397    // we must be an interned string that was forward referenced and already assigned
398    if (IsImageOffsetAssigned(obj)) {
399      DCHECK_EQ(obj, obj->AsString()->Intern());
400      return;
401    }
402    mirror::String* const interned = obj->AsString()->Intern();
403    if (obj != interned) {
404      if (!IsImageOffsetAssigned(interned)) {
405        // interned obj is after us, allocate its location early
406        AssignImageOffset(interned);
407      }
408      // point those looking for this object to the interned version.
409      SetImageOffset(obj, GetImageOffset(interned));
410      return;
411    }
412    // else (obj == interned), nothing to do but fall through to the normal case
413  }
414
415  AssignImageOffset(obj);
416}
417
418ObjectArray<Object>* ImageWriter::CreateImageRoots() const {
419  Runtime* runtime = Runtime::Current();
420  ClassLinker* class_linker = runtime->GetClassLinker();
421  Thread* self = Thread::Current();
422  StackHandleScope<3> hs(self);
423  Handle<Class> object_array_class(hs.NewHandle(
424      class_linker->FindSystemClass(self, "[Ljava/lang/Object;")));
425
426  // build an Object[] of all the DexCaches used in the source_space_.
427  // Since we can't hold the dex lock when allocating the dex_caches
428  // ObjectArray, we lock the dex lock twice, first to get the number
429  // of dex caches first and then lock it again to copy the dex
430  // caches. We check that the number of dex caches does not change.
431  size_t dex_cache_count;
432  {
433    ReaderMutexLock mu(Thread::Current(), *class_linker->DexLock());
434    dex_cache_count = class_linker->GetDexCacheCount();
435  }
436  Handle<ObjectArray<Object>> dex_caches(
437      hs.NewHandle(ObjectArray<Object>::Alloc(self, object_array_class.Get(),
438                                              dex_cache_count)));
439  CHECK(dex_caches.Get() != nullptr) << "Failed to allocate a dex cache array.";
440  {
441    ReaderMutexLock mu(Thread::Current(), *class_linker->DexLock());
442    CHECK_EQ(dex_cache_count, class_linker->GetDexCacheCount())
443        << "The number of dex caches changed.";
444    for (size_t i = 0; i < dex_cache_count; ++i) {
445      dex_caches->Set<false>(i, class_linker->GetDexCache(i));
446    }
447  }
448
449  // build an Object[] of the roots needed to restore the runtime
450  Handle<ObjectArray<Object>> image_roots(hs.NewHandle(
451      ObjectArray<Object>::Alloc(self, object_array_class.Get(), ImageHeader::kImageRootsMax)));
452  image_roots->Set<false>(ImageHeader::kResolutionMethod, runtime->GetResolutionMethod());
453  image_roots->Set<false>(ImageHeader::kImtConflictMethod, runtime->GetImtConflictMethod());
454  image_roots->Set<false>(ImageHeader::kImtUnimplementedMethod,
455                          runtime->GetImtUnimplementedMethod());
456  image_roots->Set<false>(ImageHeader::kDefaultImt, runtime->GetDefaultImt());
457  image_roots->Set<false>(ImageHeader::kCalleeSaveMethod,
458                          runtime->GetCalleeSaveMethod(Runtime::kSaveAll));
459  image_roots->Set<false>(ImageHeader::kRefsOnlySaveMethod,
460                          runtime->GetCalleeSaveMethod(Runtime::kRefsOnly));
461  image_roots->Set<false>(ImageHeader::kRefsAndArgsSaveMethod,
462                          runtime->GetCalleeSaveMethod(Runtime::kRefsAndArgs));
463  image_roots->Set<false>(ImageHeader::kDexCaches, dex_caches.Get());
464  image_roots->Set<false>(ImageHeader::kClassRoots, class_linker->GetClassRoots());
465  for (int i = 0; i < ImageHeader::kImageRootsMax; i++) {
466    CHECK(image_roots->Get(i) != NULL);
467  }
468  return image_roots.Get();
469}
470
471// Walk instance fields of the given Class. Separate function to allow recursion on the super
472// class.
473void ImageWriter::WalkInstanceFields(mirror::Object* obj, mirror::Class* klass) {
474  // Visit fields of parent classes first.
475  StackHandleScope<1> hs(Thread::Current());
476  Handle<mirror::Class> h_class(hs.NewHandle(klass));
477  mirror::Class* super = h_class->GetSuperClass();
478  if (super != nullptr) {
479    WalkInstanceFields(obj, super);
480  }
481  //
482  size_t num_reference_fields = h_class->NumReferenceInstanceFields();
483  for (size_t i = 0; i < num_reference_fields; ++i) {
484    mirror::ArtField* field = h_class->GetInstanceField(i);
485    MemberOffset field_offset = field->GetOffset();
486    mirror::Object* value = obj->GetFieldObject<mirror::Object>(field_offset);
487    if (value != nullptr) {
488      WalkFieldsInOrder(value);
489    }
490  }
491}
492
493// For an unvisited object, visit it then all its children found via fields.
494void ImageWriter::WalkFieldsInOrder(mirror::Object* obj) {
495  if (!IsImageOffsetAssigned(obj)) {
496    // Walk instance fields of all objects
497    StackHandleScope<2> hs(Thread::Current());
498    Handle<mirror::Object> h_obj(hs.NewHandle(obj));
499    Handle<mirror::Class> klass(hs.NewHandle(obj->GetClass()));
500    // visit the object itself.
501    CalculateObjectOffsets(h_obj.Get());
502    WalkInstanceFields(h_obj.Get(), klass.Get());
503    // Walk static fields of a Class.
504    if (h_obj->IsClass()) {
505      size_t num_static_fields = klass->NumReferenceStaticFields();
506      for (size_t i = 0; i < num_static_fields; ++i) {
507        mirror::ArtField* field = klass->GetStaticField(i);
508        MemberOffset field_offset = field->GetOffset();
509        mirror::Object* value = h_obj->GetFieldObject<mirror::Object>(field_offset);
510        if (value != nullptr) {
511          WalkFieldsInOrder(value);
512        }
513      }
514    } else if (h_obj->IsObjectArray()) {
515      // Walk elements of an object array.
516      int32_t length = h_obj->AsObjectArray<mirror::Object>()->GetLength();
517      for (int32_t i = 0; i < length; i++) {
518        mirror::ObjectArray<mirror::Object>* obj_array = h_obj->AsObjectArray<mirror::Object>();
519        mirror::Object* value = obj_array->Get(i);
520        if (value != nullptr) {
521          WalkFieldsInOrder(value);
522        }
523      }
524    }
525  }
526}
527
528void ImageWriter::WalkFieldsCallback(mirror::Object* obj, void* arg) {
529  ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
530  DCHECK(writer != nullptr);
531  writer->WalkFieldsInOrder(obj);
532}
533
534void ImageWriter::CalculateNewObjectOffsets(size_t oat_loaded_size, size_t oat_data_offset) {
535  CHECK_NE(0U, oat_loaded_size);
536  Thread* self = Thread::Current();
537  StackHandleScope<1> hs(self);
538  Handle<ObjectArray<Object>> image_roots(hs.NewHandle(CreateImageRoots()));
539
540  gc::Heap* heap = Runtime::Current()->GetHeap();
541  DCHECK_EQ(0U, image_end_);
542
543  // Leave space for the header, but do not write it yet, we need to
544  // know where image_roots is going to end up
545  image_end_ += RoundUp(sizeof(ImageHeader), 8);  // 64-bit-alignment
546
547  {
548    WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
549    // TODO: Image spaces only?
550    const char* old = self->StartAssertNoThreadSuspension("ImageWriter");
551    DCHECK_LT(image_end_, image_->Size());
552    // Clear any pre-existing monitors which may have been in the monitor words.
553    heap->VisitObjects(WalkFieldsCallback, this);
554    self->EndAssertNoThreadSuspension(old);
555  }
556
557  const byte* oat_file_begin = image_begin_ + RoundUp(image_end_, kPageSize);
558  const byte* oat_file_end = oat_file_begin + oat_loaded_size;
559  oat_data_begin_ = oat_file_begin + oat_data_offset;
560  const byte* oat_data_end = oat_data_begin_ + oat_file_->Size();
561
562  // Return to write header at start of image with future location of image_roots. At this point,
563  // image_end_ is the size of the image (excluding bitmaps).
564  const size_t heap_bytes_per_bitmap_byte = kBitsPerByte * kObjectAlignment;
565  const size_t bitmap_bytes = RoundUp(image_end_, heap_bytes_per_bitmap_byte) /
566      heap_bytes_per_bitmap_byte;
567  ImageHeader image_header(PointerToLowMemUInt32(image_begin_),
568                           static_cast<uint32_t>(image_end_),
569                           RoundUp(image_end_, kPageSize),
570                           RoundUp(bitmap_bytes, kPageSize),
571                           PointerToLowMemUInt32(GetImageAddress(image_roots.Get())),
572                           oat_file_->GetOatHeader().GetChecksum(),
573                           PointerToLowMemUInt32(oat_file_begin),
574                           PointerToLowMemUInt32(oat_data_begin_),
575                           PointerToLowMemUInt32(oat_data_end),
576                           PointerToLowMemUInt32(oat_file_end),
577                           compile_pic_);
578  memcpy(image_->Begin(), &image_header, sizeof(image_header));
579
580  // Note that image_end_ is left at end of used space
581}
582
583void ImageWriter::CopyAndFixupObjects()
584    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
585  Thread* self = Thread::Current();
586  const char* old_cause = self->StartAssertNoThreadSuspension("ImageWriter");
587  gc::Heap* heap = Runtime::Current()->GetHeap();
588  // TODO: heap validation can't handle this fix up pass
589  heap->DisableObjectValidation();
590  // TODO: Image spaces only?
591  WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
592  heap->VisitObjects(CopyAndFixupObjectsCallback, this);
593  // Fix up the object previously had hash codes.
594  for (const std::pair<mirror::Object*, uint32_t>& hash_pair : saved_hashes_) {
595    hash_pair.first->SetLockWord(LockWord::FromHashCode(hash_pair.second), false);
596  }
597  saved_hashes_.clear();
598  self->EndAssertNoThreadSuspension(old_cause);
599}
600
601void ImageWriter::CopyAndFixupObjectsCallback(Object* obj, void* arg) {
602  DCHECK(obj != nullptr);
603  DCHECK(arg != nullptr);
604  ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg);
605  // see GetLocalAddress for similar computation
606  size_t offset = image_writer->GetImageOffset(obj);
607  byte* dst = image_writer->image_->Begin() + offset;
608  const byte* src = reinterpret_cast<const byte*>(obj);
609  size_t n = obj->SizeOf();
610  DCHECK_LT(offset + n, image_writer->image_->Size());
611  memcpy(dst, src, n);
612  Object* copy = reinterpret_cast<Object*>(dst);
613  // Write in a hash code of objects which have inflated monitors or a hash code in their monitor
614  // word.
615  copy->SetLockWord(LockWord(), false);
616  image_writer->FixupObject(obj, copy);
617}
618
619class FixupVisitor {
620 public:
621  FixupVisitor(ImageWriter* image_writer, Object* copy) : image_writer_(image_writer), copy_(copy) {
622  }
623
624  void operator()(Object* obj, MemberOffset offset, bool /*is_static*/) const
625      EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
626    Object* ref = obj->GetFieldObject<Object, kVerifyNone>(offset);
627    // Use SetFieldObjectWithoutWriteBarrier to avoid card marking since we are writing to the
628    // image.
629    copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
630        offset, image_writer_->GetImageAddress(ref));
631  }
632
633  // java.lang.ref.Reference visitor.
634  void operator()(mirror::Class* /*klass*/, mirror::Reference* ref) const
635      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
636      EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
637    copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
638        mirror::Reference::ReferentOffset(), image_writer_->GetImageAddress(ref->GetReferent()));
639  }
640
641 protected:
642  ImageWriter* const image_writer_;
643  mirror::Object* const copy_;
644};
645
646class FixupClassVisitor FINAL : public FixupVisitor {
647 public:
648  FixupClassVisitor(ImageWriter* image_writer, Object* copy) : FixupVisitor(image_writer, copy) {
649  }
650
651  void operator()(Object* obj, MemberOffset offset, bool /*is_static*/) const
652      EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
653    DCHECK(obj->IsClass());
654    FixupVisitor::operator()(obj, offset, false);
655
656    if (offset.Uint32Value() < mirror::Class::EmbeddedVTableOffset().Uint32Value()) {
657      return;
658    }
659  }
660
661  void operator()(mirror::Class* /*klass*/, mirror::Reference* ref) const
662      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
663      EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
664    LOG(FATAL) << "Reference not expected here.";
665  }
666};
667
668void ImageWriter::FixupObject(Object* orig, Object* copy) {
669  DCHECK(orig != nullptr);
670  DCHECK(copy != nullptr);
671  if (kUseBakerOrBrooksReadBarrier) {
672    orig->AssertReadBarrierPointer();
673    if (kUseBrooksReadBarrier) {
674      // Note the address 'copy' isn't the same as the image address of 'orig'.
675      copy->SetReadBarrierPointer(GetImageAddress(orig));
676      DCHECK_EQ(copy->GetReadBarrierPointer(), GetImageAddress(orig));
677    }
678  }
679  if (orig->IsClass() && orig->AsClass()->ShouldHaveEmbeddedImtAndVTable()) {
680    FixupClassVisitor visitor(this, copy);
681    orig->VisitReferences<true /*visit class*/>(visitor, visitor);
682  } else {
683    FixupVisitor visitor(this, copy);
684    orig->VisitReferences<true /*visit class*/>(visitor, visitor);
685  }
686  if (orig->IsArtMethod<kVerifyNone>()) {
687    FixupMethod(orig->AsArtMethod<kVerifyNone>(), down_cast<ArtMethod*>(copy));
688  }
689}
690
691const byte* ImageWriter::GetQuickCode(mirror::ArtMethod* method, bool* quick_is_interpreted) {
692  DCHECK(!method->IsResolutionMethod() && !method->IsImtConflictMethod() &&
693         !method->IsImtUnimplementedMethod() && !method->IsAbstract()) << PrettyMethod(method);
694
695  // Use original code if it exists. Otherwise, set the code pointer to the resolution
696  // trampoline.
697
698  // Quick entrypoint:
699  const byte* quick_code = GetOatAddress(method->GetQuickOatCodeOffset());
700  *quick_is_interpreted = false;
701  if (quick_code != nullptr &&
702      (!method->IsStatic() || method->IsConstructor() || method->GetDeclaringClass()->IsInitialized())) {
703    // We have code for a non-static or initialized method, just use the code.
704  } else if (quick_code == nullptr && method->IsNative() &&
705      (!method->IsStatic() || method->GetDeclaringClass()->IsInitialized())) {
706    // Non-static or initialized native method missing compiled code, use generic JNI version.
707    quick_code = GetOatAddress(quick_generic_jni_trampoline_offset_);
708  } else if (quick_code == nullptr && !method->IsNative()) {
709    // We don't have code at all for a non-native method, use the interpreter.
710    quick_code = GetOatAddress(quick_to_interpreter_bridge_offset_);
711    *quick_is_interpreted = true;
712  } else {
713    CHECK(!method->GetDeclaringClass()->IsInitialized());
714    // We have code for a static method, but need to go through the resolution stub for class
715    // initialization.
716    quick_code = GetOatAddress(quick_resolution_trampoline_offset_);
717  }
718  return quick_code;
719}
720
721const byte* ImageWriter::GetQuickEntryPoint(mirror::ArtMethod* method) {
722  // Calculate the quick entry point following the same logic as FixupMethod() below.
723  // The resolution method has a special trampoline to call.
724  Runtime* runtime = Runtime::Current();
725  if (UNLIKELY(method == runtime->GetResolutionMethod())) {
726    return GetOatAddress(quick_resolution_trampoline_offset_);
727  } else if (UNLIKELY(method == runtime->GetImtConflictMethod() ||
728                      method == runtime->GetImtUnimplementedMethod())) {
729    return GetOatAddress(quick_imt_conflict_trampoline_offset_);
730  } else {
731    // We assume all methods have code. If they don't currently then we set them to the use the
732    // resolution trampoline. Abstract methods never have code and so we need to make sure their
733    // use results in an AbstractMethodError. We use the interpreter to achieve this.
734    if (UNLIKELY(method->IsAbstract())) {
735      return GetOatAddress(quick_to_interpreter_bridge_offset_);
736    } else {
737      bool quick_is_interpreted;
738      return GetQuickCode(method, &quick_is_interpreted);
739    }
740  }
741}
742
743void ImageWriter::FixupMethod(ArtMethod* orig, ArtMethod* copy) {
744  // OatWriter replaces the code_ with an offset value. Here we re-adjust to a pointer relative to
745  // oat_begin_
746
747  // The resolution method has a special trampoline to call.
748  Runtime* runtime = Runtime::Current();
749  if (UNLIKELY(orig == runtime->GetResolutionMethod())) {
750#if defined(ART_USE_PORTABLE_COMPILER)
751    copy->SetEntryPointFromPortableCompiledCode<kVerifyNone>(GetOatAddress(portable_resolution_trampoline_offset_));
752#endif
753    copy->SetEntryPointFromQuickCompiledCode<kVerifyNone>(GetOatAddress(quick_resolution_trampoline_offset_));
754  } else if (UNLIKELY(orig == runtime->GetImtConflictMethod() ||
755                      orig == runtime->GetImtUnimplementedMethod())) {
756#if defined(ART_USE_PORTABLE_COMPILER)
757    copy->SetEntryPointFromPortableCompiledCode<kVerifyNone>(GetOatAddress(portable_imt_conflict_trampoline_offset_));
758#endif
759    copy->SetEntryPointFromQuickCompiledCode<kVerifyNone>(GetOatAddress(quick_imt_conflict_trampoline_offset_));
760  } else {
761    // We assume all methods have code. If they don't currently then we set them to the use the
762    // resolution trampoline. Abstract methods never have code and so we need to make sure their
763    // use results in an AbstractMethodError. We use the interpreter to achieve this.
764    if (UNLIKELY(orig->IsAbstract())) {
765#if defined(ART_USE_PORTABLE_COMPILER)
766      copy->SetEntryPointFromPortableCompiledCode<kVerifyNone>(GetOatAddress(portable_to_interpreter_bridge_offset_));
767#endif
768      copy->SetEntryPointFromQuickCompiledCode<kVerifyNone>(GetOatAddress(quick_to_interpreter_bridge_offset_));
769      copy->SetEntryPointFromInterpreter<kVerifyNone>(reinterpret_cast<EntryPointFromInterpreter*>
770          (const_cast<byte*>(GetOatAddress(interpreter_to_interpreter_bridge_offset_))));
771    } else {
772      bool quick_is_interpreted;
773      const byte* quick_code = GetQuickCode(orig, &quick_is_interpreted);
774      copy->SetEntryPointFromQuickCompiledCode<kVerifyNone>(quick_code);
775
776      // Portable entrypoint:
777      bool portable_is_interpreted = false;
778#if defined(ART_USE_PORTABLE_COMPILER)
779      const byte* portable_code = GetOatAddress(orig->GetPortableOatCodeOffset());
780      if (portable_code != nullptr &&
781          (!orig->IsStatic() || orig->IsConstructor() || orig->GetDeclaringClass()->IsInitialized())) {
782        // We have code for a non-static or initialized method, just use the code.
783      } else if (portable_code == nullptr && orig->IsNative() &&
784          (!orig->IsStatic() || orig->GetDeclaringClass()->IsInitialized())) {
785        // Non-static or initialized native method missing compiled code, use generic JNI version.
786        // TODO: generic JNI support for LLVM.
787        portable_code = GetOatAddress(portable_resolution_trampoline_offset_);
788      } else if (portable_code == nullptr && !orig->IsNative()) {
789        // We don't have code at all for a non-native method, use the interpreter.
790        portable_code = GetOatAddress(portable_to_interpreter_bridge_offset_);
791        portable_is_interpreted = true;
792      } else {
793        CHECK(!orig->GetDeclaringClass()->IsInitialized());
794        // We have code for a static method, but need to go through the resolution stub for class
795        // initialization.
796        portable_code = GetOatAddress(portable_resolution_trampoline_offset_);
797      }
798      copy->SetEntryPointFromPortableCompiledCode<kVerifyNone>(portable_code);
799#endif
800      // JNI entrypoint:
801      if (orig->IsNative()) {
802        // The native method's pointer is set to a stub to lookup via dlsym.
803        // Note this is not the code_ pointer, that is handled above.
804        copy->SetNativeMethod<kVerifyNone>(GetOatAddress(jni_dlsym_lookup_offset_));
805      } else {
806        // Normal (non-abstract non-native) methods have various tables to relocate.
807        uint32_t native_gc_map_offset = orig->GetOatNativeGcMapOffset();
808        const byte* native_gc_map = GetOatAddress(native_gc_map_offset);
809        copy->SetNativeGcMap<kVerifyNone>(reinterpret_cast<const uint8_t*>(native_gc_map));
810      }
811
812      // Interpreter entrypoint:
813      // Set the interpreter entrypoint depending on whether there is compiled code or not.
814      uint32_t interpreter_code = (quick_is_interpreted && portable_is_interpreted)
815          ? interpreter_to_interpreter_bridge_offset_
816          : interpreter_to_compiled_code_bridge_offset_;
817      copy->SetEntryPointFromInterpreter<kVerifyNone>(
818          reinterpret_cast<EntryPointFromInterpreter*>(
819              const_cast<byte*>(GetOatAddress(interpreter_code))));
820    }
821  }
822}
823
824static OatHeader* GetOatHeaderFromElf(ElfFile* elf) {
825  Elf32_Shdr* data_sec = elf->FindSectionByName(".rodata");
826  if (data_sec == nullptr) {
827    return nullptr;
828  }
829  return reinterpret_cast<OatHeader*>(elf->Begin() + data_sec->sh_offset);
830}
831
832void ImageWriter::PatchOatCodeAndMethods(File* elf_file) {
833  std::string error_msg;
834  std::unique_ptr<ElfFile> elf(ElfFile::Open(elf_file, PROT_READ|PROT_WRITE,
835                                             MAP_SHARED, &error_msg));
836  if (elf.get() == nullptr) {
837    LOG(FATAL) << "Unable patch oat file: " << error_msg;
838    return;
839  }
840  if (!ElfPatcher::Patch(&compiler_driver_, elf.get(), oat_file_,
841                         reinterpret_cast<uintptr_t>(oat_data_begin_),
842                         GetImageAddressCallback, reinterpret_cast<void*>(this),
843                         &error_msg)) {
844    LOG(FATAL) << "unable to patch oat file: " << error_msg;
845    return;
846  }
847  OatHeader* oat_header = GetOatHeaderFromElf(elf.get());
848  CHECK(oat_header != nullptr);
849  CHECK(oat_header->IsValid());
850
851  ImageHeader* image_header = reinterpret_cast<ImageHeader*>(image_->Begin());
852  image_header->SetOatChecksum(oat_header->GetChecksum());
853}
854
855}  // namespace art
856