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 #include <lz4.h>
21 #include <lz4hc.h>
22 
23 #include <memory>
24 #include <numeric>
25 #include <unordered_set>
26 #include <vector>
27 
28 #include "art_field-inl.h"
29 #include "art_method-inl.h"
30 #include "base/logging.h"
31 #include "base/unix_file/fd_file.h"
32 #include "class_linker-inl.h"
33 #include "compiled_method.h"
34 #include "dex_file-inl.h"
35 #include "driver/compiler_driver.h"
36 #include "elf_file.h"
37 #include "elf_utils.h"
38 #include "elf_writer.h"
39 #include "gc/accounting/card_table-inl.h"
40 #include "gc/accounting/heap_bitmap.h"
41 #include "gc/accounting/space_bitmap-inl.h"
42 #include "gc/heap.h"
43 #include "gc/space/large_object_space.h"
44 #include "gc/space/space-inl.h"
45 #include "globals.h"
46 #include "image.h"
47 #include "intern_table.h"
48 #include "linear_alloc.h"
49 #include "lock_word.h"
50 #include "mirror/abstract_method.h"
51 #include "mirror/array-inl.h"
52 #include "mirror/class-inl.h"
53 #include "mirror/class_loader.h"
54 #include "mirror/dex_cache-inl.h"
55 #include "mirror/method.h"
56 #include "mirror/object-inl.h"
57 #include "mirror/object_array-inl.h"
58 #include "mirror/string-inl.h"
59 #include "oat.h"
60 #include "oat_file.h"
61 #include "oat_file_manager.h"
62 #include "runtime.h"
63 #include "scoped_thread_state_change.h"
64 #include "handle_scope-inl.h"
65 #include "utils/dex_cache_arrays_layout-inl.h"
66 
67 using ::art::mirror::Class;
68 using ::art::mirror::DexCache;
69 using ::art::mirror::Object;
70 using ::art::mirror::ObjectArray;
71 using ::art::mirror::String;
72 
73 namespace art {
74 
75 // Separate objects into multiple bins to optimize dirty memory use.
76 static constexpr bool kBinObjects = true;
77 
78 // Return true if an object is already in an image space.
IsInBootImage(const void * obj) const79 bool ImageWriter::IsInBootImage(const void* obj) const {
80   gc::Heap* const heap = Runtime::Current()->GetHeap();
81   if (!compile_app_image_) {
82     DCHECK(heap->GetBootImageSpaces().empty());
83     return false;
84   }
85   for (gc::space::ImageSpace* boot_image_space : heap->GetBootImageSpaces()) {
86     const uint8_t* image_begin = boot_image_space->Begin();
87     // Real image end including ArtMethods and ArtField sections.
88     const uint8_t* image_end = image_begin + boot_image_space->GetImageHeader().GetImageSize();
89     if (image_begin <= obj && obj < image_end) {
90       return true;
91     }
92   }
93   return false;
94 }
95 
IsInBootOatFile(const void * ptr) const96 bool ImageWriter::IsInBootOatFile(const void* ptr) const {
97   gc::Heap* const heap = Runtime::Current()->GetHeap();
98   if (!compile_app_image_) {
99     DCHECK(heap->GetBootImageSpaces().empty());
100     return false;
101   }
102   for (gc::space::ImageSpace* boot_image_space : heap->GetBootImageSpaces()) {
103     const ImageHeader& image_header = boot_image_space->GetImageHeader();
104     if (image_header.GetOatFileBegin() <= ptr && ptr < image_header.GetOatFileEnd()) {
105       return true;
106     }
107   }
108   return false;
109 }
110 
CheckNoDexObjectsCallback(Object * obj,void * arg ATTRIBUTE_UNUSED)111 static void CheckNoDexObjectsCallback(Object* obj, void* arg ATTRIBUTE_UNUSED)
112     SHARED_REQUIRES(Locks::mutator_lock_) {
113   Class* klass = obj->GetClass();
114   CHECK_NE(PrettyClass(klass), "com.android.dex.Dex");
115 }
116 
CheckNoDexObjects()117 static void CheckNoDexObjects() {
118   ScopedObjectAccess soa(Thread::Current());
119   Runtime::Current()->GetHeap()->VisitObjects(CheckNoDexObjectsCallback, nullptr);
120 }
121 
PrepareImageAddressSpace()122 bool ImageWriter::PrepareImageAddressSpace() {
123   target_ptr_size_ = InstructionSetPointerSize(compiler_driver_.GetInstructionSet());
124   gc::Heap* const heap = Runtime::Current()->GetHeap();
125   {
126     ScopedObjectAccess soa(Thread::Current());
127     PruneNonImageClasses();  // Remove junk
128     if (!compile_app_image_) {
129       // Avoid for app image since this may increase RAM and image size.
130       ComputeLazyFieldsForImageClasses();  // Add useful information
131     }
132   }
133   heap->CollectGarbage(false);  // Remove garbage.
134 
135   // Dex caches must not have their dex fields set in the image. These are memory buffers of mapped
136   // dex files.
137   //
138   // We may open them in the unstarted-runtime code for class metadata. Their fields should all be
139   // reset in PruneNonImageClasses and the objects reclaimed in the GC. Make sure that's actually
140   // true.
141   if (kIsDebugBuild) {
142     CheckNoDexObjects();
143   }
144 
145   if (kIsDebugBuild) {
146     ScopedObjectAccess soa(Thread::Current());
147     CheckNonImageClassesRemoved();
148   }
149 
150   {
151     ScopedObjectAccess soa(Thread::Current());
152     CalculateNewObjectOffsets();
153   }
154 
155   // This needs to happen after CalculateNewObjectOffsets since it relies on intern_table_bytes_ and
156   // bin size sums being calculated.
157   if (!AllocMemory()) {
158     return false;
159   }
160 
161   return true;
162 }
163 
Write(int image_fd,const std::vector<const char * > & image_filenames,const std::vector<const char * > & oat_filenames)164 bool ImageWriter::Write(int image_fd,
165                         const std::vector<const char*>& image_filenames,
166                         const std::vector<const char*>& oat_filenames) {
167   // If image_fd or oat_fd are not kInvalidFd then we may have empty strings in image_filenames or
168   // oat_filenames.
169   CHECK(!image_filenames.empty());
170   if (image_fd != kInvalidFd) {
171     CHECK_EQ(image_filenames.size(), 1u);
172   }
173   CHECK(!oat_filenames.empty());
174   CHECK_EQ(image_filenames.size(), oat_filenames.size());
175 
176   {
177     ScopedObjectAccess soa(Thread::Current());
178     for (size_t i = 0; i < oat_filenames.size(); ++i) {
179       CreateHeader(i);
180       CopyAndFixupNativeData(i);
181     }
182   }
183 
184   {
185     // TODO: heap validation can't handle these fix up passes.
186     ScopedObjectAccess soa(Thread::Current());
187     Runtime::Current()->GetHeap()->DisableObjectValidation();
188     CopyAndFixupObjects();
189   }
190 
191   for (size_t i = 0; i < image_filenames.size(); ++i) {
192     const char* image_filename = image_filenames[i];
193     ImageInfo& image_info = GetImageInfo(i);
194     std::unique_ptr<File> image_file;
195     if (image_fd != kInvalidFd) {
196       if (strlen(image_filename) == 0u) {
197         image_file.reset(new File(image_fd, unix_file::kCheckSafeUsage));
198         // Empty the file in case it already exists.
199         if (image_file != nullptr) {
200           TEMP_FAILURE_RETRY(image_file->SetLength(0));
201           TEMP_FAILURE_RETRY(image_file->Flush());
202         }
203       } else {
204         LOG(ERROR) << "image fd " << image_fd << " name " << image_filename;
205       }
206     } else {
207       image_file.reset(OS::CreateEmptyFile(image_filename));
208     }
209 
210     if (image_file == nullptr) {
211       LOG(ERROR) << "Failed to open image file " << image_filename;
212       return false;
213     }
214 
215     if (!compile_app_image_ && fchmod(image_file->Fd(), 0644) != 0) {
216       PLOG(ERROR) << "Failed to make image file world readable: " << image_filename;
217       image_file->Erase();
218       return EXIT_FAILURE;
219     }
220 
221     std::unique_ptr<char[]> compressed_data;
222     // Image data size excludes the bitmap and the header.
223     ImageHeader* const image_header = reinterpret_cast<ImageHeader*>(image_info.image_->Begin());
224     const size_t image_data_size = image_header->GetImageSize() - sizeof(ImageHeader);
225     char* image_data = reinterpret_cast<char*>(image_info.image_->Begin()) + sizeof(ImageHeader);
226     size_t data_size;
227     const char* image_data_to_write;
228     const uint64_t compress_start_time = NanoTime();
229 
230     CHECK_EQ(image_header->storage_mode_, image_storage_mode_);
231     switch (image_storage_mode_) {
232       case ImageHeader::kStorageModeLZ4HC:  // Fall-through.
233       case ImageHeader::kStorageModeLZ4: {
234         const size_t compressed_max_size = LZ4_compressBound(image_data_size);
235         compressed_data.reset(new char[compressed_max_size]);
236         data_size = LZ4_compress(
237             reinterpret_cast<char*>(image_info.image_->Begin()) + sizeof(ImageHeader),
238             &compressed_data[0],
239             image_data_size);
240 
241         break;
242       }
243       /*
244        * Disabled due to image_test64 flakyness. Both use same decompression. b/27560444
245       case ImageHeader::kStorageModeLZ4HC: {
246         // Bound is same as non HC.
247         const size_t compressed_max_size = LZ4_compressBound(image_data_size);
248         compressed_data.reset(new char[compressed_max_size]);
249         data_size = LZ4_compressHC(
250             reinterpret_cast<char*>(image_info.image_->Begin()) + sizeof(ImageHeader),
251             &compressed_data[0],
252             image_data_size);
253         break;
254       }
255       */
256       case ImageHeader::kStorageModeUncompressed: {
257         data_size = image_data_size;
258         image_data_to_write = image_data;
259         break;
260       }
261       default: {
262         LOG(FATAL) << "Unsupported";
263         UNREACHABLE();
264       }
265     }
266 
267     if (compressed_data != nullptr) {
268       image_data_to_write = &compressed_data[0];
269       VLOG(compiler) << "Compressed from " << image_data_size << " to " << data_size << " in "
270                      << PrettyDuration(NanoTime() - compress_start_time);
271       if (kIsDebugBuild) {
272         std::unique_ptr<uint8_t[]> temp(new uint8_t[image_data_size]);
273         const size_t decompressed_size = LZ4_decompress_safe(
274             reinterpret_cast<char*>(&compressed_data[0]),
275             reinterpret_cast<char*>(&temp[0]),
276             data_size,
277             image_data_size);
278         CHECK_EQ(decompressed_size, image_data_size);
279         CHECK_EQ(memcmp(image_data, &temp[0], image_data_size), 0) << image_storage_mode_;
280       }
281     }
282 
283     // Write out the image + fields + methods.
284     const bool is_compressed = compressed_data != nullptr;
285     if (!image_file->PwriteFully(image_data_to_write, data_size, sizeof(ImageHeader))) {
286       PLOG(ERROR) << "Failed to write image file data " << image_filename;
287       image_file->Erase();
288       return false;
289     }
290 
291     // Write out the image bitmap at the page aligned start of the image end, also uncompressed for
292     // convenience.
293     const ImageSection& bitmap_section = image_header->GetImageSection(
294         ImageHeader::kSectionImageBitmap);
295     // Align up since data size may be unaligned if the image is compressed.
296     size_t bitmap_position_in_file = RoundUp(sizeof(ImageHeader) + data_size, kPageSize);
297     if (!is_compressed) {
298       CHECK_EQ(bitmap_position_in_file, bitmap_section.Offset());
299     }
300     if (!image_file->PwriteFully(reinterpret_cast<char*>(image_info.image_bitmap_->Begin()),
301                                  bitmap_section.Size(),
302                                  bitmap_position_in_file)) {
303       PLOG(ERROR) << "Failed to write image file " << image_filename;
304       image_file->Erase();
305       return false;
306     }
307 
308     int err = image_file->Flush();
309     if (err < 0) {
310       PLOG(ERROR) << "Failed to flush image file " << image_filename << " with result " << err;
311       image_file->Erase();
312       return false;
313     }
314 
315     // Write header last in case the compiler gets killed in the middle of image writing.
316     // We do not want to have a corrupted image with a valid header.
317     // The header is uncompressed since it contains whether the image is compressed or not.
318     image_header->data_size_ = data_size;
319     if (!image_file->PwriteFully(reinterpret_cast<char*>(image_info.image_->Begin()),
320                                  sizeof(ImageHeader),
321                                  0)) {
322       PLOG(ERROR) << "Failed to write image file header " << image_filename;
323       image_file->Erase();
324       return false;
325     }
326 
327     CHECK_EQ(bitmap_position_in_file + bitmap_section.Size(),
328              static_cast<size_t>(image_file->GetLength()));
329     if (image_file->FlushCloseOrErase() != 0) {
330       PLOG(ERROR) << "Failed to flush and close image file " << image_filename;
331       return false;
332     }
333   }
334   return true;
335 }
336 
SetImageOffset(mirror::Object * object,size_t offset)337 void ImageWriter::SetImageOffset(mirror::Object* object, size_t offset) {
338   DCHECK(object != nullptr);
339   DCHECK_NE(offset, 0U);
340 
341   // The object is already deflated from when we set the bin slot. Just overwrite the lock word.
342   object->SetLockWord(LockWord::FromForwardingAddress(offset), false);
343   DCHECK_EQ(object->GetLockWord(false).ReadBarrierState(), 0u);
344   DCHECK(IsImageOffsetAssigned(object));
345 }
346 
UpdateImageOffset(mirror::Object * obj,uintptr_t offset)347 void ImageWriter::UpdateImageOffset(mirror::Object* obj, uintptr_t offset) {
348   DCHECK(IsImageOffsetAssigned(obj)) << obj << " " << offset;
349   obj->SetLockWord(LockWord::FromForwardingAddress(offset), false);
350   DCHECK_EQ(obj->GetLockWord(false).ReadBarrierState(), 0u);
351 }
352 
AssignImageOffset(mirror::Object * object,ImageWriter::BinSlot bin_slot)353 void ImageWriter::AssignImageOffset(mirror::Object* object, ImageWriter::BinSlot bin_slot) {
354   DCHECK(object != nullptr);
355   DCHECK_NE(image_objects_offset_begin_, 0u);
356 
357   size_t oat_index = GetOatIndex(object);
358   ImageInfo& image_info = GetImageInfo(oat_index);
359   size_t bin_slot_offset = image_info.bin_slot_offsets_[bin_slot.GetBin()];
360   size_t new_offset = bin_slot_offset + bin_slot.GetIndex();
361   DCHECK_ALIGNED(new_offset, kObjectAlignment);
362 
363   SetImageOffset(object, new_offset);
364   DCHECK_LT(new_offset, image_info.image_end_);
365 }
366 
IsImageOffsetAssigned(mirror::Object * object) const367 bool ImageWriter::IsImageOffsetAssigned(mirror::Object* object) const {
368   // Will also return true if the bin slot was assigned since we are reusing the lock word.
369   DCHECK(object != nullptr);
370   return object->GetLockWord(false).GetState() == LockWord::kForwardingAddress;
371 }
372 
GetImageOffset(mirror::Object * object) const373 size_t ImageWriter::GetImageOffset(mirror::Object* object) const {
374   DCHECK(object != nullptr);
375   DCHECK(IsImageOffsetAssigned(object));
376   LockWord lock_word = object->GetLockWord(false);
377   size_t offset = lock_word.ForwardingAddress();
378   size_t oat_index = GetOatIndex(object);
379   const ImageInfo& image_info = GetImageInfo(oat_index);
380   DCHECK_LT(offset, image_info.image_end_);
381   return offset;
382 }
383 
SetImageBinSlot(mirror::Object * object,BinSlot bin_slot)384 void ImageWriter::SetImageBinSlot(mirror::Object* object, BinSlot bin_slot) {
385   DCHECK(object != nullptr);
386   DCHECK(!IsImageOffsetAssigned(object));
387   DCHECK(!IsImageBinSlotAssigned(object));
388 
389   // Before we stomp over the lock word, save the hash code for later.
390   Monitor::Deflate(Thread::Current(), object);;
391   LockWord lw(object->GetLockWord(false));
392   switch (lw.GetState()) {
393     case LockWord::kFatLocked: {
394       LOG(FATAL) << "Fat locked object " << object << " found during object copy";
395       break;
396     }
397     case LockWord::kThinLocked: {
398       LOG(FATAL) << "Thin locked object " << object << " found during object copy";
399       break;
400     }
401     case LockWord::kUnlocked:
402       // No hash, don't need to save it.
403       break;
404     case LockWord::kHashCode:
405       DCHECK(saved_hashcode_map_.find(object) == saved_hashcode_map_.end());
406       saved_hashcode_map_.emplace(object, lw.GetHashCode());
407       break;
408     default:
409       LOG(FATAL) << "Unreachable.";
410       UNREACHABLE();
411   }
412   object->SetLockWord(LockWord::FromForwardingAddress(bin_slot.Uint32Value()), false);
413   DCHECK_EQ(object->GetLockWord(false).ReadBarrierState(), 0u);
414   DCHECK(IsImageBinSlotAssigned(object));
415 }
416 
PrepareDexCacheArraySlots()417 void ImageWriter::PrepareDexCacheArraySlots() {
418   // Prepare dex cache array starts based on the ordering specified in the CompilerDriver.
419   // Set the slot size early to avoid DCHECK() failures in IsImageBinSlotAssigned()
420   // when AssignImageBinSlot() assigns their indexes out or order.
421   for (const DexFile* dex_file : compiler_driver_.GetDexFilesForOatFile()) {
422     auto it = dex_file_oat_index_map_.find(dex_file);
423     DCHECK(it != dex_file_oat_index_map_.end()) << dex_file->GetLocation();
424     ImageInfo& image_info = GetImageInfo(it->second);
425     image_info.dex_cache_array_starts_.Put(dex_file, image_info.bin_slot_sizes_[kBinDexCacheArray]);
426     DexCacheArraysLayout layout(target_ptr_size_, dex_file);
427     image_info.bin_slot_sizes_[kBinDexCacheArray] += layout.Size();
428   }
429 
430   ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
431   Thread* const self = Thread::Current();
432   ReaderMutexLock mu(self, *class_linker->DexLock());
433   for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
434     mirror::DexCache* dex_cache =
435         down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
436     if (dex_cache == nullptr || IsInBootImage(dex_cache)) {
437       continue;
438     }
439     const DexFile* dex_file = dex_cache->GetDexFile();
440     CHECK(dex_file_oat_index_map_.find(dex_file) != dex_file_oat_index_map_.end())
441         << "Dex cache should have been pruned " << dex_file->GetLocation()
442         << "; possibly in class path";
443     DexCacheArraysLayout layout(target_ptr_size_, dex_file);
444     DCHECK(layout.Valid());
445     size_t oat_index = GetOatIndexForDexCache(dex_cache);
446     ImageInfo& image_info = GetImageInfo(oat_index);
447     uint32_t start = image_info.dex_cache_array_starts_.Get(dex_file);
448     DCHECK_EQ(dex_file->NumTypeIds() != 0u, dex_cache->GetResolvedTypes() != nullptr);
449     AddDexCacheArrayRelocation(dex_cache->GetResolvedTypes(),
450                                start + layout.TypesOffset(),
451                                dex_cache);
452     DCHECK_EQ(dex_file->NumMethodIds() != 0u, dex_cache->GetResolvedMethods() != nullptr);
453     AddDexCacheArrayRelocation(dex_cache->GetResolvedMethods(),
454                                start + layout.MethodsOffset(),
455                                dex_cache);
456     DCHECK_EQ(dex_file->NumFieldIds() != 0u, dex_cache->GetResolvedFields() != nullptr);
457     AddDexCacheArrayRelocation(dex_cache->GetResolvedFields(),
458                                start + layout.FieldsOffset(),
459                                dex_cache);
460     DCHECK_EQ(dex_file->NumStringIds() != 0u, dex_cache->GetStrings() != nullptr);
461     AddDexCacheArrayRelocation(dex_cache->GetStrings(), start + layout.StringsOffset(), dex_cache);
462   }
463 }
464 
AddDexCacheArrayRelocation(void * array,size_t offset,DexCache * dex_cache)465 void ImageWriter::AddDexCacheArrayRelocation(void* array, size_t offset, DexCache* dex_cache) {
466   if (array != nullptr) {
467     DCHECK(!IsInBootImage(array));
468     size_t oat_index = GetOatIndexForDexCache(dex_cache);
469     native_object_relocations_.emplace(array,
470         NativeObjectRelocation { oat_index, offset, kNativeObjectRelocationTypeDexCacheArray });
471   }
472 }
473 
AddMethodPointerArray(mirror::PointerArray * arr)474 void ImageWriter::AddMethodPointerArray(mirror::PointerArray* arr) {
475   DCHECK(arr != nullptr);
476   if (kIsDebugBuild) {
477     for (size_t i = 0, len = arr->GetLength(); i < len; i++) {
478       ArtMethod* method = arr->GetElementPtrSize<ArtMethod*>(i, target_ptr_size_);
479       if (method != nullptr && !method->IsRuntimeMethod()) {
480         mirror::Class* klass = method->GetDeclaringClass();
481         CHECK(klass == nullptr || KeepClass(klass))
482             << PrettyClass(klass) << " should be a kept class";
483       }
484     }
485   }
486   // kBinArtMethodClean picked arbitrarily, just required to differentiate between ArtFields and
487   // ArtMethods.
488   pointer_arrays_.emplace(arr, kBinArtMethodClean);
489 }
490 
AssignImageBinSlot(mirror::Object * object)491 void ImageWriter::AssignImageBinSlot(mirror::Object* object) {
492   DCHECK(object != nullptr);
493   size_t object_size = object->SizeOf();
494 
495   // The magic happens here. We segregate objects into different bins based
496   // on how likely they are to get dirty at runtime.
497   //
498   // Likely-to-dirty objects get packed together into the same bin so that
499   // at runtime their page dirtiness ratio (how many dirty objects a page has) is
500   // maximized.
501   //
502   // This means more pages will stay either clean or shared dirty (with zygote) and
503   // the app will use less of its own (private) memory.
504   Bin bin = kBinRegular;
505   size_t current_offset = 0u;
506 
507   if (kBinObjects) {
508     //
509     // Changing the bin of an object is purely a memory-use tuning.
510     // It has no change on runtime correctness.
511     //
512     // Memory analysis has determined that the following types of objects get dirtied
513     // the most:
514     //
515     // * Dex cache arrays are stored in a special bin. The arrays for each dex cache have
516     //   a fixed layout which helps improve generated code (using PC-relative addressing),
517     //   so we pre-calculate their offsets separately in PrepareDexCacheArraySlots().
518     //   Since these arrays are huge, most pages do not overlap other objects and it's not
519     //   really important where they are for the clean/dirty separation. Due to their
520     //   special PC-relative addressing, we arbitrarily keep them at the end.
521     // * Class'es which are verified [their clinit runs only at runtime]
522     //   - classes in general [because their static fields get overwritten]
523     //   - initialized classes with all-final statics are unlikely to be ever dirty,
524     //     so bin them separately
525     // * Art Methods that are:
526     //   - native [their native entry point is not looked up until runtime]
527     //   - have declaring classes that aren't initialized
528     //            [their interpreter/quick entry points are trampolines until the class
529     //             becomes initialized]
530     //
531     // We also assume the following objects get dirtied either never or extremely rarely:
532     //  * Strings (they are immutable)
533     //  * Art methods that aren't native and have initialized declared classes
534     //
535     // We assume that "regular" bin objects are highly unlikely to become dirtied,
536     // so packing them together will not result in a noticeably tighter dirty-to-clean ratio.
537     //
538     if (object->IsClass()) {
539       bin = kBinClassVerified;
540       mirror::Class* klass = object->AsClass();
541 
542       // Add non-embedded vtable to the pointer array table if there is one.
543       auto* vtable = klass->GetVTable();
544       if (vtable != nullptr) {
545         AddMethodPointerArray(vtable);
546       }
547       auto* iftable = klass->GetIfTable();
548       if (iftable != nullptr) {
549         for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
550           if (iftable->GetMethodArrayCount(i) > 0) {
551             AddMethodPointerArray(iftable->GetMethodArray(i));
552           }
553         }
554       }
555 
556       if (klass->GetStatus() == Class::kStatusInitialized) {
557         bin = kBinClassInitialized;
558 
559         // If the class's static fields are all final, put it into a separate bin
560         // since it's very likely it will stay clean.
561         uint32_t num_static_fields = klass->NumStaticFields();
562         if (num_static_fields == 0) {
563           bin = kBinClassInitializedFinalStatics;
564         } else {
565           // Maybe all the statics are final?
566           bool all_final = true;
567           for (uint32_t i = 0; i < num_static_fields; ++i) {
568             ArtField* field = klass->GetStaticField(i);
569             if (!field->IsFinal()) {
570               all_final = false;
571               break;
572             }
573           }
574 
575           if (all_final) {
576             bin = kBinClassInitializedFinalStatics;
577           }
578         }
579       }
580     } else if (object->GetClass<kVerifyNone>()->IsStringClass()) {
581       bin = kBinString;  // Strings are almost always immutable (except for object header).
582     } else if (object->GetClass<kVerifyNone>() ==
583         Runtime::Current()->GetClassLinker()->GetClassRoot(ClassLinker::kJavaLangObject)) {
584       // Instance of java lang object, probably a lock object. This means it will be dirty when we
585       // synchronize on it.
586       bin = kBinMiscDirty;
587     } else if (object->IsDexCache()) {
588       // Dex file field becomes dirty when the image is loaded.
589       bin = kBinMiscDirty;
590     }
591     // else bin = kBinRegular
592   }
593 
594   size_t oat_index = GetOatIndex(object);
595   ImageInfo& image_info = GetImageInfo(oat_index);
596 
597   size_t offset_delta = RoundUp(object_size, kObjectAlignment);  // 64-bit alignment
598   current_offset = image_info.bin_slot_sizes_[bin];  // How many bytes the current bin is at (aligned).
599   // Move the current bin size up to accommodate the object we just assigned a bin slot.
600   image_info.bin_slot_sizes_[bin] += offset_delta;
601 
602   BinSlot new_bin_slot(bin, current_offset);
603   SetImageBinSlot(object, new_bin_slot);
604 
605   ++image_info.bin_slot_count_[bin];
606 
607   // Grow the image closer to the end by the object we just assigned.
608   image_info.image_end_ += offset_delta;
609 }
610 
WillMethodBeDirty(ArtMethod * m) const611 bool ImageWriter::WillMethodBeDirty(ArtMethod* m) const {
612   if (m->IsNative()) {
613     return true;
614   }
615   mirror::Class* declaring_class = m->GetDeclaringClass();
616   // Initialized is highly unlikely to dirty since there's no entry points to mutate.
617   return declaring_class == nullptr || declaring_class->GetStatus() != Class::kStatusInitialized;
618 }
619 
IsImageBinSlotAssigned(mirror::Object * object) const620 bool ImageWriter::IsImageBinSlotAssigned(mirror::Object* object) const {
621   DCHECK(object != nullptr);
622 
623   // We always stash the bin slot into a lockword, in the 'forwarding address' state.
624   // If it's in some other state, then we haven't yet assigned an image bin slot.
625   if (object->GetLockWord(false).GetState() != LockWord::kForwardingAddress) {
626     return false;
627   } else if (kIsDebugBuild) {
628     LockWord lock_word = object->GetLockWord(false);
629     size_t offset = lock_word.ForwardingAddress();
630     BinSlot bin_slot(offset);
631     size_t oat_index = GetOatIndex(object);
632     const ImageInfo& image_info = GetImageInfo(oat_index);
633     DCHECK_LT(bin_slot.GetIndex(), image_info.bin_slot_sizes_[bin_slot.GetBin()])
634         << "bin slot offset should not exceed the size of that bin";
635   }
636   return true;
637 }
638 
GetImageBinSlot(mirror::Object * object) const639 ImageWriter::BinSlot ImageWriter::GetImageBinSlot(mirror::Object* object) const {
640   DCHECK(object != nullptr);
641   DCHECK(IsImageBinSlotAssigned(object));
642 
643   LockWord lock_word = object->GetLockWord(false);
644   size_t offset = lock_word.ForwardingAddress();  // TODO: ForwardingAddress should be uint32_t
645   DCHECK_LE(offset, std::numeric_limits<uint32_t>::max());
646 
647   BinSlot bin_slot(static_cast<uint32_t>(offset));
648   size_t oat_index = GetOatIndex(object);
649   const ImageInfo& image_info = GetImageInfo(oat_index);
650   DCHECK_LT(bin_slot.GetIndex(), image_info.bin_slot_sizes_[bin_slot.GetBin()]);
651 
652   return bin_slot;
653 }
654 
AllocMemory()655 bool ImageWriter::AllocMemory() {
656   for (ImageInfo& image_info : image_infos_) {
657     ImageSection unused_sections[ImageHeader::kSectionCount];
658     const size_t length = RoundUp(
659         image_info.CreateImageSections(unused_sections), kPageSize);
660 
661     std::string error_msg;
662     image_info.image_.reset(MemMap::MapAnonymous("image writer image",
663                                                  nullptr,
664                                                  length,
665                                                  PROT_READ | PROT_WRITE,
666                                                  false,
667                                                  false,
668                                                  &error_msg));
669     if (UNLIKELY(image_info.image_.get() == nullptr)) {
670       LOG(ERROR) << "Failed to allocate memory for image file generation: " << error_msg;
671       return false;
672     }
673 
674     // Create the image bitmap, only needs to cover mirror object section which is up to image_end_.
675     CHECK_LE(image_info.image_end_, length);
676     image_info.image_bitmap_.reset(gc::accounting::ContinuousSpaceBitmap::Create(
677         "image bitmap", image_info.image_->Begin(), RoundUp(image_info.image_end_, kPageSize)));
678     if (image_info.image_bitmap_.get() == nullptr) {
679       LOG(ERROR) << "Failed to allocate memory for image bitmap";
680       return false;
681     }
682   }
683   return true;
684 }
685 
686 class ComputeLazyFieldsForClassesVisitor : public ClassVisitor {
687  public:
operator ()(Class * c)688   bool operator()(Class* c) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
689     StackHandleScope<1> hs(Thread::Current());
690     mirror::Class::ComputeName(hs.NewHandle(c));
691     return true;
692   }
693 };
694 
ComputeLazyFieldsForImageClasses()695 void ImageWriter::ComputeLazyFieldsForImageClasses() {
696   ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
697   ComputeLazyFieldsForClassesVisitor visitor;
698   class_linker->VisitClassesWithoutClassesLock(&visitor);
699 }
700 
IsBootClassLoaderClass(mirror::Class * klass)701 static bool IsBootClassLoaderClass(mirror::Class* klass) SHARED_REQUIRES(Locks::mutator_lock_) {
702   return klass->GetClassLoader() == nullptr;
703 }
704 
IsBootClassLoaderNonImageClass(mirror::Class * klass)705 bool ImageWriter::IsBootClassLoaderNonImageClass(mirror::Class* klass) {
706   return IsBootClassLoaderClass(klass) && !IsInBootImage(klass);
707 }
708 
PruneAppImageClass(mirror::Class * klass)709 bool ImageWriter::PruneAppImageClass(mirror::Class* klass) {
710   bool early_exit = false;
711   std::unordered_set<mirror::Class*> visited;
712   return PruneAppImageClassInternal(klass, &early_exit, &visited);
713 }
714 
PruneAppImageClassInternal(mirror::Class * klass,bool * early_exit,std::unordered_set<mirror::Class * > * visited)715 bool ImageWriter::PruneAppImageClassInternal(
716     mirror::Class* klass,
717     bool* early_exit,
718     std::unordered_set<mirror::Class*>* visited) {
719   DCHECK(early_exit != nullptr);
720   DCHECK(visited != nullptr);
721   DCHECK(compile_app_image_);
722   if (klass == nullptr || IsInBootImage(klass)) {
723     return false;
724   }
725   auto found = prune_class_memo_.find(klass);
726   if (found != prune_class_memo_.end()) {
727     // Already computed, return the found value.
728     return found->second;
729   }
730   // Circular dependencies, return false but do not store the result in the memoization table.
731   if (visited->find(klass) != visited->end()) {
732     *early_exit = true;
733     return false;
734   }
735   visited->emplace(klass);
736   bool result = IsBootClassLoaderClass(klass);
737   std::string temp;
738   // Prune if not an image class, this handles any broken sets of image classes such as having a
739   // class in the set but not it's superclass.
740   result = result || !compiler_driver_.IsImageClass(klass->GetDescriptor(&temp));
741   bool my_early_exit = false;  // Only for ourselves, ignore caller.
742   // Remove classes that failed to verify since we don't want to have java.lang.VerifyError in the
743   // app image.
744   if (klass->GetStatus() == mirror::Class::kStatusError) {
745     result = true;
746   } else {
747     CHECK(klass->GetVerifyError() == nullptr) << PrettyClass(klass);
748   }
749   if (!result) {
750     // Check interfaces since these wont be visited through VisitReferences.)
751     mirror::IfTable* if_table = klass->GetIfTable();
752     for (size_t i = 0, num_interfaces = klass->GetIfTableCount(); i < num_interfaces; ++i) {
753       result = result || PruneAppImageClassInternal(if_table->GetInterface(i),
754                                                     &my_early_exit,
755                                                     visited);
756     }
757   }
758   if (klass->IsObjectArrayClass()) {
759     result = result || PruneAppImageClassInternal(klass->GetComponentType(),
760                                                   &my_early_exit,
761                                                   visited);
762   }
763   // Check static fields and their classes.
764   size_t num_static_fields = klass->NumReferenceStaticFields();
765   if (num_static_fields != 0 && klass->IsResolved()) {
766     // Presumably GC can happen when we are cross compiling, it should not cause performance
767     // problems to do pointer size logic.
768     MemberOffset field_offset = klass->GetFirstReferenceStaticFieldOffset(
769         Runtime::Current()->GetClassLinker()->GetImagePointerSize());
770     for (size_t i = 0u; i < num_static_fields; ++i) {
771       mirror::Object* ref = klass->GetFieldObject<mirror::Object>(field_offset);
772       if (ref != nullptr) {
773         if (ref->IsClass()) {
774           result = result || PruneAppImageClassInternal(ref->AsClass(),
775                                                         &my_early_exit,
776                                                         visited);
777         } else {
778           result = result || PruneAppImageClassInternal(ref->GetClass(),
779                                                         &my_early_exit,
780                                                         visited);
781         }
782       }
783       field_offset = MemberOffset(field_offset.Uint32Value() +
784                                   sizeof(mirror::HeapReference<mirror::Object>));
785     }
786   }
787   result = result || PruneAppImageClassInternal(klass->GetSuperClass(),
788                                                 &my_early_exit,
789                                                 visited);
790   // Erase the element we stored earlier since we are exiting the function.
791   auto it = visited->find(klass);
792   DCHECK(it != visited->end());
793   visited->erase(it);
794   // Only store result if it is true or none of the calls early exited due to circular
795   // dependencies. If visited is empty then we are the root caller, in this case the cycle was in
796   // a child call and we can remember the result.
797   if (result == true || !my_early_exit || visited->empty()) {
798     prune_class_memo_[klass] = result;
799   }
800   *early_exit |= my_early_exit;
801   return result;
802 }
803 
KeepClass(Class * klass)804 bool ImageWriter::KeepClass(Class* klass) {
805   if (klass == nullptr) {
806     return false;
807   }
808   if (compile_app_image_ && Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(klass)) {
809     // Already in boot image, return true.
810     return true;
811   }
812   std::string temp;
813   if (!compiler_driver_.IsImageClass(klass->GetDescriptor(&temp))) {
814     return false;
815   }
816   if (compile_app_image_) {
817     // For app images, we need to prune boot loader classes that are not in the boot image since
818     // these may have already been loaded when the app image is loaded.
819     // Keep classes in the boot image space since we don't want to re-resolve these.
820     return !PruneAppImageClass(klass);
821   }
822   return true;
823 }
824 
825 class NonImageClassesVisitor : public ClassVisitor {
826  public:
NonImageClassesVisitor(ImageWriter * image_writer)827   explicit NonImageClassesVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {}
828 
operator ()(Class * klass)829   bool operator()(Class* klass) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
830     if (!image_writer_->KeepClass(klass)) {
831       classes_to_prune_.insert(klass);
832     }
833     return true;
834   }
835 
836   std::unordered_set<mirror::Class*> classes_to_prune_;
837   ImageWriter* const image_writer_;
838 };
839 
PruneNonImageClasses()840 void ImageWriter::PruneNonImageClasses() {
841   Runtime* runtime = Runtime::Current();
842   ClassLinker* class_linker = runtime->GetClassLinker();
843   Thread* self = Thread::Current();
844 
845   // Clear class table strong roots so that dex caches can get pruned. We require pruning the class
846   // path dex caches.
847   class_linker->ClearClassTableStrongRoots();
848 
849   // Make a list of classes we would like to prune.
850   NonImageClassesVisitor visitor(this);
851   class_linker->VisitClasses(&visitor);
852 
853   // Remove the undesired classes from the class roots.
854   VLOG(compiler) << "Pruning " << visitor.classes_to_prune_.size() << " classes";
855   for (mirror::Class* klass : visitor.classes_to_prune_) {
856     std::string temp;
857     const char* name = klass->GetDescriptor(&temp);
858     VLOG(compiler) << "Pruning class " << name;
859     if (!compile_app_image_) {
860       DCHECK(IsBootClassLoaderClass(klass));
861     }
862     bool result = class_linker->RemoveClass(name, klass->GetClassLoader());
863     DCHECK(result);
864   }
865 
866   // Clear references to removed classes from the DexCaches.
867   ArtMethod* resolution_method = runtime->GetResolutionMethod();
868 
869   ScopedAssertNoThreadSuspension sa(self, __FUNCTION__);
870   ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);  // For ClassInClassTable
871   ReaderMutexLock mu2(self, *class_linker->DexLock());
872   for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
873     if (self->IsJWeakCleared(data.weak_root)) {
874       continue;
875     }
876     mirror::DexCache* dex_cache = self->DecodeJObject(data.weak_root)->AsDexCache();
877     for (size_t i = 0; i < dex_cache->NumResolvedTypes(); i++) {
878       Class* klass = dex_cache->GetResolvedType(i);
879       if (klass != nullptr && !KeepClass(klass)) {
880         dex_cache->SetResolvedType(i, nullptr);
881       }
882     }
883     ArtMethod** resolved_methods = dex_cache->GetResolvedMethods();
884     for (size_t i = 0, num = dex_cache->NumResolvedMethods(); i != num; ++i) {
885       ArtMethod* method =
886           mirror::DexCache::GetElementPtrSize(resolved_methods, i, target_ptr_size_);
887       DCHECK(method != nullptr) << "Expected resolution method instead of null method";
888       mirror::Class* declaring_class = method->GetDeclaringClass();
889       // Copied methods may be held live by a class which was not an image class but have a
890       // declaring class which is an image class. Set it to the resolution method to be safe and
891       // prevent dangling pointers.
892       if (method->IsCopied() || !KeepClass(declaring_class)) {
893         mirror::DexCache::SetElementPtrSize(resolved_methods,
894                                             i,
895                                             resolution_method,
896                                             target_ptr_size_);
897       } else {
898         // Check that the class is still in the classes table.
899         DCHECK(class_linker->ClassInClassTable(declaring_class)) << "Class "
900             << PrettyClass(declaring_class) << " not in class linker table";
901       }
902     }
903     ArtField** resolved_fields = dex_cache->GetResolvedFields();
904     for (size_t i = 0; i < dex_cache->NumResolvedFields(); i++) {
905       ArtField* field = mirror::DexCache::GetElementPtrSize(resolved_fields, i, target_ptr_size_);
906       if (field != nullptr && !KeepClass(field->GetDeclaringClass())) {
907         dex_cache->SetResolvedField(i, nullptr, target_ptr_size_);
908       }
909     }
910     // Clean the dex field. It might have been populated during the initialization phase, but
911     // contains data only valid during a real run.
912     dex_cache->SetFieldObject<false>(mirror::DexCache::DexOffset(), nullptr);
913   }
914 
915   // Drop the array class cache in the ClassLinker, as these are roots holding those classes live.
916   class_linker->DropFindArrayClassCache();
917 
918   // Clear to save RAM.
919   prune_class_memo_.clear();
920 }
921 
CheckNonImageClassesRemoved()922 void ImageWriter::CheckNonImageClassesRemoved() {
923   if (compiler_driver_.GetImageClasses() != nullptr) {
924     gc::Heap* heap = Runtime::Current()->GetHeap();
925     heap->VisitObjects(CheckNonImageClassesRemovedCallback, this);
926   }
927 }
928 
CheckNonImageClassesRemovedCallback(Object * obj,void * arg)929 void ImageWriter::CheckNonImageClassesRemovedCallback(Object* obj, void* arg) {
930   ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg);
931   if (obj->IsClass() && !image_writer->IsInBootImage(obj)) {
932     Class* klass = obj->AsClass();
933     if (!image_writer->KeepClass(klass)) {
934       image_writer->DumpImageClasses();
935       std::string temp;
936       CHECK(image_writer->KeepClass(klass)) << klass->GetDescriptor(&temp)
937                                             << " " << PrettyDescriptor(klass);
938     }
939   }
940 }
941 
DumpImageClasses()942 void ImageWriter::DumpImageClasses() {
943   auto image_classes = compiler_driver_.GetImageClasses();
944   CHECK(image_classes != nullptr);
945   for (const std::string& image_class : *image_classes) {
946     LOG(INFO) << " " << image_class;
947   }
948 }
949 
FindInternedString(mirror::String * string)950 mirror::String* ImageWriter::FindInternedString(mirror::String* string) {
951   Thread* const self = Thread::Current();
952   for (const ImageInfo& image_info : image_infos_) {
953     mirror::String* const found = image_info.intern_table_->LookupStrong(self, string);
954     DCHECK(image_info.intern_table_->LookupWeak(self, string) == nullptr)
955         << string->ToModifiedUtf8();
956     if (found != nullptr) {
957       return found;
958     }
959   }
960   if (compile_app_image_) {
961     Runtime* const runtime = Runtime::Current();
962     mirror::String* found = runtime->GetInternTable()->LookupStrong(self, string);
963     // If we found it in the runtime intern table it could either be in the boot image or interned
964     // during app image compilation. If it was in the boot image return that, otherwise return null
965     // since it belongs to another image space.
966     if (found != nullptr && runtime->GetHeap()->ObjectIsInBootImageSpace(found)) {
967       return found;
968     }
969     DCHECK(runtime->GetInternTable()->LookupWeak(self, string) == nullptr)
970         << string->ToModifiedUtf8();
971   }
972   return nullptr;
973 }
974 
CalculateObjectBinSlots(Object * obj)975 void ImageWriter::CalculateObjectBinSlots(Object* obj) {
976   DCHECK(obj != nullptr);
977   // if it is a string, we want to intern it if its not interned.
978   if (obj->GetClass()->IsStringClass()) {
979     size_t oat_index = GetOatIndex(obj);
980     ImageInfo& image_info = GetImageInfo(oat_index);
981 
982     // we must be an interned string that was forward referenced and already assigned
983     if (IsImageBinSlotAssigned(obj)) {
984       DCHECK_EQ(obj, FindInternedString(obj->AsString()));
985       return;
986     }
987     // Need to check if the string is already interned in another image info so that we don't have
988     // the intern tables of two different images contain the same string.
989     mirror::String* interned = FindInternedString(obj->AsString());
990     if (interned == nullptr) {
991       // Not in another image space, insert to our table.
992       interned = image_info.intern_table_->InternStrongImageString(obj->AsString());
993     }
994     if (obj != interned) {
995       if (!IsImageBinSlotAssigned(interned)) {
996         // interned obj is after us, allocate its location early
997         AssignImageBinSlot(interned);
998       }
999       // point those looking for this object to the interned version.
1000       SetImageBinSlot(obj, GetImageBinSlot(interned));
1001       return;
1002     }
1003     // else (obj == interned), nothing to do but fall through to the normal case
1004   }
1005 
1006   AssignImageBinSlot(obj);
1007 }
1008 
CreateImageRoots(size_t oat_index) const1009 ObjectArray<Object>* ImageWriter::CreateImageRoots(size_t oat_index) const {
1010   Runtime* runtime = Runtime::Current();
1011   ClassLinker* class_linker = runtime->GetClassLinker();
1012   Thread* self = Thread::Current();
1013   StackHandleScope<3> hs(self);
1014   Handle<Class> object_array_class(hs.NewHandle(
1015       class_linker->FindSystemClass(self, "[Ljava/lang/Object;")));
1016 
1017   std::unordered_set<const DexFile*> image_dex_files;
1018   for (auto& pair : dex_file_oat_index_map_) {
1019     const DexFile* image_dex_file = pair.first;
1020     size_t image_oat_index = pair.second;
1021     if (oat_index == image_oat_index) {
1022       image_dex_files.insert(image_dex_file);
1023     }
1024   }
1025 
1026   // build an Object[] of all the DexCaches used in the source_space_.
1027   // Since we can't hold the dex lock when allocating the dex_caches
1028   // ObjectArray, we lock the dex lock twice, first to get the number
1029   // of dex caches first and then lock it again to copy the dex
1030   // caches. We check that the number of dex caches does not change.
1031   size_t dex_cache_count = 0;
1032   {
1033     ReaderMutexLock mu(self, *class_linker->DexLock());
1034     // Count number of dex caches not in the boot image.
1035     for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
1036       mirror::DexCache* dex_cache =
1037           down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
1038       if (dex_cache == nullptr) {
1039         continue;
1040       }
1041       const DexFile* dex_file = dex_cache->GetDexFile();
1042       if (!IsInBootImage(dex_cache)) {
1043         dex_cache_count += image_dex_files.find(dex_file) != image_dex_files.end() ? 1u : 0u;
1044       }
1045     }
1046   }
1047   Handle<ObjectArray<Object>> dex_caches(
1048       hs.NewHandle(ObjectArray<Object>::Alloc(self, object_array_class.Get(), dex_cache_count)));
1049   CHECK(dex_caches.Get() != nullptr) << "Failed to allocate a dex cache array.";
1050   {
1051     ReaderMutexLock mu(self, *class_linker->DexLock());
1052     size_t non_image_dex_caches = 0;
1053     // Re-count number of non image dex caches.
1054     for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
1055       mirror::DexCache* dex_cache =
1056           down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
1057       if (dex_cache == nullptr) {
1058         continue;
1059       }
1060       const DexFile* dex_file = dex_cache->GetDexFile();
1061       if (!IsInBootImage(dex_cache)) {
1062         non_image_dex_caches += image_dex_files.find(dex_file) != image_dex_files.end() ? 1u : 0u;
1063       }
1064     }
1065     CHECK_EQ(dex_cache_count, non_image_dex_caches)
1066         << "The number of non-image dex caches changed.";
1067     size_t i = 0;
1068     for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
1069       mirror::DexCache* dex_cache =
1070           down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
1071       if (dex_cache == nullptr) {
1072         continue;
1073       }
1074       const DexFile* dex_file = dex_cache->GetDexFile();
1075       if (!IsInBootImage(dex_cache) && image_dex_files.find(dex_file) != image_dex_files.end()) {
1076         dex_caches->Set<false>(i, dex_cache);
1077         ++i;
1078       }
1079     }
1080   }
1081 
1082   // build an Object[] of the roots needed to restore the runtime
1083   auto image_roots(hs.NewHandle(
1084       ObjectArray<Object>::Alloc(self, object_array_class.Get(), ImageHeader::kImageRootsMax)));
1085   image_roots->Set<false>(ImageHeader::kDexCaches, dex_caches.Get());
1086   image_roots->Set<false>(ImageHeader::kClassRoots, class_linker->GetClassRoots());
1087   for (int i = 0; i < ImageHeader::kImageRootsMax; i++) {
1088     CHECK(image_roots->Get(i) != nullptr);
1089   }
1090   return image_roots.Get();
1091 }
1092 
1093 // Walk instance fields of the given Class. Separate function to allow recursion on the super
1094 // class.
WalkInstanceFields(mirror::Object * obj,mirror::Class * klass)1095 void ImageWriter::WalkInstanceFields(mirror::Object* obj, mirror::Class* klass) {
1096   // Visit fields of parent classes first.
1097   StackHandleScope<1> hs(Thread::Current());
1098   Handle<mirror::Class> h_class(hs.NewHandle(klass));
1099   mirror::Class* super = h_class->GetSuperClass();
1100   if (super != nullptr) {
1101     WalkInstanceFields(obj, super);
1102   }
1103   //
1104   size_t num_reference_fields = h_class->NumReferenceInstanceFields();
1105   MemberOffset field_offset = h_class->GetFirstReferenceInstanceFieldOffset();
1106   for (size_t i = 0; i < num_reference_fields; ++i) {
1107     mirror::Object* value = obj->GetFieldObject<mirror::Object>(field_offset);
1108     if (value != nullptr) {
1109       WalkFieldsInOrder(value);
1110     }
1111     field_offset = MemberOffset(field_offset.Uint32Value() +
1112                                 sizeof(mirror::HeapReference<mirror::Object>));
1113   }
1114 }
1115 
1116 // For an unvisited object, visit it then all its children found via fields.
WalkFieldsInOrder(mirror::Object * obj)1117 void ImageWriter::WalkFieldsInOrder(mirror::Object* obj) {
1118   if (IsInBootImage(obj)) {
1119     // Object is in the image, don't need to fix it up.
1120     return;
1121   }
1122   // Use our own visitor routine (instead of GC visitor) to get better locality between
1123   // an object and its fields
1124   if (!IsImageBinSlotAssigned(obj)) {
1125     // Walk instance fields of all objects
1126     StackHandleScope<2> hs(Thread::Current());
1127     Handle<mirror::Object> h_obj(hs.NewHandle(obj));
1128     Handle<mirror::Class> klass(hs.NewHandle(obj->GetClass()));
1129     // visit the object itself.
1130     CalculateObjectBinSlots(h_obj.Get());
1131     WalkInstanceFields(h_obj.Get(), klass.Get());
1132     // Walk static fields of a Class.
1133     if (h_obj->IsClass()) {
1134       size_t num_reference_static_fields = klass->NumReferenceStaticFields();
1135       MemberOffset field_offset = klass->GetFirstReferenceStaticFieldOffset(target_ptr_size_);
1136       for (size_t i = 0; i < num_reference_static_fields; ++i) {
1137         mirror::Object* value = h_obj->GetFieldObject<mirror::Object>(field_offset);
1138         if (value != nullptr) {
1139           WalkFieldsInOrder(value);
1140         }
1141         field_offset = MemberOffset(field_offset.Uint32Value() +
1142                                     sizeof(mirror::HeapReference<mirror::Object>));
1143       }
1144       // Visit and assign offsets for fields and field arrays.
1145       auto* as_klass = h_obj->AsClass();
1146       mirror::DexCache* dex_cache = as_klass->GetDexCache();
1147       DCHECK_NE(klass->GetStatus(), mirror::Class::kStatusError);
1148       if (compile_app_image_) {
1149         // Extra sanity, no boot loader classes should be left!
1150         CHECK(!IsBootClassLoaderClass(as_klass)) << PrettyClass(as_klass);
1151       }
1152       LengthPrefixedArray<ArtField>* fields[] = {
1153           as_klass->GetSFieldsPtr(), as_klass->GetIFieldsPtr(),
1154       };
1155       size_t oat_index = GetOatIndexForDexCache(dex_cache);
1156       ImageInfo& image_info = GetImageInfo(oat_index);
1157       {
1158         // Note: This table is only accessed from the image writer, so the lock is technically
1159         // unnecessary.
1160         WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
1161         // Insert in the class table for this iamge.
1162         image_info.class_table_->Insert(as_klass);
1163       }
1164       for (LengthPrefixedArray<ArtField>* cur_fields : fields) {
1165         // Total array length including header.
1166         if (cur_fields != nullptr) {
1167           const size_t header_size = LengthPrefixedArray<ArtField>::ComputeSize(0);
1168           // Forward the entire array at once.
1169           auto it = native_object_relocations_.find(cur_fields);
1170           CHECK(it == native_object_relocations_.end()) << "Field array " << cur_fields
1171                                                   << " already forwarded";
1172           size_t& offset = image_info.bin_slot_sizes_[kBinArtField];
1173           DCHECK(!IsInBootImage(cur_fields));
1174           native_object_relocations_.emplace(
1175               cur_fields,
1176               NativeObjectRelocation {
1177                   oat_index, offset, kNativeObjectRelocationTypeArtFieldArray
1178               });
1179           offset += header_size;
1180           // Forward individual fields so that we can quickly find where they belong.
1181           for (size_t i = 0, count = cur_fields->size(); i < count; ++i) {
1182             // Need to forward arrays separate of fields.
1183             ArtField* field = &cur_fields->At(i);
1184             auto it2 = native_object_relocations_.find(field);
1185             CHECK(it2 == native_object_relocations_.end()) << "Field at index=" << i
1186                 << " already assigned " << PrettyField(field) << " static=" << field->IsStatic();
1187             DCHECK(!IsInBootImage(field));
1188             native_object_relocations_.emplace(
1189                 field,
1190                 NativeObjectRelocation { oat_index, offset, kNativeObjectRelocationTypeArtField });
1191             offset += sizeof(ArtField);
1192           }
1193         }
1194       }
1195       // Visit and assign offsets for methods.
1196       size_t num_methods = as_klass->NumMethods();
1197       if (num_methods != 0) {
1198         bool any_dirty = false;
1199         for (auto& m : as_klass->GetMethods(target_ptr_size_)) {
1200           if (WillMethodBeDirty(&m)) {
1201             any_dirty = true;
1202             break;
1203           }
1204         }
1205         NativeObjectRelocationType type = any_dirty
1206             ? kNativeObjectRelocationTypeArtMethodDirty
1207             : kNativeObjectRelocationTypeArtMethodClean;
1208         Bin bin_type = BinTypeForNativeRelocationType(type);
1209         // Forward the entire array at once, but header first.
1210         const size_t method_alignment = ArtMethod::Alignment(target_ptr_size_);
1211         const size_t method_size = ArtMethod::Size(target_ptr_size_);
1212         const size_t header_size = LengthPrefixedArray<ArtMethod>::ComputeSize(0,
1213                                                                                method_size,
1214                                                                                method_alignment);
1215         LengthPrefixedArray<ArtMethod>* array = as_klass->GetMethodsPtr();
1216         auto it = native_object_relocations_.find(array);
1217         CHECK(it == native_object_relocations_.end())
1218             << "Method array " << array << " already forwarded";
1219         size_t& offset = image_info.bin_slot_sizes_[bin_type];
1220         DCHECK(!IsInBootImage(array));
1221         native_object_relocations_.emplace(array,
1222             NativeObjectRelocation {
1223                 oat_index,
1224                 offset,
1225                 any_dirty ? kNativeObjectRelocationTypeArtMethodArrayDirty
1226                           : kNativeObjectRelocationTypeArtMethodArrayClean });
1227         offset += header_size;
1228         for (auto& m : as_klass->GetMethods(target_ptr_size_)) {
1229           AssignMethodOffset(&m, type, oat_index);
1230         }
1231         (any_dirty ? dirty_methods_ : clean_methods_) += num_methods;
1232       }
1233       // Assign offsets for all runtime methods in the IMT since these may hold conflict tables
1234       // live.
1235       if (as_klass->ShouldHaveEmbeddedImtAndVTable()) {
1236         for (size_t i = 0; i < mirror::Class::kImtSize; ++i) {
1237           ArtMethod* imt_method = as_klass->GetEmbeddedImTableEntry(i, target_ptr_size_);
1238           DCHECK(imt_method != nullptr);
1239           if (imt_method->IsRuntimeMethod() &&
1240               !IsInBootImage(imt_method) &&
1241               !NativeRelocationAssigned(imt_method)) {
1242             AssignMethodOffset(imt_method, kNativeObjectRelocationTypeRuntimeMethod, oat_index);
1243           }
1244         }
1245       }
1246     } else if (h_obj->IsObjectArray()) {
1247       // Walk elements of an object array.
1248       int32_t length = h_obj->AsObjectArray<mirror::Object>()->GetLength();
1249       for (int32_t i = 0; i < length; i++) {
1250         mirror::ObjectArray<mirror::Object>* obj_array = h_obj->AsObjectArray<mirror::Object>();
1251         mirror::Object* value = obj_array->Get(i);
1252         if (value != nullptr) {
1253           WalkFieldsInOrder(value);
1254         }
1255       }
1256     } else if (h_obj->IsClassLoader()) {
1257       // Register the class loader if it has a class table.
1258       // The fake boot class loader should not get registered and we should end up with only one
1259       // class loader.
1260       mirror::ClassLoader* class_loader = h_obj->AsClassLoader();
1261       if (class_loader->GetClassTable() != nullptr) {
1262         class_loaders_.insert(class_loader);
1263       }
1264     }
1265   }
1266 }
1267 
NativeRelocationAssigned(void * ptr) const1268 bool ImageWriter::NativeRelocationAssigned(void* ptr) const {
1269   return native_object_relocations_.find(ptr) != native_object_relocations_.end();
1270 }
1271 
TryAssignConflictTableOffset(ImtConflictTable * table,size_t oat_index)1272 void ImageWriter::TryAssignConflictTableOffset(ImtConflictTable* table, size_t oat_index) {
1273   // No offset, or already assigned.
1274   if (table == nullptr || NativeRelocationAssigned(table)) {
1275     return;
1276   }
1277   CHECK(!IsInBootImage(table));
1278   // If the method is a conflict method we also want to assign the conflict table offset.
1279   ImageInfo& image_info = GetImageInfo(oat_index);
1280   const size_t size = table->ComputeSize(target_ptr_size_);
1281   native_object_relocations_.emplace(
1282       table,
1283       NativeObjectRelocation {
1284           oat_index,
1285           image_info.bin_slot_sizes_[kBinIMTConflictTable],
1286           kNativeObjectRelocationTypeIMTConflictTable});
1287   image_info.bin_slot_sizes_[kBinIMTConflictTable] += size;
1288 }
1289 
AssignMethodOffset(ArtMethod * method,NativeObjectRelocationType type,size_t oat_index)1290 void ImageWriter::AssignMethodOffset(ArtMethod* method,
1291                                      NativeObjectRelocationType type,
1292                                      size_t oat_index) {
1293   DCHECK(!IsInBootImage(method));
1294   CHECK(!NativeRelocationAssigned(method)) << "Method " << method << " already assigned "
1295       << PrettyMethod(method);
1296   if (method->IsRuntimeMethod()) {
1297     TryAssignConflictTableOffset(method->GetImtConflictTable(target_ptr_size_), oat_index);
1298   }
1299   ImageInfo& image_info = GetImageInfo(oat_index);
1300   size_t& offset = image_info.bin_slot_sizes_[BinTypeForNativeRelocationType(type)];
1301   native_object_relocations_.emplace(method, NativeObjectRelocation { oat_index, offset, type });
1302   offset += ArtMethod::Size(target_ptr_size_);
1303 }
1304 
WalkFieldsCallback(mirror::Object * obj,void * arg)1305 void ImageWriter::WalkFieldsCallback(mirror::Object* obj, void* arg) {
1306   ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
1307   DCHECK(writer != nullptr);
1308   writer->WalkFieldsInOrder(obj);
1309 }
1310 
UnbinObjectsIntoOffsetCallback(mirror::Object * obj,void * arg)1311 void ImageWriter::UnbinObjectsIntoOffsetCallback(mirror::Object* obj, void* arg) {
1312   ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
1313   DCHECK(writer != nullptr);
1314   if (!writer->IsInBootImage(obj)) {
1315     writer->UnbinObjectsIntoOffset(obj);
1316   }
1317 }
1318 
UnbinObjectsIntoOffset(mirror::Object * obj)1319 void ImageWriter::UnbinObjectsIntoOffset(mirror::Object* obj) {
1320   DCHECK(!IsInBootImage(obj));
1321   CHECK(obj != nullptr);
1322 
1323   // We know the bin slot, and the total bin sizes for all objects by now,
1324   // so calculate the object's final image offset.
1325 
1326   DCHECK(IsImageBinSlotAssigned(obj));
1327   BinSlot bin_slot = GetImageBinSlot(obj);
1328   // Change the lockword from a bin slot into an offset
1329   AssignImageOffset(obj, bin_slot);
1330 }
1331 
CalculateNewObjectOffsets()1332 void ImageWriter::CalculateNewObjectOffsets() {
1333   Thread* const self = Thread::Current();
1334   StackHandleScopeCollection handles(self);
1335   std::vector<Handle<ObjectArray<Object>>> image_roots;
1336   for (size_t i = 0, size = oat_filenames_.size(); i != size; ++i) {
1337     image_roots.push_back(handles.NewHandle(CreateImageRoots(i)));
1338   }
1339 
1340   auto* runtime = Runtime::Current();
1341   auto* heap = runtime->GetHeap();
1342 
1343   // Leave space for the header, but do not write it yet, we need to
1344   // know where image_roots is going to end up
1345   image_objects_offset_begin_ = RoundUp(sizeof(ImageHeader), kObjectAlignment);  // 64-bit-alignment
1346 
1347   const size_t method_alignment = ArtMethod::Alignment(target_ptr_size_);
1348   // Write the image runtime methods.
1349   image_methods_[ImageHeader::kResolutionMethod] = runtime->GetResolutionMethod();
1350   image_methods_[ImageHeader::kImtConflictMethod] = runtime->GetImtConflictMethod();
1351   image_methods_[ImageHeader::kImtUnimplementedMethod] = runtime->GetImtUnimplementedMethod();
1352   image_methods_[ImageHeader::kCalleeSaveMethod] = runtime->GetCalleeSaveMethod(Runtime::kSaveAll);
1353   image_methods_[ImageHeader::kRefsOnlySaveMethod] =
1354       runtime->GetCalleeSaveMethod(Runtime::kRefsOnly);
1355   image_methods_[ImageHeader::kRefsAndArgsSaveMethod] =
1356       runtime->GetCalleeSaveMethod(Runtime::kRefsAndArgs);
1357   // Visit image methods first to have the main runtime methods in the first image.
1358   for (auto* m : image_methods_) {
1359     CHECK(m != nullptr);
1360     CHECK(m->IsRuntimeMethod());
1361     DCHECK_EQ(compile_app_image_, IsInBootImage(m)) << "Trampolines should be in boot image";
1362     if (!IsInBootImage(m)) {
1363       AssignMethodOffset(m, kNativeObjectRelocationTypeRuntimeMethod, GetDefaultOatIndex());
1364     }
1365   }
1366 
1367   // Clear any pre-existing monitors which may have been in the monitor words, assign bin slots.
1368   heap->VisitObjects(WalkFieldsCallback, this);
1369 
1370   // Calculate size of the dex cache arrays slot and prepare offsets.
1371   PrepareDexCacheArraySlots();
1372 
1373   // Calculate the sizes of the intern tables and class tables.
1374   for (ImageInfo& image_info : image_infos_) {
1375     // Calculate how big the intern table will be after being serialized.
1376     InternTable* const intern_table = image_info.intern_table_.get();
1377     CHECK_EQ(intern_table->WeakSize(), 0u) << " should have strong interned all the strings";
1378     image_info.intern_table_bytes_ = intern_table->WriteToMemory(nullptr);
1379     // Calculate the size of the class table.
1380     ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
1381     image_info.class_table_bytes_ += image_info.class_table_->WriteToMemory(nullptr);
1382   }
1383 
1384   // Calculate bin slot offsets.
1385   for (ImageInfo& image_info : image_infos_) {
1386     size_t bin_offset = image_objects_offset_begin_;
1387     for (size_t i = 0; i != kBinSize; ++i) {
1388       switch (i) {
1389         case kBinArtMethodClean:
1390         case kBinArtMethodDirty: {
1391           bin_offset = RoundUp(bin_offset, method_alignment);
1392           break;
1393         }
1394         case kBinIMTConflictTable: {
1395           bin_offset = RoundUp(bin_offset, target_ptr_size_);
1396           break;
1397         }
1398         default: {
1399           // Normal alignment.
1400         }
1401       }
1402       image_info.bin_slot_offsets_[i] = bin_offset;
1403       bin_offset += image_info.bin_slot_sizes_[i];
1404     }
1405     // NOTE: There may be additional padding between the bin slots and the intern table.
1406     DCHECK_EQ(image_info.image_end_,
1407               GetBinSizeSum(image_info, kBinMirrorCount) + image_objects_offset_begin_);
1408   }
1409 
1410   // Calculate image offsets.
1411   size_t image_offset = 0;
1412   for (ImageInfo& image_info : image_infos_) {
1413     image_info.image_begin_ = global_image_begin_ + image_offset;
1414     image_info.image_offset_ = image_offset;
1415     ImageSection unused_sections[ImageHeader::kSectionCount];
1416     image_info.image_size_ = RoundUp(image_info.CreateImageSections(unused_sections), kPageSize);
1417     // There should be no gaps until the next image.
1418     image_offset += image_info.image_size_;
1419   }
1420 
1421   // Transform each object's bin slot into an offset which will be used to do the final copy.
1422   heap->VisitObjects(UnbinObjectsIntoOffsetCallback, this);
1423 
1424   // DCHECK_EQ(image_end_, GetBinSizeSum(kBinMirrorCount) + image_objects_offset_begin_);
1425 
1426   size_t i = 0;
1427   for (ImageInfo& image_info : image_infos_) {
1428     image_info.image_roots_address_ = PointerToLowMemUInt32(GetImageAddress(image_roots[i].Get()));
1429     i++;
1430   }
1431 
1432   // Update the native relocations by adding their bin sums.
1433   for (auto& pair : native_object_relocations_) {
1434     NativeObjectRelocation& relocation = pair.second;
1435     Bin bin_type = BinTypeForNativeRelocationType(relocation.type);
1436     ImageInfo& image_info = GetImageInfo(relocation.oat_index);
1437     relocation.offset += image_info.bin_slot_offsets_[bin_type];
1438   }
1439 
1440   // Note that image_info.image_end_ is left at end of used mirror object section.
1441 }
1442 
CreateImageSections(ImageSection * out_sections) const1443 size_t ImageWriter::ImageInfo::CreateImageSections(ImageSection* out_sections) const {
1444   DCHECK(out_sections != nullptr);
1445 
1446   // Do not round up any sections here that are represented by the bins since it will break
1447   // offsets.
1448 
1449   // Objects section
1450   ImageSection* objects_section = &out_sections[ImageHeader::kSectionObjects];
1451   *objects_section = ImageSection(0u, image_end_);
1452 
1453   // Add field section.
1454   ImageSection* field_section = &out_sections[ImageHeader::kSectionArtFields];
1455   *field_section = ImageSection(bin_slot_offsets_[kBinArtField], bin_slot_sizes_[kBinArtField]);
1456   CHECK_EQ(bin_slot_offsets_[kBinArtField], field_section->Offset());
1457 
1458   // Add method section.
1459   ImageSection* methods_section = &out_sections[ImageHeader::kSectionArtMethods];
1460   *methods_section = ImageSection(
1461       bin_slot_offsets_[kBinArtMethodClean],
1462       bin_slot_sizes_[kBinArtMethodClean] + bin_slot_sizes_[kBinArtMethodDirty]);
1463 
1464   // Conflict tables section.
1465   ImageSection* imt_conflict_tables_section = &out_sections[ImageHeader::kSectionIMTConflictTables];
1466   *imt_conflict_tables_section = ImageSection(bin_slot_offsets_[kBinIMTConflictTable],
1467                                               bin_slot_sizes_[kBinIMTConflictTable]);
1468 
1469   // Runtime methods section.
1470   ImageSection* runtime_methods_section = &out_sections[ImageHeader::kSectionRuntimeMethods];
1471   *runtime_methods_section = ImageSection(bin_slot_offsets_[kBinRuntimeMethod],
1472                                           bin_slot_sizes_[kBinRuntimeMethod]);
1473 
1474   // Add dex cache arrays section.
1475   ImageSection* dex_cache_arrays_section = &out_sections[ImageHeader::kSectionDexCacheArrays];
1476   *dex_cache_arrays_section = ImageSection(bin_slot_offsets_[kBinDexCacheArray],
1477                                            bin_slot_sizes_[kBinDexCacheArray]);
1478 
1479   // Round up to the alignment the string table expects. See HashSet::WriteToMemory.
1480   size_t cur_pos = RoundUp(dex_cache_arrays_section->End(), sizeof(uint64_t));
1481   // Calculate the size of the interned strings.
1482   ImageSection* interned_strings_section = &out_sections[ImageHeader::kSectionInternedStrings];
1483   *interned_strings_section = ImageSection(cur_pos, intern_table_bytes_);
1484   cur_pos = interned_strings_section->End();
1485   // Round up to the alignment the class table expects. See HashSet::WriteToMemory.
1486   cur_pos = RoundUp(cur_pos, sizeof(uint64_t));
1487   // Calculate the size of the class table section.
1488   ImageSection* class_table_section = &out_sections[ImageHeader::kSectionClassTable];
1489   *class_table_section = ImageSection(cur_pos, class_table_bytes_);
1490   cur_pos = class_table_section->End();
1491   // Image end goes right before the start of the image bitmap.
1492   return cur_pos;
1493 }
1494 
CreateHeader(size_t oat_index)1495 void ImageWriter::CreateHeader(size_t oat_index) {
1496   ImageInfo& image_info = GetImageInfo(oat_index);
1497   const uint8_t* oat_file_begin = image_info.oat_file_begin_;
1498   const uint8_t* oat_file_end = oat_file_begin + image_info.oat_loaded_size_;
1499   const uint8_t* oat_data_end = image_info.oat_data_begin_ + image_info.oat_size_;
1500 
1501   // Create the image sections.
1502   ImageSection sections[ImageHeader::kSectionCount];
1503   const size_t image_end = image_info.CreateImageSections(sections);
1504 
1505   // Finally bitmap section.
1506   const size_t bitmap_bytes = image_info.image_bitmap_->Size();
1507   auto* bitmap_section = &sections[ImageHeader::kSectionImageBitmap];
1508   *bitmap_section = ImageSection(RoundUp(image_end, kPageSize), RoundUp(bitmap_bytes, kPageSize));
1509   if (VLOG_IS_ON(compiler)) {
1510     LOG(INFO) << "Creating header for " << oat_filenames_[oat_index];
1511     size_t idx = 0;
1512     for (const ImageSection& section : sections) {
1513       LOG(INFO) << static_cast<ImageHeader::ImageSections>(idx) << " " << section;
1514       ++idx;
1515     }
1516     LOG(INFO) << "Methods: clean=" << clean_methods_ << " dirty=" << dirty_methods_;
1517     LOG(INFO) << "Image roots address=" << std::hex << image_info.image_roots_address_ << std::dec;
1518     LOG(INFO) << "Image begin=" << std::hex << reinterpret_cast<uintptr_t>(global_image_begin_)
1519               << " Image offset=" << image_info.image_offset_ << std::dec;
1520     LOG(INFO) << "Oat file begin=" << std::hex << reinterpret_cast<uintptr_t>(oat_file_begin)
1521               << " Oat data begin=" << reinterpret_cast<uintptr_t>(image_info.oat_data_begin_)
1522               << " Oat data end=" << reinterpret_cast<uintptr_t>(oat_data_end)
1523               << " Oat file end=" << reinterpret_cast<uintptr_t>(oat_file_end);
1524   }
1525   // Store boot image info for app image so that we can relocate.
1526   uint32_t boot_image_begin = 0;
1527   uint32_t boot_image_end = 0;
1528   uint32_t boot_oat_begin = 0;
1529   uint32_t boot_oat_end = 0;
1530   gc::Heap* const heap = Runtime::Current()->GetHeap();
1531   heap->GetBootImagesSize(&boot_image_begin, &boot_image_end, &boot_oat_begin, &boot_oat_end);
1532 
1533   // Create the header, leave 0 for data size since we will fill this in as we are writing the
1534   // image.
1535   new (image_info.image_->Begin()) ImageHeader(PointerToLowMemUInt32(image_info.image_begin_),
1536                                                image_end,
1537                                                sections,
1538                                                image_info.image_roots_address_,
1539                                                image_info.oat_checksum_,
1540                                                PointerToLowMemUInt32(oat_file_begin),
1541                                                PointerToLowMemUInt32(image_info.oat_data_begin_),
1542                                                PointerToLowMemUInt32(oat_data_end),
1543                                                PointerToLowMemUInt32(oat_file_end),
1544                                                boot_image_begin,
1545                                                boot_image_end - boot_image_begin,
1546                                                boot_oat_begin,
1547                                                boot_oat_end - boot_oat_begin,
1548                                                target_ptr_size_,
1549                                                compile_pic_,
1550                                                /*is_pic*/compile_app_image_,
1551                                                image_storage_mode_,
1552                                                /*data_size*/0u);
1553 }
1554 
GetImageMethodAddress(ArtMethod * method)1555 ArtMethod* ImageWriter::GetImageMethodAddress(ArtMethod* method) {
1556   auto it = native_object_relocations_.find(method);
1557   CHECK(it != native_object_relocations_.end()) << PrettyMethod(method) << " @ " << method;
1558   size_t oat_index = GetOatIndex(method->GetDexCache());
1559   ImageInfo& image_info = GetImageInfo(oat_index);
1560   CHECK_GE(it->second.offset, image_info.image_end_) << "ArtMethods should be after Objects";
1561   return reinterpret_cast<ArtMethod*>(image_info.image_begin_ + it->second.offset);
1562 }
1563 
1564 class FixupRootVisitor : public RootVisitor {
1565  public:
FixupRootVisitor(ImageWriter * image_writer)1566   explicit FixupRootVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {
1567   }
1568 
VisitRoots(mirror::Object *** roots,size_t count,const RootInfo & info ATTRIBUTE_UNUSED)1569   void VisitRoots(mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED)
1570       OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
1571     for (size_t i = 0; i < count; ++i) {
1572       *roots[i] = image_writer_->GetImageAddress(*roots[i]);
1573     }
1574   }
1575 
VisitRoots(mirror::CompressedReference<mirror::Object> ** roots,size_t count,const RootInfo & info ATTRIBUTE_UNUSED)1576   void VisitRoots(mirror::CompressedReference<mirror::Object>** roots, size_t count,
1577                   const RootInfo& info ATTRIBUTE_UNUSED)
1578       OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
1579     for (size_t i = 0; i < count; ++i) {
1580       roots[i]->Assign(image_writer_->GetImageAddress(roots[i]->AsMirrorPtr()));
1581     }
1582   }
1583 
1584  private:
1585   ImageWriter* const image_writer_;
1586 };
1587 
CopyAndFixupImtConflictTable(ImtConflictTable * orig,ImtConflictTable * copy)1588 void ImageWriter::CopyAndFixupImtConflictTable(ImtConflictTable* orig, ImtConflictTable* copy) {
1589   const size_t count = orig->NumEntries(target_ptr_size_);
1590   for (size_t i = 0; i < count; ++i) {
1591     ArtMethod* interface_method = orig->GetInterfaceMethod(i, target_ptr_size_);
1592     ArtMethod* implementation_method = orig->GetImplementationMethod(i, target_ptr_size_);
1593     copy->SetInterfaceMethod(i, target_ptr_size_, NativeLocationInImage(interface_method));
1594     copy->SetImplementationMethod(i,
1595                                   target_ptr_size_,
1596                                   NativeLocationInImage(implementation_method));
1597   }
1598 }
1599 
CopyAndFixupNativeData(size_t oat_index)1600 void ImageWriter::CopyAndFixupNativeData(size_t oat_index) {
1601   const ImageInfo& image_info = GetImageInfo(oat_index);
1602   // Copy ArtFields and methods to their locations and update the array for convenience.
1603   for (auto& pair : native_object_relocations_) {
1604     NativeObjectRelocation& relocation = pair.second;
1605     // Only work with fields and methods that are in the current oat file.
1606     if (relocation.oat_index != oat_index) {
1607       continue;
1608     }
1609     auto* dest = image_info.image_->Begin() + relocation.offset;
1610     DCHECK_GE(dest, image_info.image_->Begin() + image_info.image_end_);
1611     DCHECK(!IsInBootImage(pair.first));
1612     switch (relocation.type) {
1613       case kNativeObjectRelocationTypeArtField: {
1614         memcpy(dest, pair.first, sizeof(ArtField));
1615         reinterpret_cast<ArtField*>(dest)->SetDeclaringClass(
1616             GetImageAddress(reinterpret_cast<ArtField*>(pair.first)->GetDeclaringClass()));
1617         break;
1618       }
1619       case kNativeObjectRelocationTypeRuntimeMethod:
1620       case kNativeObjectRelocationTypeArtMethodClean:
1621       case kNativeObjectRelocationTypeArtMethodDirty: {
1622         CopyAndFixupMethod(reinterpret_cast<ArtMethod*>(pair.first),
1623                            reinterpret_cast<ArtMethod*>(dest),
1624                            image_info);
1625         break;
1626       }
1627       // For arrays, copy just the header since the elements will get copied by their corresponding
1628       // relocations.
1629       case kNativeObjectRelocationTypeArtFieldArray: {
1630         memcpy(dest, pair.first, LengthPrefixedArray<ArtField>::ComputeSize(0));
1631         break;
1632       }
1633       case kNativeObjectRelocationTypeArtMethodArrayClean:
1634       case kNativeObjectRelocationTypeArtMethodArrayDirty: {
1635         size_t size = ArtMethod::Size(target_ptr_size_);
1636         size_t alignment = ArtMethod::Alignment(target_ptr_size_);
1637         memcpy(dest, pair.first, LengthPrefixedArray<ArtMethod>::ComputeSize(0, size, alignment));
1638         // Clear padding to avoid non-deterministic data in the image (and placate valgrind).
1639         reinterpret_cast<LengthPrefixedArray<ArtMethod>*>(dest)->ClearPadding(size, alignment);
1640         break;
1641       }
1642       case kNativeObjectRelocationTypeDexCacheArray:
1643         // Nothing to copy here, everything is done in FixupDexCache().
1644         break;
1645       case kNativeObjectRelocationTypeIMTConflictTable: {
1646         auto* orig_table = reinterpret_cast<ImtConflictTable*>(pair.first);
1647         CopyAndFixupImtConflictTable(
1648             orig_table,
1649             new(dest)ImtConflictTable(orig_table->NumEntries(target_ptr_size_), target_ptr_size_));
1650         break;
1651       }
1652     }
1653   }
1654   // Fixup the image method roots.
1655   auto* image_header = reinterpret_cast<ImageHeader*>(image_info.image_->Begin());
1656   for (size_t i = 0; i < ImageHeader::kImageMethodsCount; ++i) {
1657     ArtMethod* method = image_methods_[i];
1658     CHECK(method != nullptr);
1659     if (!IsInBootImage(method)) {
1660       method = NativeLocationInImage(method);
1661     }
1662     image_header->SetImageMethod(static_cast<ImageHeader::ImageMethod>(i), method);
1663   }
1664   FixupRootVisitor root_visitor(this);
1665 
1666   // Write the intern table into the image.
1667   if (image_info.intern_table_bytes_ > 0) {
1668     const ImageSection& intern_table_section = image_header->GetImageSection(
1669         ImageHeader::kSectionInternedStrings);
1670     InternTable* const intern_table = image_info.intern_table_.get();
1671     uint8_t* const intern_table_memory_ptr =
1672         image_info.image_->Begin() + intern_table_section.Offset();
1673     const size_t intern_table_bytes = intern_table->WriteToMemory(intern_table_memory_ptr);
1674     CHECK_EQ(intern_table_bytes, image_info.intern_table_bytes_);
1675     // Fixup the pointers in the newly written intern table to contain image addresses.
1676     InternTable temp_intern_table;
1677     // Note that we require that ReadFromMemory does not make an internal copy of the elements so that
1678     // the VisitRoots() will update the memory directly rather than the copies.
1679     // This also relies on visit roots not doing any verification which could fail after we update
1680     // the roots to be the image addresses.
1681     temp_intern_table.AddTableFromMemory(intern_table_memory_ptr);
1682     CHECK_EQ(temp_intern_table.Size(), intern_table->Size());
1683     temp_intern_table.VisitRoots(&root_visitor, kVisitRootFlagAllRoots);
1684   }
1685   // Write the class table(s) into the image. class_table_bytes_ may be 0 if there are multiple
1686   // class loaders. Writing multiple class tables into the image is currently unsupported.
1687   if (image_info.class_table_bytes_ > 0u) {
1688     const ImageSection& class_table_section = image_header->GetImageSection(
1689         ImageHeader::kSectionClassTable);
1690     uint8_t* const class_table_memory_ptr =
1691         image_info.image_->Begin() + class_table_section.Offset();
1692     ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
1693 
1694     ClassTable* table = image_info.class_table_.get();
1695     CHECK(table != nullptr);
1696     const size_t class_table_bytes = table->WriteToMemory(class_table_memory_ptr);
1697     CHECK_EQ(class_table_bytes, image_info.class_table_bytes_);
1698     // Fixup the pointers in the newly written class table to contain image addresses. See
1699     // above comment for intern tables.
1700     ClassTable temp_class_table;
1701     temp_class_table.ReadFromMemory(class_table_memory_ptr);
1702     CHECK_EQ(temp_class_table.NumZygoteClasses(), table->NumNonZygoteClasses() +
1703              table->NumZygoteClasses());
1704     BufferedRootVisitor<kDefaultBufferedRootCount> buffered_visitor(&root_visitor,
1705                                                                     RootInfo(kRootUnknown));
1706     temp_class_table.VisitRoots(buffered_visitor);
1707   }
1708 }
1709 
CopyAndFixupObjects()1710 void ImageWriter::CopyAndFixupObjects() {
1711   gc::Heap* heap = Runtime::Current()->GetHeap();
1712   heap->VisitObjects(CopyAndFixupObjectsCallback, this);
1713   // Fix up the object previously had hash codes.
1714   for (const auto& hash_pair : saved_hashcode_map_) {
1715     Object* obj = hash_pair.first;
1716     DCHECK_EQ(obj->GetLockWord<kVerifyNone>(false).ReadBarrierState(), 0U);
1717     obj->SetLockWord<kVerifyNone>(LockWord::FromHashCode(hash_pair.second, 0U), false);
1718   }
1719   saved_hashcode_map_.clear();
1720 }
1721 
CopyAndFixupObjectsCallback(Object * obj,void * arg)1722 void ImageWriter::CopyAndFixupObjectsCallback(Object* obj, void* arg) {
1723   DCHECK(obj != nullptr);
1724   DCHECK(arg != nullptr);
1725   reinterpret_cast<ImageWriter*>(arg)->CopyAndFixupObject(obj);
1726 }
1727 
FixupPointerArray(mirror::Object * dst,mirror::PointerArray * arr,mirror::Class * klass,Bin array_type)1728 void ImageWriter::FixupPointerArray(mirror::Object* dst, mirror::PointerArray* arr,
1729                                     mirror::Class* klass, Bin array_type) {
1730   CHECK(klass->IsArrayClass());
1731   CHECK(arr->IsIntArray() || arr->IsLongArray()) << PrettyClass(klass) << " " << arr;
1732   // Fixup int and long pointers for the ArtMethod or ArtField arrays.
1733   const size_t num_elements = arr->GetLength();
1734   dst->SetClass(GetImageAddress(arr->GetClass()));
1735   auto* dest_array = down_cast<mirror::PointerArray*>(dst);
1736   for (size_t i = 0, count = num_elements; i < count; ++i) {
1737     void* elem = arr->GetElementPtrSize<void*>(i, target_ptr_size_);
1738     if (elem != nullptr && !IsInBootImage(elem)) {
1739       auto it = native_object_relocations_.find(elem);
1740       if (UNLIKELY(it == native_object_relocations_.end())) {
1741         if (it->second.IsArtMethodRelocation()) {
1742           auto* method = reinterpret_cast<ArtMethod*>(elem);
1743           LOG(FATAL) << "No relocation entry for ArtMethod " << PrettyMethod(method) << " @ "
1744               << method << " idx=" << i << "/" << num_elements << " with declaring class "
1745               << PrettyClass(method->GetDeclaringClass());
1746         } else {
1747           CHECK_EQ(array_type, kBinArtField);
1748           auto* field = reinterpret_cast<ArtField*>(elem);
1749           LOG(FATAL) << "No relocation entry for ArtField " << PrettyField(field) << " @ "
1750               << field << " idx=" << i << "/" << num_elements << " with declaring class "
1751               << PrettyClass(field->GetDeclaringClass());
1752         }
1753         UNREACHABLE();
1754       } else {
1755         ImageInfo& image_info = GetImageInfo(it->second.oat_index);
1756         elem = image_info.image_begin_ + it->second.offset;
1757       }
1758     }
1759     dest_array->SetElementPtrSize<false, true>(i, elem, target_ptr_size_);
1760   }
1761 }
1762 
CopyAndFixupObject(Object * obj)1763 void ImageWriter::CopyAndFixupObject(Object* obj) {
1764   if (IsInBootImage(obj)) {
1765     return;
1766   }
1767   size_t offset = GetImageOffset(obj);
1768   size_t oat_index = GetOatIndex(obj);
1769   ImageInfo& image_info = GetImageInfo(oat_index);
1770   auto* dst = reinterpret_cast<Object*>(image_info.image_->Begin() + offset);
1771   DCHECK_LT(offset, image_info.image_end_);
1772   const auto* src = reinterpret_cast<const uint8_t*>(obj);
1773 
1774   image_info.image_bitmap_->Set(dst);  // Mark the obj as live.
1775 
1776   const size_t n = obj->SizeOf();
1777   DCHECK_LE(offset + n, image_info.image_->Size());
1778   memcpy(dst, src, n);
1779 
1780   // Write in a hash code of objects which have inflated monitors or a hash code in their monitor
1781   // word.
1782   const auto it = saved_hashcode_map_.find(obj);
1783   dst->SetLockWord(it != saved_hashcode_map_.end() ?
1784       LockWord::FromHashCode(it->second, 0u) : LockWord::Default(), false);
1785   FixupObject(obj, dst);
1786 }
1787 
1788 // Rewrite all the references in the copied object to point to their image address equivalent
1789 class FixupVisitor {
1790  public:
FixupVisitor(ImageWriter * image_writer,Object * copy)1791   FixupVisitor(ImageWriter* image_writer, Object* copy) : image_writer_(image_writer), copy_(copy) {
1792   }
1793 
1794   // Ignore class roots since we don't have a way to map them to the destination. These are handled
1795   // with other logic.
VisitRootIfNonNull(mirror::CompressedReference<mirror::Object> * root ATTRIBUTE_UNUSED) const1796   void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED)
1797       const {}
VisitRoot(mirror::CompressedReference<mirror::Object> * root ATTRIBUTE_UNUSED) const1798   void VisitRoot(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const {}
1799 
1800 
operator ()(Object * obj,MemberOffset offset,bool is_static ATTRIBUTE_UNUSED) const1801   void operator()(Object* obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
1802       REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1803     Object* ref = obj->GetFieldObject<Object, kVerifyNone>(offset);
1804     // Use SetFieldObjectWithoutWriteBarrier to avoid card marking since we are writing to the
1805     // image.
1806     copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
1807         offset,
1808         image_writer_->GetImageAddress(ref));
1809   }
1810 
1811   // java.lang.ref.Reference visitor.
operator ()(mirror::Class * klass ATTRIBUTE_UNUSED,mirror::Reference * ref) const1812   void operator()(mirror::Class* klass ATTRIBUTE_UNUSED, mirror::Reference* ref) const
1813       SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
1814     copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
1815         mirror::Reference::ReferentOffset(),
1816         image_writer_->GetImageAddress(ref->GetReferent()));
1817   }
1818 
1819  protected:
1820   ImageWriter* const image_writer_;
1821   mirror::Object* const copy_;
1822 };
1823 
1824 class FixupClassVisitor FINAL : public FixupVisitor {
1825  public:
FixupClassVisitor(ImageWriter * image_writer,Object * copy)1826   FixupClassVisitor(ImageWriter* image_writer, Object* copy) : FixupVisitor(image_writer, copy) {
1827   }
1828 
operator ()(Object * obj,MemberOffset offset,bool is_static ATTRIBUTE_UNUSED) const1829   void operator()(Object* obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
1830       REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1831     DCHECK(obj->IsClass());
1832     FixupVisitor::operator()(obj, offset, /*is_static*/false);
1833   }
1834 
operator ()(mirror::Class * klass ATTRIBUTE_UNUSED,mirror::Reference * ref ATTRIBUTE_UNUSED) const1835   void operator()(mirror::Class* klass ATTRIBUTE_UNUSED,
1836                   mirror::Reference* ref ATTRIBUTE_UNUSED) const
1837       SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
1838     LOG(FATAL) << "Reference not expected here.";
1839   }
1840 };
1841 
NativeOffsetInImage(void * obj)1842 uintptr_t ImageWriter::NativeOffsetInImage(void* obj) {
1843   DCHECK(obj != nullptr);
1844   DCHECK(!IsInBootImage(obj));
1845   auto it = native_object_relocations_.find(obj);
1846   CHECK(it != native_object_relocations_.end()) << obj << " spaces "
1847       << Runtime::Current()->GetHeap()->DumpSpaces();
1848   const NativeObjectRelocation& relocation = it->second;
1849   return relocation.offset;
1850 }
1851 
1852 template <typename T>
NativeLocationInImage(T * obj)1853 T* ImageWriter::NativeLocationInImage(T* obj) {
1854   if (obj == nullptr || IsInBootImage(obj)) {
1855     return obj;
1856   } else {
1857     auto it = native_object_relocations_.find(obj);
1858     CHECK(it != native_object_relocations_.end()) << obj << " spaces "
1859         << Runtime::Current()->GetHeap()->DumpSpaces();
1860     const NativeObjectRelocation& relocation = it->second;
1861     ImageInfo& image_info = GetImageInfo(relocation.oat_index);
1862     return reinterpret_cast<T*>(image_info.image_begin_ + relocation.offset);
1863   }
1864 }
1865 
1866 template <typename T>
NativeCopyLocation(T * obj,mirror::DexCache * dex_cache)1867 T* ImageWriter::NativeCopyLocation(T* obj, mirror::DexCache* dex_cache) {
1868   if (obj == nullptr || IsInBootImage(obj)) {
1869     return obj;
1870   } else {
1871     size_t oat_index = GetOatIndexForDexCache(dex_cache);
1872     ImageInfo& image_info = GetImageInfo(oat_index);
1873     return reinterpret_cast<T*>(image_info.image_->Begin() + NativeOffsetInImage(obj));
1874   }
1875 }
1876 
1877 class NativeLocationVisitor {
1878  public:
NativeLocationVisitor(ImageWriter * image_writer)1879   explicit NativeLocationVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {}
1880 
1881   template <typename T>
operator ()(T * ptr) const1882   T* operator()(T* ptr) const SHARED_REQUIRES(Locks::mutator_lock_) {
1883     return image_writer_->NativeLocationInImage(ptr);
1884   }
1885 
1886  private:
1887   ImageWriter* const image_writer_;
1888 };
1889 
FixupClass(mirror::Class * orig,mirror::Class * copy)1890 void ImageWriter::FixupClass(mirror::Class* orig, mirror::Class* copy) {
1891   orig->FixupNativePointers(copy, target_ptr_size_, NativeLocationVisitor(this));
1892   FixupClassVisitor visitor(this, copy);
1893   static_cast<mirror::Object*>(orig)->VisitReferences(visitor, visitor);
1894 
1895   // Remove the clinitThreadId. This is required for image determinism.
1896   copy->SetClinitThreadId(static_cast<pid_t>(0));
1897 }
1898 
FixupObject(Object * orig,Object * copy)1899 void ImageWriter::FixupObject(Object* orig, Object* copy) {
1900   DCHECK(orig != nullptr);
1901   DCHECK(copy != nullptr);
1902   if (kUseBakerOrBrooksReadBarrier) {
1903     orig->AssertReadBarrierPointer();
1904     if (kUseBrooksReadBarrier) {
1905       // Note the address 'copy' isn't the same as the image address of 'orig'.
1906       copy->SetReadBarrierPointer(GetImageAddress(orig));
1907       DCHECK_EQ(copy->GetReadBarrierPointer(), GetImageAddress(orig));
1908     }
1909   }
1910   auto* klass = orig->GetClass();
1911   if (klass->IsIntArrayClass() || klass->IsLongArrayClass()) {
1912     // Is this a native pointer array?
1913     auto it = pointer_arrays_.find(down_cast<mirror::PointerArray*>(orig));
1914     if (it != pointer_arrays_.end()) {
1915       // Should only need to fixup every pointer array exactly once.
1916       FixupPointerArray(copy, down_cast<mirror::PointerArray*>(orig), klass, it->second);
1917       pointer_arrays_.erase(it);
1918       return;
1919     }
1920   }
1921   if (orig->IsClass()) {
1922     FixupClass(orig->AsClass<kVerifyNone>(), down_cast<mirror::Class*>(copy));
1923   } else {
1924     if (klass == mirror::Method::StaticClass() || klass == mirror::Constructor::StaticClass()) {
1925       // Need to go update the ArtMethod.
1926       auto* dest = down_cast<mirror::AbstractMethod*>(copy);
1927       auto* src = down_cast<mirror::AbstractMethod*>(orig);
1928       ArtMethod* src_method = src->GetArtMethod();
1929       auto it = native_object_relocations_.find(src_method);
1930       CHECK(it != native_object_relocations_.end())
1931           << "Missing relocation for AbstractMethod.artMethod " << PrettyMethod(src_method);
1932       dest->SetArtMethod(
1933           reinterpret_cast<ArtMethod*>(global_image_begin_ + it->second.offset));
1934     } else if (!klass->IsArrayClass()) {
1935       ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1936       if (klass == class_linker->GetClassRoot(ClassLinker::kJavaLangDexCache)) {
1937         FixupDexCache(down_cast<mirror::DexCache*>(orig), down_cast<mirror::DexCache*>(copy));
1938       } else if (klass->IsClassLoaderClass()) {
1939         mirror::ClassLoader* copy_loader = down_cast<mirror::ClassLoader*>(copy);
1940         // If src is a ClassLoader, set the class table to null so that it gets recreated by the
1941         // ClassLoader.
1942         copy_loader->SetClassTable(nullptr);
1943         // Also set allocator to null to be safe. The allocator is created when we create the class
1944         // table. We also never expect to unload things in the image since they are held live as
1945         // roots.
1946         copy_loader->SetAllocator(nullptr);
1947       }
1948     }
1949     FixupVisitor visitor(this, copy);
1950     orig->VisitReferences(visitor, visitor);
1951   }
1952 }
1953 
1954 
1955 class ImageAddressVisitor {
1956  public:
ImageAddressVisitor(ImageWriter * image_writer)1957   explicit ImageAddressVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {}
1958 
1959   template <typename T>
operator ()(T * ptr) const1960   T* operator()(T* ptr) const SHARED_REQUIRES(Locks::mutator_lock_) {
1961     return image_writer_->GetImageAddress(ptr);
1962   }
1963 
1964  private:
1965   ImageWriter* const image_writer_;
1966 };
1967 
1968 
FixupDexCache(mirror::DexCache * orig_dex_cache,mirror::DexCache * copy_dex_cache)1969 void ImageWriter::FixupDexCache(mirror::DexCache* orig_dex_cache,
1970                                 mirror::DexCache* copy_dex_cache) {
1971   // Though the DexCache array fields are usually treated as native pointers, we set the full
1972   // 64-bit values here, clearing the top 32 bits for 32-bit targets. The zero-extension is
1973   // done by casting to the unsigned type uintptr_t before casting to int64_t, i.e.
1974   //     static_cast<int64_t>(reinterpret_cast<uintptr_t>(image_begin_ + offset))).
1975   GcRoot<mirror::String>* orig_strings = orig_dex_cache->GetStrings();
1976   if (orig_strings != nullptr) {
1977     copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::StringsOffset(),
1978                                                NativeLocationInImage(orig_strings),
1979                                                /*pointer size*/8u);
1980     orig_dex_cache->FixupStrings(NativeCopyLocation(orig_strings, orig_dex_cache),
1981                                  ImageAddressVisitor(this));
1982   }
1983   GcRoot<mirror::Class>* orig_types = orig_dex_cache->GetResolvedTypes();
1984   if (orig_types != nullptr) {
1985     copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedTypesOffset(),
1986                                                NativeLocationInImage(orig_types),
1987                                                /*pointer size*/8u);
1988     orig_dex_cache->FixupResolvedTypes(NativeCopyLocation(orig_types, orig_dex_cache),
1989                                        ImageAddressVisitor(this));
1990   }
1991   ArtMethod** orig_methods = orig_dex_cache->GetResolvedMethods();
1992   if (orig_methods != nullptr) {
1993     copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedMethodsOffset(),
1994                                                NativeLocationInImage(orig_methods),
1995                                                /*pointer size*/8u);
1996     ArtMethod** copy_methods = NativeCopyLocation(orig_methods, orig_dex_cache);
1997     for (size_t i = 0, num = orig_dex_cache->NumResolvedMethods(); i != num; ++i) {
1998       ArtMethod* orig = mirror::DexCache::GetElementPtrSize(orig_methods, i, target_ptr_size_);
1999       // NativeLocationInImage also handles runtime methods since these have relocation info.
2000       ArtMethod* copy = NativeLocationInImage(orig);
2001       mirror::DexCache::SetElementPtrSize(copy_methods, i, copy, target_ptr_size_);
2002     }
2003   }
2004   ArtField** orig_fields = orig_dex_cache->GetResolvedFields();
2005   if (orig_fields != nullptr) {
2006     copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedFieldsOffset(),
2007                                                NativeLocationInImage(orig_fields),
2008                                                /*pointer size*/8u);
2009     ArtField** copy_fields = NativeCopyLocation(orig_fields, orig_dex_cache);
2010     for (size_t i = 0, num = orig_dex_cache->NumResolvedFields(); i != num; ++i) {
2011       ArtField* orig = mirror::DexCache::GetElementPtrSize(orig_fields, i, target_ptr_size_);
2012       ArtField* copy = NativeLocationInImage(orig);
2013       mirror::DexCache::SetElementPtrSize(copy_fields, i, copy, target_ptr_size_);
2014     }
2015   }
2016 
2017   // Remove the DexFile pointers. They will be fixed up when the runtime loads the oat file. Leaving
2018   // compiler pointers in here will make the output non-deterministic.
2019   copy_dex_cache->SetDexFile(nullptr);
2020 }
2021 
GetOatAddress(OatAddress type) const2022 const uint8_t* ImageWriter::GetOatAddress(OatAddress type) const {
2023   DCHECK_LT(type, kOatAddressCount);
2024   // If we are compiling an app image, we need to use the stubs of the boot image.
2025   if (compile_app_image_) {
2026     // Use the current image pointers.
2027     const std::vector<gc::space::ImageSpace*>& image_spaces =
2028         Runtime::Current()->GetHeap()->GetBootImageSpaces();
2029     DCHECK(!image_spaces.empty());
2030     const OatFile* oat_file = image_spaces[0]->GetOatFile();
2031     CHECK(oat_file != nullptr);
2032     const OatHeader& header = oat_file->GetOatHeader();
2033     switch (type) {
2034       // TODO: We could maybe clean this up if we stored them in an array in the oat header.
2035       case kOatAddressQuickGenericJNITrampoline:
2036         return static_cast<const uint8_t*>(header.GetQuickGenericJniTrampoline());
2037       case kOatAddressInterpreterToInterpreterBridge:
2038         return static_cast<const uint8_t*>(header.GetInterpreterToInterpreterBridge());
2039       case kOatAddressInterpreterToCompiledCodeBridge:
2040         return static_cast<const uint8_t*>(header.GetInterpreterToCompiledCodeBridge());
2041       case kOatAddressJNIDlsymLookup:
2042         return static_cast<const uint8_t*>(header.GetJniDlsymLookup());
2043       case kOatAddressQuickIMTConflictTrampoline:
2044         return static_cast<const uint8_t*>(header.GetQuickImtConflictTrampoline());
2045       case kOatAddressQuickResolutionTrampoline:
2046         return static_cast<const uint8_t*>(header.GetQuickResolutionTrampoline());
2047       case kOatAddressQuickToInterpreterBridge:
2048         return static_cast<const uint8_t*>(header.GetQuickToInterpreterBridge());
2049       default:
2050         UNREACHABLE();
2051     }
2052   }
2053   const ImageInfo& primary_image_info = GetImageInfo(0);
2054   return GetOatAddressForOffset(primary_image_info.oat_address_offsets_[type], primary_image_info);
2055 }
2056 
GetQuickCode(ArtMethod * method,const ImageInfo & image_info,bool * quick_is_interpreted)2057 const uint8_t* ImageWriter::GetQuickCode(ArtMethod* method,
2058                                          const ImageInfo& image_info,
2059                                          bool* quick_is_interpreted) {
2060   DCHECK(!method->IsResolutionMethod()) << PrettyMethod(method);
2061   DCHECK_NE(method, Runtime::Current()->GetImtConflictMethod()) << PrettyMethod(method);
2062   DCHECK(!method->IsImtUnimplementedMethod()) << PrettyMethod(method);
2063   DCHECK(method->IsInvokable()) << PrettyMethod(method);
2064   DCHECK(!IsInBootImage(method)) << PrettyMethod(method);
2065 
2066   // Use original code if it exists. Otherwise, set the code pointer to the resolution
2067   // trampoline.
2068 
2069   // Quick entrypoint:
2070   const void* quick_oat_entry_point =
2071       method->GetEntryPointFromQuickCompiledCodePtrSize(target_ptr_size_);
2072   const uint8_t* quick_code;
2073 
2074   if (UNLIKELY(IsInBootImage(method->GetDeclaringClass()))) {
2075     DCHECK(method->IsCopied());
2076     // If the code is not in the oat file corresponding to this image (e.g. default methods)
2077     quick_code = reinterpret_cast<const uint8_t*>(quick_oat_entry_point);
2078   } else {
2079     uint32_t quick_oat_code_offset = PointerToLowMemUInt32(quick_oat_entry_point);
2080     quick_code = GetOatAddressForOffset(quick_oat_code_offset, image_info);
2081   }
2082 
2083   *quick_is_interpreted = false;
2084   if (quick_code != nullptr && (!method->IsStatic() || method->IsConstructor() ||
2085       method->GetDeclaringClass()->IsInitialized())) {
2086     // We have code for a non-static or initialized method, just use the code.
2087   } else if (quick_code == nullptr && method->IsNative() &&
2088       (!method->IsStatic() || method->GetDeclaringClass()->IsInitialized())) {
2089     // Non-static or initialized native method missing compiled code, use generic JNI version.
2090     quick_code = GetOatAddress(kOatAddressQuickGenericJNITrampoline);
2091   } else if (quick_code == nullptr && !method->IsNative()) {
2092     // We don't have code at all for a non-native method, use the interpreter.
2093     quick_code = GetOatAddress(kOatAddressQuickToInterpreterBridge);
2094     *quick_is_interpreted = true;
2095   } else {
2096     CHECK(!method->GetDeclaringClass()->IsInitialized());
2097     // We have code for a static method, but need to go through the resolution stub for class
2098     // initialization.
2099     quick_code = GetOatAddress(kOatAddressQuickResolutionTrampoline);
2100   }
2101   if (!IsInBootOatFile(quick_code)) {
2102     // DCHECK_GE(quick_code, oat_data_begin_);
2103   }
2104   return quick_code;
2105 }
2106 
CopyAndFixupMethod(ArtMethod * orig,ArtMethod * copy,const ImageInfo & image_info)2107 void ImageWriter::CopyAndFixupMethod(ArtMethod* orig,
2108                                      ArtMethod* copy,
2109                                      const ImageInfo& image_info) {
2110   memcpy(copy, orig, ArtMethod::Size(target_ptr_size_));
2111 
2112   copy->SetDeclaringClass(GetImageAddress(orig->GetDeclaringClassUnchecked()));
2113   ArtMethod** orig_resolved_methods = orig->GetDexCacheResolvedMethods(target_ptr_size_);
2114   copy->SetDexCacheResolvedMethods(NativeLocationInImage(orig_resolved_methods), target_ptr_size_);
2115   GcRoot<mirror::Class>* orig_resolved_types = orig->GetDexCacheResolvedTypes(target_ptr_size_);
2116   copy->SetDexCacheResolvedTypes(NativeLocationInImage(orig_resolved_types), target_ptr_size_);
2117 
2118   // OatWriter replaces the code_ with an offset value. Here we re-adjust to a pointer relative to
2119   // oat_begin_
2120 
2121   // The resolution method has a special trampoline to call.
2122   Runtime* runtime = Runtime::Current();
2123   if (orig->IsRuntimeMethod()) {
2124     ImtConflictTable* orig_table = orig->GetImtConflictTable(target_ptr_size_);
2125     if (orig_table != nullptr) {
2126       // Special IMT conflict method, normal IMT conflict method or unimplemented IMT method.
2127       copy->SetEntryPointFromQuickCompiledCodePtrSize(
2128           GetOatAddress(kOatAddressQuickIMTConflictTrampoline), target_ptr_size_);
2129       copy->SetImtConflictTable(NativeLocationInImage(orig_table), target_ptr_size_);
2130     } else if (UNLIKELY(orig == runtime->GetResolutionMethod())) {
2131       copy->SetEntryPointFromQuickCompiledCodePtrSize(
2132           GetOatAddress(kOatAddressQuickResolutionTrampoline), target_ptr_size_);
2133     } else {
2134       bool found_one = false;
2135       for (size_t i = 0; i < static_cast<size_t>(Runtime::kLastCalleeSaveType); ++i) {
2136         auto idx = static_cast<Runtime::CalleeSaveType>(i);
2137         if (runtime->HasCalleeSaveMethod(idx) && runtime->GetCalleeSaveMethod(idx) == orig) {
2138           found_one = true;
2139           break;
2140         }
2141       }
2142       CHECK(found_one) << "Expected to find callee save method but got " << PrettyMethod(orig);
2143       CHECK(copy->IsRuntimeMethod());
2144     }
2145   } else {
2146     // We assume all methods have code. If they don't currently then we set them to the use the
2147     // resolution trampoline. Abstract methods never have code and so we need to make sure their
2148     // use results in an AbstractMethodError. We use the interpreter to achieve this.
2149     if (UNLIKELY(!orig->IsInvokable())) {
2150       copy->SetEntryPointFromQuickCompiledCodePtrSize(
2151           GetOatAddress(kOatAddressQuickToInterpreterBridge), target_ptr_size_);
2152     } else {
2153       bool quick_is_interpreted;
2154       const uint8_t* quick_code = GetQuickCode(orig, image_info, &quick_is_interpreted);
2155       copy->SetEntryPointFromQuickCompiledCodePtrSize(quick_code, target_ptr_size_);
2156 
2157       // JNI entrypoint:
2158       if (orig->IsNative()) {
2159         // The native method's pointer is set to a stub to lookup via dlsym.
2160         // Note this is not the code_ pointer, that is handled above.
2161         copy->SetEntryPointFromJniPtrSize(
2162             GetOatAddress(kOatAddressJNIDlsymLookup), target_ptr_size_);
2163       }
2164     }
2165   }
2166 }
2167 
GetBinSizeSum(ImageWriter::ImageInfo & image_info,ImageWriter::Bin up_to) const2168 size_t ImageWriter::GetBinSizeSum(ImageWriter::ImageInfo& image_info, ImageWriter::Bin up_to) const {
2169   DCHECK_LE(up_to, kBinSize);
2170   return std::accumulate(&image_info.bin_slot_sizes_[0],
2171                          &image_info.bin_slot_sizes_[up_to],
2172                          /*init*/0);
2173 }
2174 
BinSlot(uint32_t lockword)2175 ImageWriter::BinSlot::BinSlot(uint32_t lockword) : lockword_(lockword) {
2176   // These values may need to get updated if more bins are added to the enum Bin
2177   static_assert(kBinBits == 3, "wrong number of bin bits");
2178   static_assert(kBinShift == 27, "wrong number of shift");
2179   static_assert(sizeof(BinSlot) == sizeof(LockWord), "BinSlot/LockWord must have equal sizes");
2180 
2181   DCHECK_LT(GetBin(), kBinSize);
2182   DCHECK_ALIGNED(GetIndex(), kObjectAlignment);
2183 }
2184 
BinSlot(Bin bin,uint32_t index)2185 ImageWriter::BinSlot::BinSlot(Bin bin, uint32_t index)
2186     : BinSlot(index | (static_cast<uint32_t>(bin) << kBinShift)) {
2187   DCHECK_EQ(index, GetIndex());
2188 }
2189 
GetBin() const2190 ImageWriter::Bin ImageWriter::BinSlot::GetBin() const {
2191   return static_cast<Bin>((lockword_ & kBinMask) >> kBinShift);
2192 }
2193 
GetIndex() const2194 uint32_t ImageWriter::BinSlot::GetIndex() const {
2195   return lockword_ & ~kBinMask;
2196 }
2197 
BinTypeForNativeRelocationType(NativeObjectRelocationType type)2198 ImageWriter::Bin ImageWriter::BinTypeForNativeRelocationType(NativeObjectRelocationType type) {
2199   switch (type) {
2200     case kNativeObjectRelocationTypeArtField:
2201     case kNativeObjectRelocationTypeArtFieldArray:
2202       return kBinArtField;
2203     case kNativeObjectRelocationTypeArtMethodClean:
2204     case kNativeObjectRelocationTypeArtMethodArrayClean:
2205       return kBinArtMethodClean;
2206     case kNativeObjectRelocationTypeArtMethodDirty:
2207     case kNativeObjectRelocationTypeArtMethodArrayDirty:
2208       return kBinArtMethodDirty;
2209     case kNativeObjectRelocationTypeDexCacheArray:
2210       return kBinDexCacheArray;
2211     case kNativeObjectRelocationTypeRuntimeMethod:
2212       return kBinRuntimeMethod;
2213     case kNativeObjectRelocationTypeIMTConflictTable:
2214       return kBinIMTConflictTable;
2215   }
2216   UNREACHABLE();
2217 }
2218 
GetOatIndex(mirror::Object * obj) const2219 size_t ImageWriter::GetOatIndex(mirror::Object* obj) const {
2220   if (compile_app_image_) {
2221     return GetDefaultOatIndex();
2222   } else {
2223     mirror::DexCache* dex_cache =
2224         obj->IsDexCache() ? obj->AsDexCache()
2225                           : obj->IsClass() ? obj->AsClass()->GetDexCache()
2226                                            : obj->GetClass()->GetDexCache();
2227     return GetOatIndexForDexCache(dex_cache);
2228   }
2229 }
2230 
GetOatIndexForDexFile(const DexFile * dex_file) const2231 size_t ImageWriter::GetOatIndexForDexFile(const DexFile* dex_file) const {
2232   if (compile_app_image_) {
2233     return GetDefaultOatIndex();
2234   } else {
2235     auto it = dex_file_oat_index_map_.find(dex_file);
2236     DCHECK(it != dex_file_oat_index_map_.end()) << dex_file->GetLocation();
2237     return it->second;
2238   }
2239 }
2240 
GetOatIndexForDexCache(mirror::DexCache * dex_cache) const2241 size_t ImageWriter::GetOatIndexForDexCache(mirror::DexCache* dex_cache) const {
2242   if (dex_cache == nullptr) {
2243     return GetDefaultOatIndex();
2244   } else {
2245     return GetOatIndexForDexFile(dex_cache->GetDexFile());
2246   }
2247 }
2248 
UpdateOatFileLayout(size_t oat_index,size_t oat_loaded_size,size_t oat_data_offset,size_t oat_data_size)2249 void ImageWriter::UpdateOatFileLayout(size_t oat_index,
2250                                       size_t oat_loaded_size,
2251                                       size_t oat_data_offset,
2252                                       size_t oat_data_size) {
2253   const uint8_t* images_end = image_infos_.back().image_begin_ + image_infos_.back().image_size_;
2254   for (const ImageInfo& info : image_infos_) {
2255     DCHECK_LE(info.image_begin_ + info.image_size_, images_end);
2256   }
2257   DCHECK(images_end != nullptr);  // Image space must be ready.
2258 
2259   ImageInfo& cur_image_info = GetImageInfo(oat_index);
2260   cur_image_info.oat_file_begin_ = images_end + cur_image_info.oat_offset_;
2261   cur_image_info.oat_loaded_size_ = oat_loaded_size;
2262   cur_image_info.oat_data_begin_ = cur_image_info.oat_file_begin_ + oat_data_offset;
2263   cur_image_info.oat_size_ = oat_data_size;
2264 
2265   if (compile_app_image_) {
2266     CHECK_EQ(oat_filenames_.size(), 1u) << "App image should have no next image.";
2267     return;
2268   }
2269 
2270   // Update the oat_offset of the next image info.
2271   if (oat_index + 1u != oat_filenames_.size()) {
2272     // There is a following one.
2273     ImageInfo& next_image_info = GetImageInfo(oat_index + 1u);
2274     next_image_info.oat_offset_ = cur_image_info.oat_offset_ + oat_loaded_size;
2275   }
2276 }
2277 
UpdateOatFileHeader(size_t oat_index,const OatHeader & oat_header)2278 void ImageWriter::UpdateOatFileHeader(size_t oat_index, const OatHeader& oat_header) {
2279   ImageInfo& cur_image_info = GetImageInfo(oat_index);
2280   cur_image_info.oat_checksum_ = oat_header.GetChecksum();
2281 
2282   if (oat_index == GetDefaultOatIndex()) {
2283     // Primary oat file, read the trampolines.
2284     cur_image_info.oat_address_offsets_[kOatAddressInterpreterToInterpreterBridge] =
2285         oat_header.GetInterpreterToInterpreterBridgeOffset();
2286     cur_image_info.oat_address_offsets_[kOatAddressInterpreterToCompiledCodeBridge] =
2287         oat_header.GetInterpreterToCompiledCodeBridgeOffset();
2288     cur_image_info.oat_address_offsets_[kOatAddressJNIDlsymLookup] =
2289         oat_header.GetJniDlsymLookupOffset();
2290     cur_image_info.oat_address_offsets_[kOatAddressQuickGenericJNITrampoline] =
2291         oat_header.GetQuickGenericJniTrampolineOffset();
2292     cur_image_info.oat_address_offsets_[kOatAddressQuickIMTConflictTrampoline] =
2293         oat_header.GetQuickImtConflictTrampolineOffset();
2294     cur_image_info.oat_address_offsets_[kOatAddressQuickResolutionTrampoline] =
2295         oat_header.GetQuickResolutionTrampolineOffset();
2296     cur_image_info.oat_address_offsets_[kOatAddressQuickToInterpreterBridge] =
2297         oat_header.GetQuickToInterpreterBridgeOffset();
2298   }
2299 }
2300 
ImageWriter(const CompilerDriver & compiler_driver,uintptr_t image_begin,bool compile_pic,bool compile_app_image,ImageHeader::StorageMode image_storage_mode,const std::vector<const char * > & oat_filenames,const std::unordered_map<const DexFile *,size_t> & dex_file_oat_index_map)2301 ImageWriter::ImageWriter(
2302     const CompilerDriver& compiler_driver,
2303     uintptr_t image_begin,
2304     bool compile_pic,
2305     bool compile_app_image,
2306     ImageHeader::StorageMode image_storage_mode,
2307     const std::vector<const char*>& oat_filenames,
2308     const std::unordered_map<const DexFile*, size_t>& dex_file_oat_index_map)
2309     : compiler_driver_(compiler_driver),
2310       global_image_begin_(reinterpret_cast<uint8_t*>(image_begin)),
2311       image_objects_offset_begin_(0),
2312       compile_pic_(compile_pic),
2313       compile_app_image_(compile_app_image),
2314       target_ptr_size_(InstructionSetPointerSize(compiler_driver_.GetInstructionSet())),
2315       image_infos_(oat_filenames.size()),
2316       dirty_methods_(0u),
2317       clean_methods_(0u),
2318       image_storage_mode_(image_storage_mode),
2319       oat_filenames_(oat_filenames),
2320       dex_file_oat_index_map_(dex_file_oat_index_map) {
2321   CHECK_NE(image_begin, 0U);
2322   std::fill_n(image_methods_, arraysize(image_methods_), nullptr);
2323   CHECK_EQ(compile_app_image, !Runtime::Current()->GetHeap()->GetBootImageSpaces().empty())
2324       << "Compiling a boot image should occur iff there are no boot image spaces loaded";
2325 }
2326 
ImageInfo()2327 ImageWriter::ImageInfo::ImageInfo()
2328     : intern_table_(new InternTable),
2329       class_table_(new ClassTable) {}
2330 
2331 }  // namespace art
2332