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 <lz4.h>
20 #include <lz4hc.h>
21 #include <sys/stat.h>
22 #include <zlib.h>
23 
24 #include <charconv>
25 #include <memory>
26 #include <numeric>
27 #include <vector>
28 
29 #include "android-base/strings.h"
30 #include "art_field-inl.h"
31 #include "art_method-inl.h"
32 #include "base/callee_save_type.h"
33 #include "base/globals.h"
34 #include "base/logging.h"  // For VLOG.
35 #include "base/pointer_size.h"
36 #include "base/stl_util.h"
37 #include "base/unix_file/fd_file.h"
38 #include "class_linker-inl.h"
39 #include "class_root-inl.h"
40 #include "dex/dex_file-inl.h"
41 #include "dex/dex_file_types.h"
42 #include "driver/compiler_options.h"
43 #include "elf/elf_utils.h"
44 #include "entrypoints/entrypoint_utils-inl.h"
45 #include "gc/accounting/card_table-inl.h"
46 #include "gc/accounting/heap_bitmap.h"
47 #include "gc/accounting/space_bitmap-inl.h"
48 #include "gc/collector/concurrent_copying.h"
49 #include "gc/heap-visit-objects-inl.h"
50 #include "gc/heap.h"
51 #include "gc/space/large_object_space.h"
52 #include "gc/space/region_space.h"
53 #include "gc/space/space-inl.h"
54 #include "gc/verification.h"
55 #include "handle_scope-inl.h"
56 #include "imt_conflict_table.h"
57 #include "indirect_reference_table-inl.h"
58 #include "intern_table-inl.h"
59 #include "jni/java_vm_ext-inl.h"
60 #include "jni/jni_internal.h"
61 #include "linear_alloc.h"
62 #include "lock_word.h"
63 #include "mirror/array-inl.h"
64 #include "mirror/class-inl.h"
65 #include "mirror/class_ext-inl.h"
66 #include "mirror/class_loader.h"
67 #include "mirror/dex_cache-inl.h"
68 #include "mirror/dex_cache.h"
69 #include "mirror/executable.h"
70 #include "mirror/method.h"
71 #include "mirror/object-inl.h"
72 #include "mirror/object-refvisitor-inl.h"
73 #include "mirror/object_array-alloc-inl.h"
74 #include "mirror/object_array-inl.h"
75 #include "mirror/string-inl.h"
76 #include "mirror/var_handle.h"
77 #include "nterp_helpers-inl.h"
78 #include "nterp_helpers.h"
79 #include "oat/elf_file.h"
80 #include "oat/image-inl.h"
81 #include "oat/oat.h"
82 #include "oat/oat_file.h"
83 #include "oat/oat_file_manager.h"
84 #include "optimizing/intrinsic_objects.h"
85 #include "runtime.h"
86 #include "scoped_thread_state_change-inl.h"
87 #include "subtype_check.h"
88 #include "thread-current-inl.h"  // For AssertOnly1Thread.
89 #include "thread_list.h"         // For AssertOnly1Thread.
90 #include "well_known_classes-inl.h"
91 
92 using ::art::mirror::Class;
93 using ::art::mirror::DexCache;
94 using ::art::mirror::Object;
95 using ::art::mirror::ObjectArray;
96 using ::art::mirror::String;
97 
98 namespace art {
99 namespace linker {
100 
101 // The actual value of `kImageClassTableMinLoadFactor` is irrelevant because image class tables
102 // are never resized, but we still need to pass a reasonable value to the constructor.
103 constexpr double kImageClassTableMinLoadFactor = 0.5;
104 // We use `kImageClassTableMaxLoadFactor` to determine the buffer size for image class tables
105 // to make them full. We never insert additional elements to them, so we do not want to waste
106 // extra memory. And unlike runtime class tables, we do not want this to depend on runtime
107 // properties (see `Runtime::GetHashTableMaxLoadFactor()` checking for low memory mode).
108 constexpr double kImageClassTableMaxLoadFactor = 0.6;
109 
110 // The actual value of `kImageInternTableMinLoadFactor` is irrelevant because image intern tables
111 // are never resized, but we still need to pass a reasonable value to the constructor.
112 constexpr double kImageInternTableMinLoadFactor = 0.5;
113 // We use `kImageInternTableMaxLoadFactor` to determine the buffer size for image intern tables
114 // to make them full. We never insert additional elements to them, so we do not want to waste
115 // extra memory. And unlike runtime intern tables, we do not want this to depend on runtime
116 // properties (see `Runtime::GetHashTableMaxLoadFactor()` checking for low memory mode).
117 constexpr double kImageInternTableMaxLoadFactor = 0.6;
118 
119 // Separate objects into multiple bins to optimize dirty memory use.
120 static constexpr bool kBinObjects = true;
121 
122 namespace {
123 
124 // Dirty object data from dirty-image-objects.
125 struct DirtyEntry {
126   // Reference field name and type.
127   struct RefInfo {
128     std::string_view name;
129     std::string_view type;
130   };
131 
132   std::string_view class_descriptor;
133   // A "path" from class object to the dirty object. If empty -- the class itself is dirty.
134   std::vector<RefInfo> reference_path;
135   uint32_t sort_key = std::numeric_limits<uint32_t>::max();
136 };
137 
138 // Parse dirty-image-object line of the format:
139 // <class_descriptor>[.<reference_field_name>:<reference_field_type>]* [<sort_key>]
ParseDirtyEntry(std::string_view entry_str)140 std::optional<DirtyEntry> ParseDirtyEntry(std::string_view entry_str) {
141   DirtyEntry entry;
142   std::vector<std::string_view> tokens;
143   Split(entry_str, ' ', &tokens);
144   if (tokens.empty()) {
145     // entry_str is empty.
146     return std::nullopt;
147   }
148 
149   std::string_view path_to_root = tokens[0];
150   // Parse sort_key if present, otherwise it will be uint32::max by default.
151   if (tokens.size() > 1) {
152     std::from_chars_result res =
153         std::from_chars(tokens[1].data(), tokens[1].data() + tokens[1].size(), entry.sort_key);
154     if (res.ec != std::errc()) {
155       LOG(WARNING) << "Failed to parse dirty object sort key: \"" << entry_str << "\"";
156       return std::nullopt;
157     }
158   }
159 
160   std::vector<std::string_view> path_components;
161   Split(path_to_root, '.', &path_components);
162   if (path_components.empty()) {
163     return std::nullopt;
164   }
165   entry.class_descriptor = path_components[0];
166   for (size_t i = 1; i < path_components.size(); ++i) {
167     std::string_view name_and_type = path_components[i];
168     std::vector<std::string_view> ref_data;
169     Split(name_and_type, ':', &ref_data);
170     if (ref_data.size() != 2) {
171       LOG(WARNING) << "Failed to parse dirty object reference field: \"" << entry_str << "\"";
172       return std::nullopt;
173     }
174 
175     std::string_view field_name = ref_data[0];
176     std::string_view field_type = ref_data[1];
177     entry.reference_path.push_back({field_name, field_type});
178   }
179 
180   return entry;
181 }
182 
183 // Calls VisitFunc for each non-null (reference)Object/ArtField pair.
184 // Doesn't work with ObjectArray instances, because array elements don't have ArtField.
185 class ReferenceFieldVisitor {
186  public:
187   using VisitFunc = std::function<void(mirror::Object&, ArtField&)>;
188 
ReferenceFieldVisitor(VisitFunc visit_func)189   explicit ReferenceFieldVisitor(VisitFunc visit_func) : visit_func_(std::move(visit_func)) {}
190 
operator ()(ObjPtr<mirror::Object> obj,MemberOffset offset,bool is_static) const191   void operator()(ObjPtr<mirror::Object> obj, MemberOffset offset, bool is_static) const
192       REQUIRES_SHARED(Locks::mutator_lock_) {
193     CHECK(!obj->IsObjectArray());
194     mirror::Object* field_obj =
195         obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(offset);
196     // Skip fields that contain null.
197     if (field_obj == nullptr) {
198       return;
199     }
200     // Skip self references.
201     if (field_obj == obj.Ptr()) {
202       return;
203     }
204 
205     ArtField* field = nullptr;
206     // Don't use Object::FindFieldByOffset, because it can't find instance fields in classes.
207     // field = obj->FindFieldByOffset(offset);
208     if (is_static) {
209       CHECK(obj->IsClass());
210       field = ArtField::FindStaticFieldWithOffset(obj->AsClass(), offset.Uint32Value());
211     } else {
212       field = ArtField::
213           FindInstanceFieldWithOffset</*kExactOffset*/ true, kVerifyNone, kWithoutReadBarrier>(
214               obj->GetClass<kVerifyNone, kWithoutReadBarrier>(), offset.Uint32Value());
215     }
216     DCHECK(field != nullptr);
217     visit_func_(*field_obj, *field);
218   }
219 
operator ()(ObjPtr<mirror::Class> klass,ObjPtr<mirror::Reference> ref) const220   void operator()([[maybe_unused]] ObjPtr<mirror::Class> klass, ObjPtr<mirror::Reference> ref) const
221       REQUIRES_SHARED(Locks::mutator_lock_) {
222     operator()(ref, mirror::Reference::ReferentOffset(), /* is_static */ false);
223   }
224 
VisitRootIfNonNull(mirror::CompressedReference<mirror::Object> * root) const225   void VisitRootIfNonNull([[maybe_unused]] mirror::CompressedReference<mirror::Object>* root) const
226       REQUIRES_SHARED(Locks::mutator_lock_) {
227     DCHECK(false) << "ReferenceFieldVisitor shouldn't visit roots";
228   }
229 
VisitRoot(mirror::CompressedReference<mirror::Object> * root) const230   void VisitRoot([[maybe_unused]] mirror::CompressedReference<mirror::Object>* root) const
231       REQUIRES_SHARED(Locks::mutator_lock_) {
232     DCHECK(false) << "ReferenceFieldVisitor shouldn't visit roots";
233   }
234 
235  private:
236   VisitFunc visit_func_;
237 };
238 
239 // Finds Class objects for descriptors of dirty entries.
240 // Map keys are string_views, that point to strings from `dirty_image_objects`.
241 // If there is no Class for a descriptor, the result map will have an entry with nullptr value.
FindClassesByDescriptor(const std::vector<std::string> & dirty_image_objects)242 static HashMap<std::string_view, mirror::Object*> FindClassesByDescriptor(
243     const std::vector<std::string>& dirty_image_objects) REQUIRES_SHARED(Locks::mutator_lock_) {
244   HashMap<std::string_view, mirror::Object*> descriptor_to_class;
245   // Collect class descriptors that are used in dirty-image-objects.
246   for (const std::string& entry : dirty_image_objects) {
247     auto it = std::find_if(entry.begin(), entry.end(), [](char c) { return c == '.' || c == ' '; });
248     size_t descriptor_len = std::distance(entry.begin(), it);
249 
250     std::string_view descriptor = std::string_view(entry).substr(0, descriptor_len);
251     descriptor_to_class.insert(std::make_pair(descriptor, nullptr));
252   }
253 
254   // Find Class objects for collected descriptors.
255   auto visitor = [&](Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
256     DCHECK(obj != nullptr);
257     if (obj->IsClass()) {
258       std::string temp;
259       const char* descriptor = obj->AsClass()->GetDescriptor(&temp);
260       auto it = descriptor_to_class.find(descriptor);
261       if (it != descriptor_to_class.end()) {
262         it->second = obj;
263       }
264     }
265   };
266   Runtime::Current()->GetHeap()->VisitObjects(visitor);
267 
268   return descriptor_to_class;
269 }
270 
271 // Get all objects that match dirty_entries by path from class.
272 // Map values are sort_keys from DirtyEntry.
MatchDirtyObjectPaths(const std::vector<std::string> & dirty_image_objects)273 HashMap<mirror::Object*, uint32_t> MatchDirtyObjectPaths(
274     const std::vector<std::string>& dirty_image_objects) REQUIRES_SHARED(Locks::mutator_lock_) {
275   auto get_array_element = [](mirror::Object* cur_obj, const DirtyEntry::RefInfo& ref_info)
276                                REQUIRES_SHARED(Locks::mutator_lock_) -> mirror::Object* {
277     if (!cur_obj->IsObjectArray()) {
278       return nullptr;
279     }
280     int32_t idx = 0;
281     std::from_chars_result idx_parse_res =
282         std::from_chars(ref_info.name.data(), ref_info.name.data() + ref_info.name.size(), idx);
283     if (idx_parse_res.ec != std::errc()) {
284       return nullptr;
285     }
286 
287     ObjPtr<ObjectArray<mirror::Object>> array = cur_obj->AsObjectArray<mirror::Object>();
288     if (idx < 0 || idx >= array->GetLength()) {
289       return nullptr;
290     }
291 
292     ObjPtr<mirror::Object> next_obj =
293         array->GetWithoutChecks<kVerifyNone, kWithoutReadBarrier>(idx);
294     if (next_obj == nullptr) {
295       return nullptr;
296     }
297 
298     std::string temp;
299     if (next_obj->GetClass<kVerifyNone, kWithoutReadBarrier>()->GetDescriptor(&temp) !=
300         ref_info.type) {
301       return nullptr;
302     }
303     return next_obj.Ptr();
304   };
305   auto get_object_field =
306       [](mirror::Object* cur_obj, const DirtyEntry::RefInfo& ref_info)
307           REQUIRES_SHARED(Locks::mutator_lock_) {
308             mirror::Object* next_obj = nullptr;
309             ReferenceFieldVisitor::VisitFunc visit_func =
310                 [&](mirror::Object& ref_obj, ArtField& ref_field)
311                     REQUIRES_SHARED(Locks::mutator_lock_) {
312                       if (ref_field.GetName() == ref_info.name &&
313                           ref_field.GetTypeDescriptor() == ref_info.type) {
314                         next_obj = &ref_obj;
315                       }
316                     };
317             ReferenceFieldVisitor visitor(visit_func);
318             cur_obj->VisitReferences</*kVisitNativeRoots=*/false, kVerifyNone, kWithoutReadBarrier>(
319                 visitor, visitor);
320 
321             return next_obj;
322           };
323 
324   HashMap<mirror::Object*, uint32_t> dirty_objects;
325   const HashMap<std::string_view, mirror::Object*> descriptor_to_class =
326       FindClassesByDescriptor(dirty_image_objects);
327   for (const std::string& entry_str : dirty_image_objects) {
328     const std::optional<DirtyEntry> entry = ParseDirtyEntry(entry_str);
329     if (entry == std::nullopt) {
330       continue;
331     }
332 
333     auto root_it = descriptor_to_class.find(entry->class_descriptor);
334     if (root_it == descriptor_to_class.end() || root_it->second == nullptr) {
335       LOG(WARNING) << "Class not found: \"" << entry->class_descriptor << "\"";
336       continue;
337     }
338 
339     mirror::Object* cur_obj = root_it->second;
340     for (const DirtyEntry::RefInfo& ref_info : entry->reference_path) {
341       if (std::all_of(
342               ref_info.name.begin(), ref_info.name.end(), [](char c) { return std::isdigit(c); })) {
343         cur_obj = get_array_element(cur_obj, ref_info);
344       } else {
345         cur_obj = get_object_field(cur_obj, ref_info);
346       }
347       if (cur_obj == nullptr) {
348         LOG(WARNING) << ART_FORMAT("Failed to find field \"{}:{}\", entry: \"{}\"",
349                                    ref_info.name,
350                                    ref_info.type,
351                                    entry_str);
352         break;
353       }
354     }
355     if (cur_obj == nullptr) {
356       continue;
357     }
358 
359     dirty_objects.insert(std::make_pair(cur_obj, entry->sort_key));
360   }
361 
362   return dirty_objects;
363 }
364 
365 }  // namespace
366 
AllocateBootImageLiveObjects(Thread * self,Runtime * runtime)367 static ObjPtr<mirror::ObjectArray<mirror::Object>> AllocateBootImageLiveObjects(
368     Thread* self, Runtime* runtime) REQUIRES_SHARED(Locks::mutator_lock_) {
369   ClassLinker* class_linker = runtime->GetClassLinker();
370   // The objects used for intrinsics must remain live even if references
371   // to them are removed using reflection. Image roots are not accessible through reflection,
372   // so the array we construct here shall keep them alive.
373   StackHandleScope<1> hs(self);
374   size_t live_objects_size =
375       enum_cast<size_t>(ImageHeader::kIntrinsicObjectsStart) +
376       IntrinsicObjects::GetNumberOfIntrinsicObjects();
377   ObjPtr<mirror::ObjectArray<mirror::Object>> live_objects =
378       mirror::ObjectArray<mirror::Object>::Alloc(
379           self, GetClassRoot<mirror::ObjectArray<mirror::Object>>(class_linker), live_objects_size);
380   if (live_objects == nullptr) {
381     return nullptr;
382   }
383   int32_t index = 0u;
384   auto set_entry = [&](ImageHeader::BootImageLiveObjects entry,
385                        ObjPtr<mirror::Object> value) REQUIRES_SHARED(Locks::mutator_lock_) {
386     DCHECK_EQ(index, enum_cast<int32_t>(entry));
387     live_objects->Set</*kTransacrionActive=*/ false>(index, value);
388     ++index;
389   };
390   set_entry(ImageHeader::kOomeWhenThrowingException,
391             runtime->GetPreAllocatedOutOfMemoryErrorWhenThrowingException());
392   set_entry(ImageHeader::kOomeWhenThrowingOome,
393             runtime->GetPreAllocatedOutOfMemoryErrorWhenThrowingOOME());
394   set_entry(ImageHeader::kOomeWhenHandlingStackOverflow,
395             runtime->GetPreAllocatedOutOfMemoryErrorWhenHandlingStackOverflow());
396   set_entry(ImageHeader::kNoClassDefFoundError, runtime->GetPreAllocatedNoClassDefFoundError());
397   set_entry(ImageHeader::kClearedJniWeakSentinel, runtime->GetSentinel().Read());
398 
399   DCHECK_EQ(index, enum_cast<int32_t>(ImageHeader::kIntrinsicObjectsStart));
400   IntrinsicObjects::FillIntrinsicObjects(live_objects, index);
401   return live_objects;
402 }
403 
404 template <typename MirrorType>
DecodeGlobalWithoutRB(JavaVMExt * vm,jobject obj)405 ObjPtr<MirrorType> ImageWriter::DecodeGlobalWithoutRB(JavaVMExt* vm, jobject obj) {
406   DCHECK_EQ(IndirectReferenceTable::GetIndirectRefKind(obj), kGlobal);
407   return ObjPtr<MirrorType>::DownCast(vm->globals_.Get<kWithoutReadBarrier>(obj));
408 }
409 
410 template <typename MirrorType>
DecodeWeakGlobalWithoutRB(JavaVMExt * vm,Thread * self,jobject obj)411 ObjPtr<MirrorType> ImageWriter::DecodeWeakGlobalWithoutRB(
412     JavaVMExt* vm, Thread* self, jobject obj) {
413   DCHECK_EQ(IndirectReferenceTable::GetIndirectRefKind(obj), kWeakGlobal);
414   DCHECK(vm->MayAccessWeakGlobals(self));
415   return ObjPtr<MirrorType>::DownCast(vm->weak_globals_.Get<kWithoutReadBarrier>(obj));
416 }
417 
GetAppClassLoader() const418 ObjPtr<mirror::ClassLoader> ImageWriter::GetAppClassLoader() const
419     REQUIRES_SHARED(Locks::mutator_lock_) {
420   return compiler_options_.IsAppImage()
421       ? ObjPtr<mirror::ClassLoader>::DownCast(Thread::Current()->DecodeJObject(app_class_loader_))
422       : nullptr;
423 }
424 
IsImageDexCache(ObjPtr<mirror::DexCache> dex_cache) const425 bool ImageWriter::IsImageDexCache(ObjPtr<mirror::DexCache> dex_cache) const {
426   // For boot image, we keep all dex caches.
427   if (compiler_options_.IsBootImage()) {
428     return true;
429   }
430   // Dex caches already in the boot image do not belong to the image being written.
431   if (IsInBootImage(dex_cache.Ptr())) {
432     return false;
433   }
434   // Dex caches for the boot class path components that are not part of the boot image
435   // cannot be garbage collected in PrepareImageAddressSpace() but we do not want to
436   // include them in the app image.
437   if (!ContainsElement(compiler_options_.GetDexFilesForOatFile(), dex_cache->GetDexFile())) {
438     return false;
439   }
440   return true;
441 }
442 
ClearDexFileCookies()443 static void ClearDexFileCookies() REQUIRES_SHARED(Locks::mutator_lock_) {
444   auto visitor = [](Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
445     DCHECK(obj != nullptr);
446     Class* klass = obj->GetClass();
447     if (klass == WellKnownClasses::dalvik_system_DexFile) {
448       ArtField* field = WellKnownClasses::dalvik_system_DexFile_cookie;
449       // Null out the cookie to enable determinism. b/34090128
450       field->SetObject</*kTransactionActive*/false>(obj, nullptr);
451     }
452   };
453   Runtime::Current()->GetHeap()->VisitObjects(visitor);
454 }
455 
PrepareImageAddressSpace(TimingLogger * timings)456 bool ImageWriter::PrepareImageAddressSpace(TimingLogger* timings) {
457   Thread* const self = Thread::Current();
458 
459   gc::Heap* const heap = Runtime::Current()->GetHeap();
460   {
461     ScopedObjectAccess soa(self);
462     {
463       TimingLogger::ScopedTiming t("PruneNonImageClasses", timings);
464       PruneNonImageClasses();  // Remove junk
465     }
466 
467     if (UNLIKELY(!CreateImageRoots())) {
468       self->AssertPendingOOMException();
469       self->ClearException();
470       return false;
471     }
472 
473     if (compiler_options_.IsAppImage()) {
474       TimingLogger::ScopedTiming t("ClearDexFileCookies", timings);
475       // Clear dex file cookies for app images to enable app image determinism. This is required
476       // since the cookie field contains long pointers to DexFiles which are not deterministic.
477       // b/34090128
478       ClearDexFileCookies();
479     }
480   }
481 
482   {
483     TimingLogger::ScopedTiming t("CollectGarbage", timings);
484     heap->CollectGarbage(/* clear_soft_references */ false);  // Remove garbage.
485   }
486 
487   if (kIsDebugBuild) {
488     ScopedObjectAccess soa(self);
489     CheckNonImageClassesRemoved();
490   }
491 
492   // From this point on, there should be no GC, so we should not use unnecessary read barriers.
493   ScopedDebugDisallowReadBarriers sddrb(self);
494 
495   {
496     // All remaining weak interns are referenced. Promote them to strong interns. Whether a
497     // string was strongly or weakly interned, we shall make it strongly interned in the image.
498     TimingLogger::ScopedTiming t("PromoteInterns", timings);
499     ScopedObjectAccess soa(self);
500     PromoteWeakInternsToStrong(self);
501   }
502 
503   {
504     TimingLogger::ScopedTiming t("CalculateNewObjectOffsets", timings);
505     ScopedObjectAccess soa(self);
506     CalculateNewObjectOffsets();
507   }
508 
509   // This needs to happen after CalculateNewObjectOffsets since it relies on intern_table_bytes_ and
510   // bin size sums being calculated.
511   TimingLogger::ScopedTiming t("AllocMemory", timings);
512   return AllocMemory();
513 }
514 
CopyMetadata()515 void ImageWriter::CopyMetadata() {
516   DCHECK(compiler_options_.IsAppImage());
517   CHECK_EQ(image_infos_.size(), 1u);
518 
519   const ImageInfo& image_info = image_infos_.back();
520   dchecked_vector<ImageSection> image_sections = image_info.CreateImageSections().second;
521 
522   auto* sfo_section_base = reinterpret_cast<AppImageReferenceOffsetInfo*>(
523       image_info.image_.Begin() +
524       image_sections[ImageHeader::kSectionStringReferenceOffsets].Offset());
525 
526   std::copy(image_info.string_reference_offsets_.begin(),
527             image_info.string_reference_offsets_.end(),
528             sfo_section_base);
529 }
530 
531 // NO_THREAD_SAFETY_ANALYSIS: Avoid locking the `Locks::intern_table_lock_` while single-threaded.
IsStronglyInternedString(ObjPtr<mirror::String> str)532 bool ImageWriter::IsStronglyInternedString(ObjPtr<mirror::String> str) NO_THREAD_SAFETY_ANALYSIS {
533   uint32_t hash = static_cast<uint32_t>(str->GetStoredHashCode());
534   if (hash == 0u && str->ComputeHashCode() != 0) {
535     // A string with uninitialized hash code cannot be interned.
536     return false;
537   }
538   InternTable* intern_table = Runtime::Current()->GetInternTable();
539   for (InternTable::Table::InternalTable& table : intern_table->strong_interns_.tables_) {
540     auto it = table.set_.FindWithHash(GcRoot<mirror::String>(str), hash);
541     if (it != table.set_.end()) {
542       return it->Read<kWithoutReadBarrier>() == str;
543     }
544   }
545   return false;
546 }
547 
IsInternedAppImageStringReference(ObjPtr<mirror::Object> referred_obj) const548 bool ImageWriter::IsInternedAppImageStringReference(ObjPtr<mirror::Object> referred_obj) const {
549   return referred_obj != nullptr &&
550          !IsInBootImage(referred_obj.Ptr()) &&
551          referred_obj->IsString() &&
552          IsStronglyInternedString(referred_obj->AsString());
553 }
554 
Write(int image_fd,const std::vector<std::string> & image_filenames,size_t component_count)555 bool ImageWriter::Write(int image_fd,
556                         const std::vector<std::string>& image_filenames,
557                         size_t component_count) {
558   // If image_fd or oat_fd are not File::kInvalidFd then we may have empty strings in
559   // image_filenames or oat_filenames.
560   CHECK(!image_filenames.empty());
561   if (image_fd != File::kInvalidFd) {
562     CHECK_EQ(image_filenames.size(), 1u);
563   }
564   DCHECK(!oat_filenames_.empty());
565   CHECK_EQ(image_filenames.size(), oat_filenames_.size());
566 
567   Thread* const self = Thread::Current();
568   ScopedDebugDisallowReadBarriers sddrb(self);
569   {
570     ScopedObjectAccess soa(self);
571     for (size_t i = 0; i < oat_filenames_.size(); ++i) {
572       CreateHeader(i, component_count);
573       CopyAndFixupNativeData(i);
574       CopyAndFixupJniStubMethods(i);
575     }
576   }
577 
578   {
579     // TODO: heap validation can't handle these fix up passes.
580     ScopedObjectAccess soa(self);
581     Runtime::Current()->GetHeap()->DisableObjectValidation();
582     CopyAndFixupObjects();
583   }
584 
585   if (compiler_options_.IsAppImage()) {
586     CopyMetadata();
587   }
588 
589   // Primary image header shall be written last for two reasons. First, this ensures
590   // that we shall not end up with a valid primary image and invalid secondary image.
591   // Second, its checksum shall include the checksums of the secondary images (XORed).
592   // This way only the primary image checksum needs to be checked to determine whether
593   // any of the images or oat files are out of date. (Oat file checksums are included
594   // in the image checksum calculation.)
595   ImageHeader* primary_header = reinterpret_cast<ImageHeader*>(image_infos_[0].image_.Begin());
596   ImageFileGuard primary_image_file;
597   for (size_t i = 0; i < image_filenames.size(); ++i) {
598     const std::string& image_filename = image_filenames[i];
599     ImageInfo& image_info = GetImageInfo(i);
600     ImageFileGuard image_file;
601     if (image_fd != File::kInvalidFd) {
602       // Ignore image_filename, it is supplied only for better diagnostic.
603       image_file.reset(new File(image_fd, unix_file::kCheckSafeUsage));
604       // Empty the file in case it already exists.
605       if (image_file != nullptr) {
606         TEMP_FAILURE_RETRY(image_file->SetLength(0));
607         TEMP_FAILURE_RETRY(image_file->Flush());
608       }
609     } else {
610       image_file.reset(OS::CreateEmptyFile(image_filename.c_str()));
611     }
612 
613     if (image_file == nullptr) {
614       LOG(ERROR) << "Failed to open image file " << image_filename;
615       return false;
616     }
617 
618     // Make file world readable if we have created it, i.e. when not passed as file descriptor.
619     if (image_fd == -1 && !compiler_options_.IsAppImage() && fchmod(image_file->Fd(), 0644) != 0) {
620       PLOG(ERROR) << "Failed to make image file world readable: " << image_filename;
621       return false;
622     }
623 
624     // Image data size excludes the bitmap and the header.
625     ImageHeader* const image_header = reinterpret_cast<ImageHeader*>(image_info.image_.Begin());
626     std::string error_msg;
627     if (!image_header->WriteData(image_file,
628                                  image_info.image_.Begin(),
629                                  reinterpret_cast<const uint8_t*>(image_info.image_bitmap_.Begin()),
630                                  image_storage_mode_,
631                                  compiler_options_.MaxImageBlockSize(),
632                                  /* update_checksum= */ true,
633                                  &error_msg)) {
634       LOG(ERROR) << error_msg;
635       return false;
636     }
637 
638     // Write header last in case the compiler gets killed in the middle of image writing.
639     // We do not want to have a corrupted image with a valid header.
640     // Delay the writing of the primary image header until after writing secondary images.
641     if (i == 0u) {
642       primary_image_file = std::move(image_file);
643     } else {
644       if (!image_file.WriteHeaderAndClose(image_filename, image_header, &error_msg)) {
645         LOG(ERROR) << error_msg;
646         return false;
647       }
648       // Update the primary image checksum with the secondary image checksum.
649       primary_header->SetImageChecksum(
650           primary_header->GetImageChecksum() ^ image_header->GetImageChecksum());
651     }
652   }
653   DCHECK(primary_image_file != nullptr);
654   std::string error_msg;
655   if (!primary_image_file.WriteHeaderAndClose(image_filenames[0], primary_header, &error_msg)) {
656     LOG(ERROR) << error_msg;
657     return false;
658   }
659 
660   return true;
661 }
662 
GetImageOffset(mirror::Object * object,size_t oat_index) const663 size_t ImageWriter::GetImageOffset(mirror::Object* object, size_t oat_index) const {
664   BinSlot bin_slot = GetImageBinSlot(object, oat_index);
665   const ImageInfo& image_info = GetImageInfo(oat_index);
666   size_t offset = image_info.GetBinSlotOffset(bin_slot.GetBin()) + bin_slot.GetOffset();
667   DCHECK_LT(offset, image_info.image_end_);
668   return offset;
669 }
670 
SetImageBinSlot(mirror::Object * object,BinSlot bin_slot)671 void ImageWriter::SetImageBinSlot(mirror::Object* object, BinSlot bin_slot) {
672   DCHECK(object != nullptr);
673   DCHECK(!IsImageBinSlotAssigned(object));
674 
675   // Before we stomp over the lock word, save the hash code for later.
676   LockWord lw(object->GetLockWord(false));
677   switch (lw.GetState()) {
678     case LockWord::kFatLocked:
679       FALLTHROUGH_INTENDED;
680     case LockWord::kThinLocked: {
681       std::ostringstream oss;
682       bool thin = (lw.GetState() == LockWord::kThinLocked);
683       oss << (thin ? "Thin" : "Fat")
684           << " locked object " << object << "(" << object->PrettyTypeOf()
685           << ") found during object copy";
686       if (thin) {
687         oss << ". Lock owner:" << lw.ThinLockOwner();
688       }
689       LOG(FATAL) << oss.str();
690       UNREACHABLE();
691     }
692     case LockWord::kUnlocked:
693       // No hash, don't need to save it.
694       break;
695     case LockWord::kHashCode:
696       DCHECK(saved_hashcode_map_.find(object) == saved_hashcode_map_.end());
697       saved_hashcode_map_.insert(std::make_pair(object, lw.GetHashCode()));
698       break;
699     default:
700       LOG(FATAL) << "UNREACHABLE";
701       UNREACHABLE();
702   }
703   object->SetLockWord(LockWord::FromForwardingAddress(bin_slot.Uint32Value()),
704                       /*as_volatile=*/ false);
705   DCHECK_EQ(object->GetLockWord(false).ReadBarrierState(), 0u);
706   DCHECK(IsImageBinSlotAssigned(object));
707 }
708 
GetImageBin(mirror::Object * object)709 ImageWriter::Bin ImageWriter::GetImageBin(mirror::Object* object) {
710   DCHECK(object != nullptr);
711 
712   // The magic happens here. We segregate objects into different bins based
713   // on how likely they are to get dirty at runtime.
714   //
715   // Likely-to-dirty objects get packed together into the same bin so that
716   // at runtime their page dirtiness ratio (how many dirty objects a page has) is
717   // maximized.
718   //
719   // This means more pages will stay either clean or shared dirty (with zygote) and
720   // the app will use less of its own (private) memory.
721   Bin bin = Bin::kRegular;
722 
723   if (kBinObjects) {
724     //
725     // Changing the bin of an object is purely a memory-use tuning.
726     // It has no change on runtime correctness.
727     //
728     // Memory analysis has determined that the following types of objects get dirtied
729     // the most:
730     //
731     // * Class'es which are verified [their clinit runs only at runtime]
732     //   - classes in general [because their static fields get overwritten]
733     //   - initialized classes with all-final statics are unlikely to be ever dirty,
734     //     so bin them separately
735     // * Art Methods that are:
736     //   - native [their native entry point is not looked up until runtime]
737     //   - have declaring classes that aren't initialized
738     //            [their interpreter/quick entry points are trampolines until the class
739     //             becomes initialized]
740     //
741     // We also assume the following objects get dirtied either never or extremely rarely:
742     //  * Strings (they are immutable)
743     //  * Art methods that aren't native and have initialized declared classes
744     //
745     // We assume that "regular" bin objects are highly unlikely to become dirtied,
746     // so packing them together will not result in a noticeably tighter dirty-to-clean ratio.
747     //
748     ObjPtr<mirror::Class> klass = object->GetClass<kVerifyNone, kWithoutReadBarrier>();
749     if (klass->IsStringClass<kVerifyNone>()) {
750       // Assign strings to their bin before checking dirty objects, because
751       // string intern processing expects strings to be in Bin::kString.
752       bin = Bin::kString;  // Strings are almost always immutable (except for object header).
753     } else if (dirty_objects_.find(object) != dirty_objects_.end()) {
754       bin = Bin::kKnownDirty;
755     } else if (klass->IsClassClass()) {
756       bin = Bin::kClassVerified;
757       ObjPtr<mirror::Class> as_klass = object->AsClass<kVerifyNone>();
758       if (as_klass->IsVisiblyInitialized<kVerifyNone>()) {
759         bin = Bin::kClassInitialized;
760 
761         // If the class's static fields are all final, put it into a separate bin
762         // since it's very likely it will stay clean.
763         uint32_t num_static_fields = as_klass->NumStaticFields();
764         if (num_static_fields == 0) {
765           bin = Bin::kClassInitializedFinalStatics;
766         } else {
767           // Maybe all the statics are final?
768           bool all_final = true;
769           for (uint32_t i = 0; i < num_static_fields; ++i) {
770             ArtField* field = as_klass->GetStaticField(i);
771             if (!field->IsFinal()) {
772               all_final = false;
773               break;
774             }
775           }
776 
777           if (all_final) {
778             bin = Bin::kClassInitializedFinalStatics;
779           }
780         }
781       }
782     } else if (!klass->HasSuperClass()) {
783       // Only `j.l.Object` and primitive classes lack the superclass and
784       // there are no instances of primitive classes.
785       DCHECK(klass->IsObjectClass());
786       // Instance of java lang object, probably a lock object. This means it will be dirty when we
787       // synchronize on it.
788       bin = Bin::kMiscDirty;
789     } else if (klass->IsDexCacheClass<kVerifyNone>()) {
790       // Dex file field becomes dirty when the image is loaded.
791       bin = Bin::kMiscDirty;
792     }
793     // else bin = kBinRegular
794   }
795 
796   return bin;
797 }
798 
AssignImageBinSlot(mirror::Object * object,size_t oat_index,Bin bin)799 void ImageWriter::AssignImageBinSlot(mirror::Object* object, size_t oat_index, Bin bin) {
800   DCHECK(object != nullptr);
801   size_t object_size = object->SizeOf();
802 
803   // Assign the oat index too.
804   if (IsMultiImage()) {
805     DCHECK(oat_index_map_.find(object) == oat_index_map_.end());
806     oat_index_map_.insert(std::make_pair(object, oat_index));
807   } else {
808     DCHECK(oat_index_map_.empty());
809   }
810 
811   ImageInfo& image_info = GetImageInfo(oat_index);
812 
813   size_t offset_delta = RoundUp(object_size, kObjectAlignment);  // 64-bit alignment
814   // How many bytes the current bin is at (aligned).
815   size_t current_offset = image_info.GetBinSlotSize(bin);
816   // Move the current bin size up to accommodate the object we just assigned a bin slot.
817   image_info.IncrementBinSlotSize(bin, offset_delta);
818 
819   BinSlot new_bin_slot(bin, current_offset);
820   SetImageBinSlot(object, new_bin_slot);
821 
822   image_info.IncrementBinSlotCount(bin, 1u);
823 
824   // Grow the image closer to the end by the object we just assigned.
825   image_info.image_end_ += offset_delta;
826 }
827 
WillMethodBeDirty(ArtMethod * m) const828 bool ImageWriter::WillMethodBeDirty(ArtMethod* m) const {
829   if (m->IsNative()) {
830     return true;
831   }
832   ObjPtr<mirror::Class> declaring_class = m->GetDeclaringClass<kWithoutReadBarrier>();
833   // Initialized is highly unlikely to dirty since there's no entry points to mutate.
834   return declaring_class == nullptr ||
835          declaring_class->GetStatus() != ClassStatus::kVisiblyInitialized;
836 }
837 
IsImageBinSlotAssigned(mirror::Object * object) const838 bool ImageWriter::IsImageBinSlotAssigned(mirror::Object* object) const {
839   DCHECK(object != nullptr);
840 
841   // We always stash the bin slot into a lockword, in the 'forwarding address' state.
842   // If it's in some other state, then we haven't yet assigned an image bin slot.
843   if (object->GetLockWord(false).GetState() != LockWord::kForwardingAddress) {
844     return false;
845   } else if (kIsDebugBuild) {
846     LockWord lock_word = object->GetLockWord(false);
847     size_t offset = lock_word.ForwardingAddress();
848     BinSlot bin_slot(offset);
849     size_t oat_index = GetOatIndex(object);
850     const ImageInfo& image_info = GetImageInfo(oat_index);
851     DCHECK_LT(bin_slot.GetOffset(), image_info.GetBinSlotSize(bin_slot.GetBin()))
852         << "bin slot offset should not exceed the size of that bin";
853   }
854   return true;
855 }
856 
GetImageBinSlot(mirror::Object * object,size_t oat_index) const857 ImageWriter::BinSlot ImageWriter::GetImageBinSlot(mirror::Object* object, size_t oat_index) const {
858   DCHECK(object != nullptr);
859   DCHECK(IsImageBinSlotAssigned(object));
860 
861   LockWord lock_word = object->GetLockWord(false);
862   size_t offset = lock_word.ForwardingAddress();  // TODO: ForwardingAddress should be uint32_t
863   DCHECK_LE(offset, std::numeric_limits<uint32_t>::max());
864 
865   BinSlot bin_slot(static_cast<uint32_t>(offset));
866   DCHECK_LT(bin_slot.GetOffset(), GetImageInfo(oat_index).GetBinSlotSize(bin_slot.GetBin()));
867 
868   return bin_slot;
869 }
870 
UpdateImageBinSlotOffset(mirror::Object * object,size_t oat_index,size_t new_offset)871 void ImageWriter::UpdateImageBinSlotOffset(mirror::Object* object,
872                                            size_t oat_index,
873                                            size_t new_offset) {
874   BinSlot old_bin_slot = GetImageBinSlot(object, oat_index);
875   DCHECK_LT(new_offset, GetImageInfo(oat_index).GetBinSlotSize(old_bin_slot.GetBin()));
876   BinSlot new_bin_slot(old_bin_slot.GetBin(), new_offset);
877   object->SetLockWord(LockWord::FromForwardingAddress(new_bin_slot.Uint32Value()),
878                       /*as_volatile=*/ false);
879   DCHECK_EQ(object->GetLockWord(false).ReadBarrierState(), 0u);
880   DCHECK(IsImageBinSlotAssigned(object));
881 }
882 
AllocMemory()883 bool ImageWriter::AllocMemory() {
884   for (ImageInfo& image_info : image_infos_) {
885     const size_t length = RoundUp(image_info.CreateImageSections().first, kElfSegmentAlignment);
886 
887     std::string error_msg;
888     image_info.image_ = MemMap::MapAnonymous("image writer image",
889                                              length,
890                                              PROT_READ | PROT_WRITE,
891                                              /*low_4gb=*/ false,
892                                              &error_msg);
893     if (UNLIKELY(!image_info.image_.IsValid())) {
894       LOG(ERROR) << "Failed to allocate memory for image file generation: " << error_msg;
895       return false;
896     }
897 
898     // Create the image bitmap, only needs to cover mirror object section which is up to image_end_.
899     // The covered size is rounded up to kCardSize to match the bitmap size expected by Loader::Init
900     // at art::gc::space::ImageSpace.
901     CHECK_LE(image_info.image_end_, length);
902     image_info.image_bitmap_ = gc::accounting::ContinuousSpaceBitmap::Create("image bitmap",
903         image_info.image_.Begin(),
904         RoundUp(image_info.image_end_, gc::accounting::CardTable::kCardSize));
905     if (!image_info.image_bitmap_.IsValid()) {
906       LOG(ERROR) << "Failed to allocate memory for image bitmap";
907       return false;
908     }
909   }
910   return true;
911 }
912 
913 // This visitor follows the references of an instance, recursively then prune this class
914 // if a type of any field is pruned.
915 class ImageWriter::PruneObjectReferenceVisitor {
916  public:
PruneObjectReferenceVisitor(ImageWriter * image_writer,bool * early_exit,HashSet<mirror::Object * > * visited,bool * result)917   PruneObjectReferenceVisitor(ImageWriter* image_writer,
918                         bool* early_exit,
919                         HashSet<mirror::Object*>* visited,
920                         bool* result)
921       : image_writer_(image_writer), early_exit_(early_exit), visited_(visited), result_(result) {}
922 
VisitRootIfNonNull(mirror::CompressedReference<mirror::Object> * root) const923   ALWAYS_INLINE void VisitRootIfNonNull(
924       [[maybe_unused]] mirror::CompressedReference<mirror::Object>* root) const
925       REQUIRES_SHARED(Locks::mutator_lock_) {}
926 
VisitRoot(mirror::CompressedReference<mirror::Object> * root) const927   ALWAYS_INLINE void VisitRoot([[maybe_unused]] mirror::CompressedReference<mirror::Object>* root)
928       const REQUIRES_SHARED(Locks::mutator_lock_) {}
929 
operator ()(ObjPtr<mirror::Object> obj,MemberOffset offset,bool is_static) const930   ALWAYS_INLINE void operator()(ObjPtr<mirror::Object> obj,
931                                 MemberOffset offset,
932                                 [[maybe_unused]] bool is_static) const
933       REQUIRES_SHARED(Locks::mutator_lock_) {
934     mirror::Object* ref =
935         obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(offset);
936     if (ref == nullptr || visited_->find(ref) != visited_->end()) {
937       return;
938     }
939 
940     ObjPtr<mirror::ObjectArray<mirror::Class>> class_roots =
941         Runtime::Current()->GetClassLinker()->GetClassRoots();
942     ObjPtr<mirror::Class> klass = ref->IsClass() ? ref->AsClass() : ref->GetClass();
943     if (klass == GetClassRoot<mirror::Method>(class_roots) ||
944         klass == GetClassRoot<mirror::Constructor>(class_roots)) {
945       // Prune all classes using reflection because the content they held will not be fixup.
946       *result_ = true;
947     }
948 
949     if (ref->IsClass()) {
950       *result_ = *result_ ||
951           image_writer_->PruneImageClassInternal(ref->AsClass(), early_exit_, visited_);
952     } else {
953       // Record the object visited in case of circular reference.
954       visited_->insert(ref);
955       *result_ = *result_ ||
956           image_writer_->PruneImageClassInternal(klass, early_exit_, visited_);
957       ref->VisitReferences(*this, *this);
958       // Clean up before exit for next call of this function.
959       auto it = visited_->find(ref);
960       DCHECK(it != visited_->end());
961       visited_->erase(it);
962     }
963   }
964 
operator ()(ObjPtr<mirror::Class> klass,ObjPtr<mirror::Reference> ref) const965   ALWAYS_INLINE void operator()([[maybe_unused]] ObjPtr<mirror::Class> klass,
966                                 ObjPtr<mirror::Reference> ref) const
967       REQUIRES_SHARED(Locks::mutator_lock_) {
968     operator()(ref, mirror::Reference::ReferentOffset(), /* is_static */ false);
969   }
970 
971  private:
972   ImageWriter* image_writer_;
973   bool* early_exit_;
974   HashSet<mirror::Object*>* visited_;
975   bool* const result_;
976 };
977 
978 
PruneImageClass(ObjPtr<mirror::Class> klass)979 bool ImageWriter::PruneImageClass(ObjPtr<mirror::Class> klass) {
980   bool early_exit = false;
981   HashSet<mirror::Object*> visited;
982   return PruneImageClassInternal(klass, &early_exit, &visited);
983 }
984 
PruneImageClassInternal(ObjPtr<mirror::Class> klass,bool * early_exit,HashSet<mirror::Object * > * visited)985 bool ImageWriter::PruneImageClassInternal(
986     ObjPtr<mirror::Class> klass,
987     bool* early_exit,
988     HashSet<mirror::Object*>* visited) {
989   DCHECK(early_exit != nullptr);
990   DCHECK(visited != nullptr);
991   DCHECK(compiler_options_.IsAppImage() || compiler_options_.IsBootImageExtension());
992   if (klass == nullptr || IsInBootImage(klass.Ptr())) {
993     return false;
994   }
995   auto found = prune_class_memo_.find(klass.Ptr());
996   if (found != prune_class_memo_.end()) {
997     // Already computed, return the found value.
998     return found->second;
999   }
1000   // Circular dependencies, return false but do not store the result in the memoization table.
1001   if (visited->find(klass.Ptr()) != visited->end()) {
1002     *early_exit = true;
1003     return false;
1004   }
1005   visited->insert(klass.Ptr());
1006   bool result = klass->IsBootStrapClassLoaded();
1007   std::string temp;
1008   // Prune if not an image class, this handles any broken sets of image classes such as having a
1009   // class in the set but not it's superclass.
1010   result = result || !compiler_options_.IsImageClass(klass->GetDescriptor(&temp));
1011   bool my_early_exit = false;  // Only for ourselves, ignore caller.
1012   // Remove classes that failed to verify since we don't want to have java.lang.VerifyError in the
1013   // app image.
1014   if (klass->IsErroneous()) {
1015     result = true;
1016   } else {
1017     ObjPtr<mirror::ClassExt> ext(klass->GetExtData());
1018     CHECK(ext.IsNull() || ext->GetErroneousStateError() == nullptr) << klass->PrettyClass();
1019   }
1020   if (!result) {
1021     // Check interfaces since these wont be visited through VisitReferences.)
1022     ObjPtr<mirror::IfTable> if_table = klass->GetIfTable();
1023     for (size_t i = 0, num_interfaces = klass->GetIfTableCount(); i < num_interfaces; ++i) {
1024       result = result || PruneImageClassInternal(if_table->GetInterface(i),
1025                                                  &my_early_exit,
1026                                                  visited);
1027     }
1028   }
1029   if (klass->IsObjectArrayClass()) {
1030     result = result || PruneImageClassInternal(klass->GetComponentType(),
1031                                                &my_early_exit,
1032                                                visited);
1033   }
1034   // Check static fields and their classes.
1035   if (klass->IsResolved() && klass->NumReferenceStaticFields() != 0) {
1036     size_t num_static_fields = klass->NumReferenceStaticFields();
1037     // Presumably GC can happen when we are cross compiling, it should not cause performance
1038     // problems to do pointer size logic.
1039     MemberOffset field_offset = klass->GetFirstReferenceStaticFieldOffset(
1040         Runtime::Current()->GetClassLinker()->GetImagePointerSize());
1041     for (size_t i = 0u; i < num_static_fields; ++i) {
1042       mirror::Object* ref = klass->GetFieldObject<mirror::Object>(field_offset);
1043       if (ref != nullptr) {
1044         if (ref->IsClass()) {
1045           result = result || PruneImageClassInternal(ref->AsClass(), &my_early_exit, visited);
1046         } else {
1047           mirror::Class* type = ref->GetClass();
1048           result = result || PruneImageClassInternal(type, &my_early_exit, visited);
1049           if (!result) {
1050             // For non-class case, also go through all the types mentioned by it's fields'
1051             // references recursively to decide whether to keep this class.
1052             bool tmp = false;
1053             PruneObjectReferenceVisitor visitor(this, &my_early_exit, visited, &tmp);
1054             ref->VisitReferences(visitor, visitor);
1055             result = result || tmp;
1056           }
1057         }
1058       }
1059       field_offset = MemberOffset(field_offset.Uint32Value() +
1060                                   sizeof(mirror::HeapReference<mirror::Object>));
1061     }
1062   }
1063   result = result || PruneImageClassInternal(klass->GetSuperClass(), &my_early_exit, visited);
1064   // Remove the class if the dex file is not in the set of dex files. This happens for classes that
1065   // are from uses-library if there is no profile. b/30688277
1066   ObjPtr<mirror::DexCache> dex_cache = klass->GetDexCache();
1067   if (dex_cache != nullptr) {
1068     result = result ||
1069         dex_file_oat_index_map_.find(dex_cache->GetDexFile()) == dex_file_oat_index_map_.end();
1070   }
1071   // Erase the element we stored earlier since we are exiting the function.
1072   auto it = visited->find(klass.Ptr());
1073   DCHECK(it != visited->end());
1074   visited->erase(it);
1075   // Only store result if it is true or none of the calls early exited due to circular
1076   // dependencies. If visited is empty then we are the root caller, in this case the cycle was in
1077   // a child call and we can remember the result.
1078   if (result == true || !my_early_exit || visited->empty()) {
1079     prune_class_memo_.Overwrite(klass.Ptr(), result);
1080   }
1081   *early_exit |= my_early_exit;
1082   return result;
1083 }
1084 
KeepClass(ObjPtr<mirror::Class> klass)1085 bool ImageWriter::KeepClass(ObjPtr<mirror::Class> klass) {
1086   if (klass == nullptr) {
1087     return false;
1088   }
1089   if (IsInBootImage(klass.Ptr())) {
1090     // Already in boot image, return true.
1091     DCHECK(!compiler_options_.IsBootImage());
1092     return true;
1093   }
1094   std::string temp;
1095   if (!compiler_options_.IsImageClass(klass->GetDescriptor(&temp))) {
1096     return false;
1097   }
1098   if (compiler_options_.IsAppImage()) {
1099     // For app images, we need to prune classes that
1100     // are defined by the boot class path we're compiling against but not in
1101     // the boot image spaces since these may have already been loaded at
1102     // run time when this image is loaded. Keep classes in the boot image
1103     // spaces we're compiling against since we don't want to re-resolve these.
1104     // FIXME: Update image classes in the `CompilerOptions` after initializing classes
1105     // with `--initialize-app-image-classes=true`. This experimental flag can currently
1106     // cause an inconsistency between `CompilerOptions::IsImageClass()` and what actually
1107     // ends up in the app image as seen in the run-test `660-clinit` where the class
1108     // `ObjectRef` is considered an app image class during compilation but in the end
1109     // it's pruned here. This inconsistency should be fixed if we want to properly
1110     // initialize app image classes. b/38313278
1111     bool keep = !PruneImageClass(klass);
1112     CHECK_IMPLIES(!compiler_options_.InitializeAppImageClasses(), keep)
1113         << klass->PrettyDescriptor();
1114     return keep;
1115   }
1116   return true;
1117 }
1118 
1119 class ImageWriter::PruneClassesVisitor : public ClassVisitor {
1120  public:
PruneClassesVisitor(ImageWriter * image_writer,ObjPtr<mirror::ClassLoader> class_loader)1121   PruneClassesVisitor(ImageWriter* image_writer, ObjPtr<mirror::ClassLoader> class_loader)
1122       : image_writer_(image_writer),
1123         class_loader_(class_loader),
1124         classes_to_prune_(),
1125         defined_class_count_(0u) { }
1126 
operator ()(ObjPtr<mirror::Class> klass)1127   bool operator()(ObjPtr<mirror::Class> klass) override REQUIRES_SHARED(Locks::mutator_lock_) {
1128     if (!image_writer_->KeepClass(klass.Ptr())) {
1129       classes_to_prune_.insert(klass.Ptr());
1130       if (klass->GetClassLoader() == class_loader_) {
1131         ++defined_class_count_;
1132       }
1133     }
1134     return true;
1135   }
1136 
Prune()1137   size_t Prune() REQUIRES_SHARED(Locks::mutator_lock_) {
1138     ClassTable* class_table =
1139         Runtime::Current()->GetClassLinker()->ClassTableForClassLoader(class_loader_);
1140     WriterMutexLock mu(Thread::Current(), class_table->lock_);
1141     // App class loader class tables contain only one internal set. The boot class path class
1142     // table also contains class sets from boot images we're compiling against but we are not
1143     // pruning these boot image classes, so all classes to remove are in the last set.
1144     DCHECK(!class_table->classes_.empty());
1145     ClassTable::ClassSet& last_class_set = class_table->classes_.back();
1146     for (mirror::Class* klass : classes_to_prune_) {
1147       uint32_t hash = klass->DescriptorHash();
1148       auto it = last_class_set.FindWithHash(ClassTable::TableSlot(klass, hash), hash);
1149       DCHECK(it != last_class_set.end());
1150       last_class_set.erase(it);
1151       DCHECK(std::none_of(class_table->classes_.begin(),
1152                           class_table->classes_.end(),
1153                           [klass, hash](ClassTable::ClassSet& class_set)
1154                               REQUIRES_SHARED(Locks::mutator_lock_) {
1155                             ClassTable::TableSlot slot(klass, hash);
1156                             return class_set.FindWithHash(slot, hash) != class_set.end();
1157                           }));
1158     }
1159     return defined_class_count_;
1160   }
1161 
1162  private:
1163   ImageWriter* const image_writer_;
1164   const ObjPtr<mirror::ClassLoader> class_loader_;
1165   HashSet<mirror::Class*> classes_to_prune_;
1166   size_t defined_class_count_;
1167 };
1168 
1169 class ImageWriter::PruneClassLoaderClassesVisitor : public ClassLoaderVisitor {
1170  public:
PruneClassLoaderClassesVisitor(ImageWriter * image_writer)1171   explicit PruneClassLoaderClassesVisitor(ImageWriter* image_writer)
1172       : image_writer_(image_writer), removed_class_count_(0) {}
1173 
Visit(ObjPtr<mirror::ClassLoader> class_loader)1174   void Visit(ObjPtr<mirror::ClassLoader> class_loader) override
1175       REQUIRES_SHARED(Locks::mutator_lock_) {
1176     PruneClassesVisitor classes_visitor(image_writer_, class_loader);
1177     ClassTable* class_table =
1178         Runtime::Current()->GetClassLinker()->ClassTableForClassLoader(class_loader);
1179     class_table->Visit(classes_visitor);
1180     removed_class_count_ += classes_visitor.Prune();
1181   }
1182 
GetRemovedClassCount() const1183   size_t GetRemovedClassCount() const {
1184     return removed_class_count_;
1185   }
1186 
1187  private:
1188   ImageWriter* const image_writer_;
1189   size_t removed_class_count_;
1190 };
1191 
VisitClassLoaders(ClassLoaderVisitor * visitor)1192 void ImageWriter::VisitClassLoaders(ClassLoaderVisitor* visitor) {
1193   WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
1194   visitor->Visit(nullptr);  // Visit boot class loader.
1195   Runtime::Current()->GetClassLinker()->VisitClassLoaders(visitor);
1196 }
1197 
PruneNonImageClasses()1198 void ImageWriter::PruneNonImageClasses() {
1199   Runtime* runtime = Runtime::Current();
1200   ClassLinker* class_linker = runtime->GetClassLinker();
1201   Thread* self = Thread::Current();
1202   ScopedAssertNoThreadSuspension sa(__FUNCTION__);
1203 
1204   // Prune uses-library dex caches. Only prune the uses-library dex caches since we want to make
1205   // sure the other ones don't get unloaded before the OatWriter runs.
1206   class_linker->VisitClassTables(
1207       [&](ClassTable* table) REQUIRES_SHARED(Locks::mutator_lock_) {
1208     table->RemoveStrongRoots(
1209         [&](GcRoot<mirror::Object> root) REQUIRES_SHARED(Locks::mutator_lock_) {
1210       ObjPtr<mirror::Object> obj = root.Read();
1211       if (obj->IsDexCache()) {
1212         // Return true if the dex file is not one of the ones in the map.
1213         return dex_file_oat_index_map_.find(obj->AsDexCache()->GetDexFile()) ==
1214             dex_file_oat_index_map_.end();
1215       }
1216       // Return false to avoid removing.
1217       return false;
1218     });
1219   });
1220 
1221   // Remove the undesired classes from the class roots.
1222   {
1223     PruneClassLoaderClassesVisitor class_loader_visitor(this);
1224     VisitClassLoaders(&class_loader_visitor);
1225     VLOG(compiler) << "Pruned " << class_loader_visitor.GetRemovedClassCount() << " classes";
1226   }
1227 
1228   // Completely clear DexCaches.
1229   dchecked_vector<ObjPtr<mirror::DexCache>> dex_caches = FindDexCaches(self);
1230   for (ObjPtr<mirror::DexCache> dex_cache : dex_caches) {
1231     dex_cache->ResetNativeArrays();
1232   }
1233 
1234   // Drop the array class cache in the ClassLinker, as these are roots holding those classes live.
1235   class_linker->DropFindArrayClassCache();
1236 
1237   // Clear to save RAM.
1238   prune_class_memo_.clear();
1239 }
1240 
FindDexCaches(Thread * self)1241 dchecked_vector<ObjPtr<mirror::DexCache>> ImageWriter::FindDexCaches(Thread* self) {
1242   dchecked_vector<ObjPtr<mirror::DexCache>> dex_caches;
1243   ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1244   ReaderMutexLock mu2(self, *Locks::dex_lock_);
1245   dex_caches.reserve(class_linker->GetDexCachesData().size());
1246   for (const auto& entry : class_linker->GetDexCachesData()) {
1247     const ClassLinker::DexCacheData& data = entry.second;
1248     if (self->IsJWeakCleared(data.weak_root)) {
1249       continue;
1250     }
1251     dex_caches.push_back(self->DecodeJObject(data.weak_root)->AsDexCache());
1252   }
1253   return dex_caches;
1254 }
1255 
CheckNonImageClassesRemoved()1256 void ImageWriter::CheckNonImageClassesRemoved() {
1257   auto visitor = [&](Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
1258     if (obj->IsClass() && !IsInBootImage(obj)) {
1259       ObjPtr<Class> klass = obj->AsClass();
1260       if (!KeepClass(klass)) {
1261         DumpImageClasses();
1262         CHECK(KeepClass(klass))
1263             << Runtime::Current()->GetHeap()->GetVerification()->FirstPathFromRootSet(klass);
1264       }
1265     }
1266   };
1267   gc::Heap* heap = Runtime::Current()->GetHeap();
1268   heap->VisitObjects(visitor);
1269 }
1270 
PromoteWeakInternsToStrong(Thread * self)1271 void ImageWriter::PromoteWeakInternsToStrong(Thread* self) {
1272   InternTable* intern_table = Runtime::Current()->GetInternTable();
1273   MutexLock mu(self, *Locks::intern_table_lock_);
1274   DCHECK_EQ(intern_table->weak_interns_.tables_.size(), 1u);
1275   for (GcRoot<mirror::String>& entry : intern_table->weak_interns_.tables_.front().set_) {
1276     ObjPtr<mirror::String> s = entry.Read<kWithoutReadBarrier>();
1277     DCHECK(!IsStronglyInternedString(s));
1278     uint32_t hash = static_cast<uint32_t>(s->GetStoredHashCode());
1279     intern_table->InsertStrong(s, hash);
1280   }
1281   intern_table->weak_interns_.tables_.front().set_.clear();
1282 }
1283 
DumpImageClasses()1284 void ImageWriter::DumpImageClasses() {
1285   for (const std::string& image_class : compiler_options_.GetImageClasses()) {
1286     LOG(INFO) << " " << image_class;
1287   }
1288 }
1289 
CreateImageRoots()1290 bool ImageWriter::CreateImageRoots() {
1291   Runtime* runtime = Runtime::Current();
1292   ClassLinker* class_linker = runtime->GetClassLinker();
1293   Thread* self = Thread::Current();
1294   VariableSizedHandleScope handles(self);
1295 
1296   // Prepare boot image live objects if we're compiling a boot image or boot image extension.
1297   Handle<mirror::ObjectArray<mirror::Object>> boot_image_live_objects;
1298   if (compiler_options_.IsBootImage()) {
1299     boot_image_live_objects = handles.NewHandle(AllocateBootImageLiveObjects(self, runtime));
1300     if (boot_image_live_objects == nullptr) {
1301       return false;
1302     }
1303   } else if (compiler_options_.IsBootImageExtension()) {
1304     gc::Heap* heap = runtime->GetHeap();
1305     DCHECK(!heap->GetBootImageSpaces().empty());
1306     const ImageHeader& primary_header = heap->GetBootImageSpaces().front()->GetImageHeader();
1307     boot_image_live_objects = handles.NewHandle(ObjPtr<ObjectArray<Object>>::DownCast(
1308         primary_header.GetImageRoot<kWithReadBarrier>(ImageHeader::kBootImageLiveObjects)));
1309     DCHECK(boot_image_live_objects != nullptr);
1310   }
1311 
1312   // Collect dex caches and the sizes of dex cache arrays.
1313   struct DexCacheRecord {
1314     uint64_t registration_index;
1315     Handle<mirror::DexCache> dex_cache;
1316     size_t oat_index;
1317   };
1318   size_t num_oat_files = oat_filenames_.size();
1319   dchecked_vector<size_t> dex_cache_counts(num_oat_files, 0u);
1320   dchecked_vector<DexCacheRecord> dex_cache_records;
1321   dex_cache_records.reserve(dex_file_oat_index_map_.size());
1322   {
1323     ReaderMutexLock mu(self, *Locks::dex_lock_);
1324     // Count number of dex caches not in the boot image.
1325     for (const auto& entry : class_linker->GetDexCachesData()) {
1326       const ClassLinker::DexCacheData& data = entry.second;
1327       ObjPtr<mirror::DexCache> dex_cache =
1328           ObjPtr<mirror::DexCache>::DownCast(self->DecodeJObject(data.weak_root));
1329       if (dex_cache == nullptr) {
1330         continue;
1331       }
1332       const DexFile* dex_file = dex_cache->GetDexFile();
1333       auto it = dex_file_oat_index_map_.find(dex_file);
1334       if (it != dex_file_oat_index_map_.end()) {
1335         size_t oat_index = it->second;
1336         DCHECK(IsImageDexCache(dex_cache));
1337         ++dex_cache_counts[oat_index];
1338         Handle<mirror::DexCache> h_dex_cache = handles.NewHandle(dex_cache);
1339         dex_cache_records.push_back({data.registration_index, h_dex_cache, oat_index});
1340       }
1341     }
1342   }
1343 
1344   // Allocate dex cache arrays.
1345   dchecked_vector<Handle<ObjectArray<Object>>> dex_cache_arrays;
1346   dex_cache_arrays.reserve(num_oat_files);
1347   for (size_t oat_index = 0; oat_index != num_oat_files; ++oat_index) {
1348     ObjPtr<ObjectArray<Object>> dex_caches = ObjectArray<Object>::Alloc(
1349         self, GetClassRoot<ObjectArray<Object>>(class_linker), dex_cache_counts[oat_index]);
1350     if (dex_caches == nullptr) {
1351       return false;
1352     }
1353     dex_cache_counts[oat_index] = 0u;  // Reset count for filling in dex caches below.
1354     dex_cache_arrays.push_back(handles.NewHandle(dex_caches));
1355   }
1356 
1357   // Sort dex caches by registration index to make output deterministic.
1358   std::sort(dex_cache_records.begin(),
1359             dex_cache_records.end(),
1360             [](const DexCacheRecord& lhs, const DexCacheRecord&rhs) {
1361               return lhs.registration_index < rhs.registration_index;
1362             });
1363 
1364   // Fill dex cache arrays.
1365   for (const DexCacheRecord& record : dex_cache_records) {
1366     ObjPtr<ObjectArray<Object>> dex_caches = dex_cache_arrays[record.oat_index].Get();
1367     dex_caches->SetWithoutChecks</*kTransactionActive=*/ false>(
1368         dex_cache_counts[record.oat_index], record.dex_cache.Get());
1369     ++dex_cache_counts[record.oat_index];
1370   }
1371 
1372   // Create image roots with empty dex cache arrays.
1373   image_roots_.reserve(num_oat_files);
1374   JavaVMExt* vm = down_cast<JNIEnvExt*>(self->GetJniEnv())->GetVm();
1375   for (size_t oat_index = 0; oat_index != num_oat_files; ++oat_index) {
1376     // Build an Object[] of the roots needed to restore the runtime.
1377     int32_t image_roots_size = ImageHeader::NumberOfImageRoots(compiler_options_.IsAppImage());
1378     ObjPtr<ObjectArray<Object>> image_roots = ObjectArray<Object>::Alloc(
1379         self, GetClassRoot<ObjectArray<Object>>(class_linker), image_roots_size);
1380     if (image_roots == nullptr) {
1381       return false;
1382     }
1383     ObjPtr<ObjectArray<Object>> dex_caches = dex_cache_arrays[oat_index].Get();
1384     CHECK_EQ(dex_cache_counts[oat_index],
1385              dchecked_integral_cast<size_t>(dex_caches->GetLength<kVerifyNone>()))
1386         << "The number of non-image dex caches changed.";
1387     image_roots->SetWithoutChecks</*kTransactionActive=*/ false>(
1388         ImageHeader::kDexCaches, dex_caches);
1389     image_roots->SetWithoutChecks</*kTransactionActive=*/ false>(
1390         ImageHeader::kClassRoots, class_linker->GetClassRoots());
1391     if (!compiler_options_.IsAppImage()) {
1392       DCHECK(boot_image_live_objects != nullptr);
1393       image_roots->SetWithoutChecks</*kTransactionActive=*/ false>(
1394           ImageHeader::kBootImageLiveObjects, boot_image_live_objects.Get());
1395     } else {
1396       DCHECK(boot_image_live_objects.GetReference() == nullptr);
1397       image_roots->SetWithoutChecks</*kTransactionActive=*/ false>(
1398           ImageHeader::kAppImageClassLoader, GetAppClassLoader());
1399     }
1400     for (int32_t i = 0; i != image_roots_size; ++i) {
1401       CHECK(image_roots->Get(i) != nullptr);
1402     }
1403     image_roots_.push_back(vm->AddGlobalRef(self, image_roots));
1404   }
1405 
1406   return true;
1407 }
1408 
RecordNativeRelocations(ObjPtr<mirror::Class> klass,size_t oat_index)1409 void ImageWriter::RecordNativeRelocations(ObjPtr<mirror::Class> klass, size_t oat_index) {
1410   // Visit and assign offsets for fields and field arrays.
1411   DCHECK_EQ(oat_index, GetOatIndexForClass(klass));
1412   DCHECK(!klass->IsErroneous()) << klass->GetStatus();
1413   if (compiler_options_.IsAppImage()) {
1414     // Extra consistency check: no boot loader classes should be left!
1415     CHECK(!klass->IsBootStrapClassLoaded()) << klass->PrettyClass();
1416   }
1417   LengthPrefixedArray<ArtField>* fields[] = {
1418       klass->GetSFieldsPtr(), klass->GetIFieldsPtr(),
1419   };
1420   ImageInfo& image_info = GetImageInfo(oat_index);
1421   for (LengthPrefixedArray<ArtField>* cur_fields : fields) {
1422     // Total array length including header.
1423     if (cur_fields != nullptr) {
1424       // Forward the entire array at once.
1425       size_t offset = image_info.GetBinSlotSize(Bin::kArtField);
1426       DCHECK(!IsInBootImage(cur_fields));
1427       bool inserted =
1428           native_object_relocations_.insert(std::make_pair(
1429               cur_fields,
1430               NativeObjectRelocation{
1431                   oat_index, offset, NativeObjectRelocationType::kArtFieldArray
1432               })).second;
1433       CHECK(inserted) << "Field array " << cur_fields << " already forwarded";
1434       const size_t size = LengthPrefixedArray<ArtField>::ComputeSize(cur_fields->size());
1435       offset += size;
1436       image_info.IncrementBinSlotSize(Bin::kArtField, size);
1437       DCHECK_EQ(offset, image_info.GetBinSlotSize(Bin::kArtField));
1438     }
1439   }
1440   // Visit and assign offsets for methods.
1441   size_t num_methods = klass->NumMethods();
1442   if (num_methods != 0) {
1443     bool any_dirty = false;
1444     for (auto& m : klass->GetMethods(target_ptr_size_)) {
1445       if (WillMethodBeDirty(&m)) {
1446         any_dirty = true;
1447         break;
1448       }
1449     }
1450     NativeObjectRelocationType type = any_dirty
1451         ? NativeObjectRelocationType::kArtMethodDirty
1452         : NativeObjectRelocationType::kArtMethodClean;
1453     Bin bin_type = BinTypeForNativeRelocationType(type);
1454     // Forward the entire array at once, but header first.
1455     const size_t method_alignment = ArtMethod::Alignment(target_ptr_size_);
1456     const size_t method_size = ArtMethod::Size(target_ptr_size_);
1457     const size_t header_size = LengthPrefixedArray<ArtMethod>::ComputeSize(0,
1458                                                                            method_size,
1459                                                                            method_alignment);
1460     LengthPrefixedArray<ArtMethod>* array = klass->GetMethodsPtr();
1461     size_t offset = image_info.GetBinSlotSize(bin_type);
1462     DCHECK(!IsInBootImage(array));
1463     bool inserted =
1464         native_object_relocations_.insert(std::make_pair(
1465             array,
1466             NativeObjectRelocation{
1467                 oat_index,
1468                 offset,
1469                 any_dirty ? NativeObjectRelocationType::kArtMethodArrayDirty
1470                           : NativeObjectRelocationType::kArtMethodArrayClean
1471             })).second;
1472     CHECK(inserted) << "Method array " << array << " already forwarded";
1473     image_info.IncrementBinSlotSize(bin_type, header_size);
1474     for (auto& m : klass->GetMethods(target_ptr_size_)) {
1475       AssignMethodOffset(&m, type, oat_index);
1476     }
1477     // Only write JNI stub methods in boot images, but not in boot image extensions and app images.
1478     // And the write only happens in non-debuggable since we never use AOT code for debuggable.
1479     if (compiler_options_.IsBootImage() &&
1480         compiler_options_.IsJniCompilationEnabled() &&
1481         !compiler_options_.GetDebuggable()) {
1482       for (auto& m : klass->GetMethods(target_ptr_size_)) {
1483         if (m.IsNative() && !m.IsIntrinsic()) {
1484           AssignJniStubMethodOffset(&m, oat_index);
1485         }
1486       }
1487     }
1488     (any_dirty ? dirty_methods_ : clean_methods_) += num_methods;
1489   }
1490   // Assign offsets for all runtime methods in the IMT since these may hold conflict tables
1491   // live.
1492   if (klass->ShouldHaveImt()) {
1493     ImTable* imt = klass->GetImt(target_ptr_size_);
1494     if (TryAssignImTableOffset(imt, oat_index)) {
1495       // Since imt's can be shared only do this the first time to not double count imt method
1496       // fixups.
1497       for (size_t i = 0; i < ImTable::kSize; ++i) {
1498         ArtMethod* imt_method = imt->Get(i, target_ptr_size_);
1499         DCHECK(imt_method != nullptr);
1500         if (imt_method->IsRuntimeMethod() &&
1501             !IsInBootImage(imt_method) &&
1502             !NativeRelocationAssigned(imt_method)) {
1503           AssignMethodOffset(imt_method, NativeObjectRelocationType::kRuntimeMethod, oat_index);
1504         }
1505       }
1506     }
1507   }
1508 }
1509 
NativeRelocationAssigned(void * ptr) const1510 bool ImageWriter::NativeRelocationAssigned(void* ptr) const {
1511   return native_object_relocations_.find(ptr) != native_object_relocations_.end();
1512 }
1513 
TryAssignImTableOffset(ImTable * imt,size_t oat_index)1514 bool ImageWriter::TryAssignImTableOffset(ImTable* imt, size_t oat_index) {
1515   // No offset, or already assigned.
1516   if (imt == nullptr || IsInBootImage(imt) || NativeRelocationAssigned(imt)) {
1517     return false;
1518   }
1519   // If the method is a conflict method we also want to assign the conflict table offset.
1520   ImageInfo& image_info = GetImageInfo(oat_index);
1521   const size_t size = ImTable::SizeInBytes(target_ptr_size_);
1522   native_object_relocations_.insert(std::make_pair(
1523       imt,
1524       NativeObjectRelocation{
1525           oat_index,
1526           image_info.GetBinSlotSize(Bin::kImTable),
1527           NativeObjectRelocationType::kIMTable
1528       }));
1529   image_info.IncrementBinSlotSize(Bin::kImTable, size);
1530   return true;
1531 }
1532 
TryAssignConflictTableOffset(ImtConflictTable * table,size_t oat_index)1533 void ImageWriter::TryAssignConflictTableOffset(ImtConflictTable* table, size_t oat_index) {
1534   // No offset, or already assigned.
1535   if (table == nullptr || NativeRelocationAssigned(table)) {
1536     return;
1537   }
1538   CHECK(!IsInBootImage(table));
1539   // If the method is a conflict method we also want to assign the conflict table offset.
1540   ImageInfo& image_info = GetImageInfo(oat_index);
1541   const size_t size = table->ComputeSize(target_ptr_size_);
1542   native_object_relocations_.insert(std::make_pair(
1543       table,
1544       NativeObjectRelocation{
1545           oat_index,
1546           image_info.GetBinSlotSize(Bin::kIMTConflictTable),
1547           NativeObjectRelocationType::kIMTConflictTable
1548       }));
1549   image_info.IncrementBinSlotSize(Bin::kIMTConflictTable, size);
1550 }
1551 
AssignMethodOffset(ArtMethod * method,NativeObjectRelocationType type,size_t oat_index)1552 void ImageWriter::AssignMethodOffset(ArtMethod* method,
1553                                      NativeObjectRelocationType type,
1554                                      size_t oat_index) {
1555   DCHECK(!IsInBootImage(method));
1556   CHECK(!NativeRelocationAssigned(method)) << "Method " << method << " already assigned "
1557       << ArtMethod::PrettyMethod(method);
1558   if (method->IsRuntimeMethod()) {
1559     TryAssignConflictTableOffset(method->GetImtConflictTable(target_ptr_size_), oat_index);
1560   }
1561   ImageInfo& image_info = GetImageInfo(oat_index);
1562   Bin bin_type = BinTypeForNativeRelocationType(type);
1563   size_t offset = image_info.GetBinSlotSize(bin_type);
1564   native_object_relocations_.insert(
1565       std::make_pair(method, NativeObjectRelocation{oat_index, offset, type}));
1566   image_info.IncrementBinSlotSize(bin_type, ArtMethod::Size(target_ptr_size_));
1567 }
1568 
AssignJniStubMethodOffset(ArtMethod * method,size_t oat_index)1569 void ImageWriter::AssignJniStubMethodOffset(ArtMethod* method, size_t oat_index) {
1570   CHECK(method->IsNative());
1571   auto it = jni_stub_map_.find(JniStubKey(method));
1572   if (it == jni_stub_map_.end()) {
1573     ImageInfo& image_info = GetImageInfo(oat_index);
1574     constexpr Bin bin_type = Bin::kJniStubMethod;
1575     size_t offset = image_info.GetBinSlotSize(bin_type);
1576     jni_stub_map_.Put(std::make_pair(
1577         JniStubKey(method),
1578         std::make_pair(method, JniStubMethodRelocation{oat_index, offset})));
1579     image_info.IncrementBinSlotSize(bin_type, static_cast<size_t>(target_ptr_size_));
1580   }
1581 }
1582 
1583 class ImageWriter::LayoutHelper {
1584  public:
LayoutHelper(ImageWriter * image_writer)1585   explicit LayoutHelper(ImageWriter* image_writer)
1586       : image_writer_(image_writer) {
1587     bin_objects_.resize(image_writer_->image_infos_.size());
1588     for (auto& inner : bin_objects_) {
1589       inner.resize(enum_cast<size_t>(Bin::kMirrorCount));
1590     }
1591   }
1592 
1593   void ProcessDexFileObjects(Thread* self) REQUIRES_SHARED(Locks::mutator_lock_);
1594   void ProcessRoots(Thread* self) REQUIRES_SHARED(Locks::mutator_lock_);
1595   void FinalizeInternTables() REQUIRES_SHARED(Locks::mutator_lock_);
1596   // Recreate dirty object offsets (kKnownDirty bin) with objects sorted by sort_key.
1597   void SortDirtyObjects(const HashMap<mirror::Object*, uint32_t>& dirty_objects, size_t oat_index)
1598       REQUIRES_SHARED(Locks::mutator_lock_);
1599 
1600   void VerifyImageBinSlotsAssigned() REQUIRES_SHARED(Locks::mutator_lock_);
1601 
1602   void FinalizeBinSlotOffsets() REQUIRES_SHARED(Locks::mutator_lock_);
1603 
1604   /*
1605    * Collects the string reference info necessary for loading app images.
1606    *
1607    * Because AppImages may contain interned strings that must be deduplicated
1608    * with previously interned strings when loading the app image, we need to
1609    * visit references to these strings and update them to point to the correct
1610    * string. To speed up the visiting of references at load time we include
1611    * a list of offsets to string references in the AppImage.
1612    */
1613   void CollectStringReferenceInfo() REQUIRES_SHARED(Locks::mutator_lock_);
1614 
1615  private:
1616   class CollectClassesVisitor;
1617   class CollectStringReferenceVisitor;
1618   class VisitReferencesVisitor;
1619 
1620   void ProcessInterns(Thread* self) REQUIRES_SHARED(Locks::mutator_lock_);
1621   void ProcessWorkQueue() REQUIRES_SHARED(Locks::mutator_lock_);
1622 
1623   using WorkQueue = std::deque<std::pair<ObjPtr<mirror::Object>, size_t>>;
1624 
1625   void VisitReferences(ObjPtr<mirror::Object> obj, size_t oat_index)
1626       REQUIRES_SHARED(Locks::mutator_lock_);
1627   bool TryAssignBinSlot(ObjPtr<mirror::Object> obj, size_t oat_index)
1628       REQUIRES_SHARED(Locks::mutator_lock_);
1629   ImageWriter::Bin AssignImageBinSlot(ObjPtr<mirror::Object> object, size_t oat_index)
1630       REQUIRES_SHARED(Locks::mutator_lock_);
1631   void AssignImageBinSlot(ObjPtr<mirror::Object> object, size_t oat_index, Bin bin)
1632       REQUIRES_SHARED(Locks::mutator_lock_);
1633 
1634   ImageWriter* const image_writer_;
1635 
1636   // Work list of <object, oat_index> for objects. Everything in the queue must already be
1637   // assigned a bin slot.
1638   WorkQueue work_queue_;
1639 
1640   // Objects for individual bins. Indexed by `oat_index` and `bin`.
1641   // Cannot use ObjPtr<> because of invalidation in Heap::VisitObjects().
1642   dchecked_vector<dchecked_vector<dchecked_vector<mirror::Object*>>> bin_objects_;
1643 
1644   // Interns that do not have a corresponding StringId in any of the input dex files.
1645   // These shall be assigned to individual images based on the `oat_index` that we
1646   // see as we visit them during the work queue processing.
1647   dchecked_vector<mirror::String*> non_dex_file_interns_;
1648 };
1649 
1650 class ImageWriter::LayoutHelper::CollectClassesVisitor {
1651  public:
CollectClassesVisitor(ImageWriter * image_writer)1652   explicit CollectClassesVisitor(ImageWriter* image_writer)
1653       : image_writer_(image_writer),
1654         dex_files_(image_writer_->compiler_options_.GetDexFilesForOatFile()) {}
1655 
operator ()(ObjPtr<mirror::Class> klass)1656   bool operator()(ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) {
1657     if (!image_writer_->IsInBootImage(klass.Ptr())) {
1658       ObjPtr<mirror::Class> component_type = klass;
1659       size_t dimension = 0u;
1660       while (component_type->IsArrayClass<kVerifyNone>()) {
1661         ++dimension;
1662         component_type = component_type->GetComponentType<kVerifyNone, kWithoutReadBarrier>();
1663       }
1664       DCHECK(!component_type->IsProxyClass());
1665       size_t dex_file_index;
1666       uint32_t class_def_index = 0u;
1667       if (UNLIKELY(component_type->IsPrimitive())) {
1668         DCHECK(image_writer_->compiler_options_.IsBootImage());
1669         dex_file_index = 0u;
1670         class_def_index = enum_cast<uint32_t>(component_type->GetPrimitiveType());
1671       } else {
1672         auto it = std::find(dex_files_.begin(), dex_files_.end(), &component_type->GetDexFile());
1673         DCHECK(it != dex_files_.end()) << klass->PrettyDescriptor();
1674         dex_file_index = std::distance(dex_files_.begin(), it) + 1u;  // 0 is for primitive types.
1675         class_def_index = component_type->GetDexClassDefIndex();
1676       }
1677       klasses_.push_back({klass, dex_file_index, class_def_index, dimension});
1678     }
1679     return true;
1680   }
1681 
ProcessCollectedClasses(Thread * self)1682   WorkQueue ProcessCollectedClasses(Thread* self) REQUIRES_SHARED(Locks::mutator_lock_) {
1683     std::sort(klasses_.begin(), klasses_.end());
1684 
1685     ImageWriter* image_writer = image_writer_;
1686     WorkQueue work_queue;
1687     size_t last_dex_file_index = static_cast<size_t>(-1);
1688     size_t last_oat_index = static_cast<size_t>(-1);
1689     for (const ClassEntry& entry : klasses_) {
1690       if (last_dex_file_index != entry.dex_file_index) {
1691         if (UNLIKELY(entry.dex_file_index == 0u)) {
1692           last_oat_index = GetDefaultOatIndex();  // Primitive type.
1693         } else {
1694           uint32_t dex_file_index = entry.dex_file_index - 1u;  // 0 is for primitive types.
1695           last_oat_index = image_writer->GetOatIndexForDexFile(dex_files_[dex_file_index]);
1696         }
1697         last_dex_file_index = entry.dex_file_index;
1698       }
1699       // Count the number of classes for class tables.
1700       image_writer->image_infos_[last_oat_index].class_table_size_ += 1u;
1701       work_queue.emplace_back(entry.klass, last_oat_index);
1702     }
1703     klasses_.clear();
1704 
1705     // Prepare image class tables.
1706     dchecked_vector<mirror::Class*> boot_image_classes;
1707     if (image_writer->compiler_options_.IsAppImage()) {
1708       DCHECK_EQ(image_writer->image_infos_.size(), 1u);
1709       ImageInfo& image_info = image_writer->image_infos_[0];
1710       // Log the non-boot image class count for app image for debugging purposes.
1711       VLOG(compiler) << "Dex2Oat:AppImage:classCount = " << image_info.class_table_size_;
1712       // Collect boot image classes referenced by app class loader's class table.
1713       JavaVMExt* vm = down_cast<JNIEnvExt*>(self->GetJniEnv())->GetVm();
1714       auto app_class_loader = DecodeGlobalWithoutRB<mirror::ClassLoader>(
1715           vm, image_writer->app_class_loader_);
1716       ClassTable* app_class_table = app_class_loader->GetClassTable();
1717       ReaderMutexLock lock(self, app_class_table->lock_);
1718       DCHECK_EQ(app_class_table->classes_.size(), 1u);
1719       const ClassTable::ClassSet& app_class_set = app_class_table->classes_[0];
1720       DCHECK_GE(app_class_set.size(), image_info.class_table_size_);
1721       boot_image_classes.reserve(app_class_set.size() - image_info.class_table_size_);
1722       for (const ClassTable::TableSlot& slot : app_class_set) {
1723         mirror::Class* klass = slot.Read<kWithoutReadBarrier>().Ptr();
1724         if (image_writer->IsInBootImage(klass)) {
1725           boot_image_classes.push_back(klass);
1726         }
1727       }
1728       DCHECK_EQ(app_class_set.size() - image_info.class_table_size_, boot_image_classes.size());
1729       // Increase the app class table size to include referenced boot image classes.
1730       image_info.class_table_size_ = app_class_set.size();
1731     }
1732     for (ImageInfo& image_info : image_writer->image_infos_) {
1733       if (image_info.class_table_size_ != 0u) {
1734         // Make sure the class table shall be full by allocating a buffer of the right size.
1735         size_t buffer_size = static_cast<size_t>(
1736             ceil(image_info.class_table_size_ / kImageClassTableMaxLoadFactor));
1737         image_info.class_table_buffer_.reset(new ClassTable::TableSlot[buffer_size]);
1738         DCHECK(image_info.class_table_buffer_ != nullptr);
1739         image_info.class_table_.emplace(kImageClassTableMinLoadFactor,
1740                                         kImageClassTableMaxLoadFactor,
1741                                         image_info.class_table_buffer_.get(),
1742                                         buffer_size);
1743       }
1744     }
1745     for (const auto& pair : work_queue) {
1746       ObjPtr<mirror::Class> klass = pair.first->AsClass();
1747       size_t oat_index = pair.second;
1748       DCHECK(image_writer->image_infos_[oat_index].class_table_.has_value());
1749       ClassTable::ClassSet& class_table = *image_writer->image_infos_[oat_index].class_table_;
1750       uint32_t hash = klass->DescriptorHash();
1751       bool inserted = class_table.InsertWithHash(ClassTable::TableSlot(klass, hash), hash).second;
1752       DCHECK(inserted) << "Class " << klass->PrettyDescriptor()
1753           << " (" << klass.Ptr() << ") already inserted";
1754     }
1755     if (image_writer->compiler_options_.IsAppImage()) {
1756       DCHECK_EQ(image_writer->image_infos_.size(), 1u);
1757       ImageInfo& image_info = image_writer->image_infos_[0];
1758       if (image_info.class_table_size_ != 0u) {
1759         // Insert boot image class references to the app class table.
1760         // The order of insertion into the app class loader's ClassTable is non-deterministic,
1761         // so sort the boot image classes by the boot image address to get deterministic table.
1762         std::sort(boot_image_classes.begin(), boot_image_classes.end());
1763         DCHECK(image_info.class_table_.has_value());
1764         ClassTable::ClassSet& table = *image_info.class_table_;
1765         for (mirror::Class* klass : boot_image_classes) {
1766           uint32_t hash = klass->DescriptorHash();
1767           bool inserted = table.InsertWithHash(ClassTable::TableSlot(klass, hash), hash).second;
1768           DCHECK(inserted) << "Boot image class " << klass->PrettyDescriptor()
1769               << " (" << klass << ") already inserted";
1770         }
1771         DCHECK_EQ(table.size(), image_info.class_table_size_);
1772       }
1773     }
1774     for (ImageInfo& image_info : image_writer->image_infos_) {
1775       DCHECK_EQ(image_info.class_table_bytes_, 0u);
1776       if (image_info.class_table_size_ != 0u) {
1777         DCHECK(image_info.class_table_.has_value());
1778         DCHECK_EQ(image_info.class_table_->size(), image_info.class_table_size_);
1779         image_info.class_table_bytes_ = image_info.class_table_->WriteToMemory(nullptr);
1780         DCHECK_NE(image_info.class_table_bytes_, 0u);
1781       } else {
1782         DCHECK(!image_info.class_table_.has_value());
1783       }
1784     }
1785 
1786     return work_queue;
1787   }
1788 
1789  private:
1790   struct ClassEntry {
1791     ObjPtr<mirror::Class> klass;
1792     // We shall sort classes by dex file, class def index and array dimension.
1793     size_t dex_file_index;
1794     uint32_t class_def_index;
1795     size_t dimension;
1796 
operator <art::linker::ImageWriter::LayoutHelper::CollectClassesVisitor::ClassEntry1797     bool operator<(const ClassEntry& other) const {
1798       return std::tie(dex_file_index, class_def_index, dimension) <
1799              std::tie(other.dex_file_index, other.class_def_index, other.dimension);
1800     }
1801   };
1802 
1803   ImageWriter* const image_writer_;
1804   const ArrayRef<const DexFile* const> dex_files_;
1805   std::deque<ClassEntry> klasses_;
1806 };
1807 
1808 class ImageWriter::LayoutHelper::CollectStringReferenceVisitor {
1809  public:
CollectStringReferenceVisitor(const ImageWriter * image_writer,size_t oat_index,dchecked_vector<AppImageReferenceOffsetInfo> * const string_reference_offsets,ObjPtr<mirror::Object> current_obj)1810   explicit CollectStringReferenceVisitor(
1811       const ImageWriter* image_writer,
1812       size_t oat_index,
1813       dchecked_vector<AppImageReferenceOffsetInfo>* const string_reference_offsets,
1814       ObjPtr<mirror::Object> current_obj)
1815       : image_writer_(image_writer),
1816         oat_index_(oat_index),
1817         string_reference_offsets_(string_reference_offsets),
1818         current_obj_(current_obj) {}
1819 
VisitRootIfNonNull(mirror::CompressedReference<mirror::Object> * root) const1820   void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
1821       REQUIRES_SHARED(Locks::mutator_lock_) {
1822     if (!root->IsNull()) {
1823       VisitRoot(root);
1824     }
1825   }
1826 
VisitRoot(mirror::CompressedReference<mirror::Object> * root) const1827   void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
1828       REQUIRES_SHARED(Locks::mutator_lock_)  {
1829     // Only dex caches have native String roots. These are collected separately.
1830     DCHECK((current_obj_->IsDexCache<kVerifyNone, kWithoutReadBarrier>()) ||
1831            !image_writer_->IsInternedAppImageStringReference(root->AsMirrorPtr()))
1832         << mirror::Object::PrettyTypeOf(current_obj_);
1833   }
1834 
1835   // Collects info for managed fields that reference managed Strings.
operator ()(ObjPtr<mirror::Object> obj,MemberOffset member_offset,bool is_static) const1836   void operator()(ObjPtr<mirror::Object> obj,
1837                   MemberOffset member_offset,
1838                   [[maybe_unused]] bool is_static) const REQUIRES_SHARED(Locks::mutator_lock_) {
1839     ObjPtr<mirror::Object> referred_obj =
1840         obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(member_offset);
1841 
1842     if (image_writer_->IsInternedAppImageStringReference(referred_obj)) {
1843       size_t base_offset = image_writer_->GetImageOffset(current_obj_.Ptr(), oat_index_);
1844       string_reference_offsets_->emplace_back(base_offset, member_offset.Uint32Value());
1845     }
1846   }
1847 
1848   ALWAYS_INLINE
operator ()(ObjPtr<mirror::Class> klass,ObjPtr<mirror::Reference> ref) const1849   void operator()([[maybe_unused]] ObjPtr<mirror::Class> klass, ObjPtr<mirror::Reference> ref) const
1850       REQUIRES_SHARED(Locks::mutator_lock_) {
1851     operator()(ref, mirror::Reference::ReferentOffset(), /* is_static */ false);
1852   }
1853 
1854  private:
1855   const ImageWriter* const image_writer_;
1856   const size_t oat_index_;
1857   dchecked_vector<AppImageReferenceOffsetInfo>* const string_reference_offsets_;
1858   const ObjPtr<mirror::Object> current_obj_;
1859 };
1860 
1861 class ImageWriter::LayoutHelper::VisitReferencesVisitor {
1862  public:
VisitReferencesVisitor(LayoutHelper * helper,size_t oat_index)1863   VisitReferencesVisitor(LayoutHelper* helper, size_t oat_index)
1864       : helper_(helper), oat_index_(oat_index) {}
1865 
1866   // We do not visit native roots. These are handled with other logic.
VisitRootIfNonNull(mirror::CompressedReference<mirror::Object> * root) const1867   void VisitRootIfNonNull(
1868       [[maybe_unused]] mirror::CompressedReference<mirror::Object>* root) const {
1869     LOG(FATAL) << "UNREACHABLE";
1870   }
VisitRoot(mirror::CompressedReference<mirror::Object> * root) const1871   void VisitRoot([[maybe_unused]] mirror::CompressedReference<mirror::Object>* root) const {
1872     LOG(FATAL) << "UNREACHABLE";
1873   }
1874 
operator ()(ObjPtr<mirror::Object> obj,MemberOffset offset,bool is_static) const1875   ALWAYS_INLINE void operator()(ObjPtr<mirror::Object> obj,
1876                                 MemberOffset offset,
1877                                 [[maybe_unused]] bool is_static) const
1878       REQUIRES_SHARED(Locks::mutator_lock_) {
1879     mirror::Object* ref =
1880         obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(offset);
1881     VisitReference(ref);
1882   }
1883 
operator ()(ObjPtr<mirror::Class> klass,ObjPtr<mirror::Reference> ref) const1884   ALWAYS_INLINE void operator()([[maybe_unused]] ObjPtr<mirror::Class> klass,
1885                                 ObjPtr<mirror::Reference> ref) const
1886       REQUIRES_SHARED(Locks::mutator_lock_) {
1887     operator()(ref, mirror::Reference::ReferentOffset(), /* is_static */ false);
1888   }
1889 
1890  private:
VisitReference(mirror::Object * ref) const1891   void VisitReference(mirror::Object* ref) const REQUIRES_SHARED(Locks::mutator_lock_) {
1892     if (helper_->TryAssignBinSlot(ref, oat_index_)) {
1893       // Remember how many objects we're adding at the front of the queue as we want
1894       // to reverse that range to process these references in the order of addition.
1895       helper_->work_queue_.emplace_front(ref, oat_index_);
1896     }
1897     if (ClassLinker::kAppImageMayContainStrings &&
1898         helper_->image_writer_->compiler_options_.IsAppImage() &&
1899         helper_->image_writer_->IsInternedAppImageStringReference(ref)) {
1900       helper_->image_writer_->image_infos_[oat_index_].num_string_references_ += 1u;
1901     }
1902   }
1903 
1904   LayoutHelper* const helper_;
1905   const size_t oat_index_;
1906 };
1907 
1908 // Visit method pointer arrays in `klass` that were not inherited from its superclass.
1909 template <typename Visitor>
VisitNewMethodPointerArrays(ObjPtr<mirror::Class> klass,Visitor && visitor)1910 static void VisitNewMethodPointerArrays(ObjPtr<mirror::Class> klass, Visitor&& visitor)
1911     REQUIRES_SHARED(Locks::mutator_lock_) {
1912   ObjPtr<mirror::Class> super = klass->GetSuperClass<kVerifyNone, kWithoutReadBarrier>();
1913   ObjPtr<mirror::PointerArray> vtable = klass->GetVTable<kVerifyNone, kWithoutReadBarrier>();
1914   if (vtable != nullptr &&
1915       (super == nullptr || vtable != super->GetVTable<kVerifyNone, kWithoutReadBarrier>())) {
1916     visitor(vtable);
1917   }
1918   int32_t iftable_count = klass->GetIfTableCount();
1919   int32_t super_iftable_count = (super != nullptr) ? super->GetIfTableCount() : 0;
1920   ObjPtr<mirror::IfTable> iftable = klass->GetIfTable<kVerifyNone, kWithoutReadBarrier>();
1921   ObjPtr<mirror::IfTable> super_iftable =
1922       (super != nullptr) ? super->GetIfTable<kVerifyNone, kWithoutReadBarrier>() : nullptr;
1923   for (int32_t i = 0; i < iftable_count; ++i) {
1924     ObjPtr<mirror::PointerArray> methods =
1925         iftable->GetMethodArrayOrNull<kVerifyNone, kWithoutReadBarrier>(i);
1926     ObjPtr<mirror::PointerArray> super_methods = (i < super_iftable_count)
1927         ? super_iftable->GetMethodArrayOrNull<kVerifyNone, kWithoutReadBarrier>(i)
1928         : nullptr;
1929     if (methods != super_methods) {
1930       DCHECK(methods != nullptr);
1931       if (i < super_iftable_count) {
1932         DCHECK(super_methods != nullptr);
1933         DCHECK_EQ(methods->GetLength(), super_methods->GetLength());
1934       }
1935       visitor(methods);
1936     }
1937   }
1938 }
1939 
ProcessDexFileObjects(Thread * self)1940 void ImageWriter::LayoutHelper::ProcessDexFileObjects(Thread* self) {
1941   Runtime* runtime = Runtime::Current();
1942   ClassLinker* class_linker = runtime->GetClassLinker();
1943   const CompilerOptions& compiler_options = image_writer_->compiler_options_;
1944   JavaVMExt* vm = down_cast<JNIEnvExt*>(self->GetJniEnv())->GetVm();
1945 
1946   // To ensure deterministic output, populate the work queue with objects in a pre-defined order.
1947   // Note: If we decide to implement a profile-guided layout, this is the place to do so.
1948 
1949   // Get initial work queue with the image classes and assign their bin slots.
1950   CollectClassesVisitor visitor(image_writer_);
1951   {
1952     WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
1953     if (compiler_options.IsBootImage() || compiler_options.IsBootImageExtension()) {
1954       // No need to filter based on class loader, boot class table contains only
1955       // classes defined by the boot class loader.
1956       ClassTable* class_table = class_linker->boot_class_table_.get();
1957       class_table->Visit<kWithoutReadBarrier>(visitor);
1958     } else {
1959       // No need to visit boot class table as there are no classes there for the app image.
1960       for (const ClassLinker::ClassLoaderData& data : class_linker->class_loaders_) {
1961         auto class_loader =
1962             DecodeWeakGlobalWithoutRB<mirror::ClassLoader>(vm, self, data.weak_root);
1963         if (class_loader != nullptr) {
1964           ClassTable* class_table = class_loader->GetClassTable();
1965           if (class_table != nullptr) {
1966             // Visit only classes defined in this class loader (avoid visiting multiple times).
1967             auto filtering_visitor = [&visitor, class_loader](ObjPtr<mirror::Class> klass)
1968                 REQUIRES_SHARED(Locks::mutator_lock_) {
1969               if (klass->GetClassLoader<kVerifyNone, kWithoutReadBarrier>() == class_loader) {
1970                 visitor(klass);
1971               }
1972               return true;
1973             };
1974             class_table->Visit<kWithoutReadBarrier>(filtering_visitor);
1975           }
1976         }
1977       }
1978     }
1979   }
1980   DCHECK(work_queue_.empty());
1981   work_queue_ = visitor.ProcessCollectedClasses(self);
1982   for (const std::pair<ObjPtr<mirror::Object>, size_t>& entry : work_queue_) {
1983     DCHECK(entry.first != nullptr);
1984     ObjPtr<mirror::Class> klass = entry.first->AsClass();
1985     size_t oat_index = entry.second;
1986     image_writer_->RecordNativeRelocations(klass, oat_index);
1987     AssignImageBinSlot(klass.Ptr(), oat_index);
1988 
1989     auto method_pointer_array_visitor =
1990         [&](ObjPtr<mirror::PointerArray> pointer_array) REQUIRES_SHARED(Locks::mutator_lock_) {
1991           constexpr Bin bin = kBinObjects ? Bin::kInternalClean : Bin::kRegular;
1992           AssignImageBinSlot(pointer_array.Ptr(), oat_index, bin);
1993           // No need to add to the work queue. The class reference, if not in the boot image
1994           // (that is, when compiling the primary boot image), is already in the work queue.
1995         };
1996     VisitNewMethodPointerArrays(klass, method_pointer_array_visitor);
1997   }
1998 
1999   // Assign bin slots to dex caches.
2000   {
2001     ReaderMutexLock mu(self, *Locks::dex_lock_);
2002     for (const DexFile* dex_file : compiler_options.GetDexFilesForOatFile()) {
2003       auto it = image_writer_->dex_file_oat_index_map_.find(dex_file);
2004       DCHECK(it != image_writer_->dex_file_oat_index_map_.end()) << dex_file->GetLocation();
2005       const size_t oat_index = it->second;
2006       // Assign bin slot to this file's dex cache and add it to the end of the work queue.
2007       auto dcd_it = class_linker->GetDexCachesData().find(dex_file);
2008       DCHECK(dcd_it != class_linker->GetDexCachesData().end()) << dex_file->GetLocation();
2009       auto dex_cache =
2010           DecodeWeakGlobalWithoutRB<mirror::DexCache>(vm, self, dcd_it->second.weak_root);
2011       DCHECK(dex_cache != nullptr);
2012       bool assigned = TryAssignBinSlot(dex_cache, oat_index);
2013       DCHECK(assigned);
2014       work_queue_.emplace_back(dex_cache, oat_index);
2015     }
2016   }
2017 
2018   // Assign interns to images depending on the first dex file they appear in.
2019   // Record those that do not have a StringId in any dex file.
2020   ProcessInterns(self);
2021 
2022   // Since classes and dex caches have been assigned to their bins, when we process a class
2023   // we do not follow through the class references or dex caches, so we correctly process
2024   // only objects actually belonging to that class before taking a new class from the queue.
2025   // If multiple class statics reference the same object (directly or indirectly), the object
2026   // is treated as belonging to the first encountered referencing class.
2027   ProcessWorkQueue();
2028 }
2029 
ProcessRoots(Thread * self)2030 void ImageWriter::LayoutHelper::ProcessRoots(Thread* self) {
2031   // Assign bin slots to the image roots and boot image live objects, add them to the work queue
2032   // and process the work queue. These objects reference other objects needed for the image, for
2033   // example the array of dex cache references, or the pre-allocated exceptions for the boot image.
2034   DCHECK(work_queue_.empty());
2035 
2036   constexpr Bin clean_bin = kBinObjects ? Bin::kInternalClean : Bin::kRegular;
2037   size_t num_oat_files = image_writer_->oat_filenames_.size();
2038   JavaVMExt* vm = down_cast<JNIEnvExt*>(self->GetJniEnv())->GetVm();
2039   for (size_t oat_index = 0; oat_index != num_oat_files; ++oat_index) {
2040     // Put image roots and dex caches into `clean_bin`.
2041     auto image_roots = DecodeGlobalWithoutRB<mirror::ObjectArray<mirror::Object>>(
2042        vm, image_writer_->image_roots_[oat_index]);
2043     AssignImageBinSlot(image_roots, oat_index, clean_bin);
2044     work_queue_.emplace_back(image_roots, oat_index);
2045     // Do not rely on the `work_queue_` for dex cache arrays, it would assign a different bin.
2046     ObjPtr<ObjectArray<Object>> dex_caches = ObjPtr<ObjectArray<Object>>::DownCast(
2047         image_roots->GetWithoutChecks<kVerifyNone, kWithoutReadBarrier>(ImageHeader::kDexCaches));
2048     AssignImageBinSlot(dex_caches, oat_index, clean_bin);
2049     work_queue_.emplace_back(dex_caches, oat_index);
2050   }
2051   // Do not rely on the `work_queue_` for boot image live objects, it would assign a different bin.
2052   if (image_writer_->compiler_options_.IsBootImage()) {
2053     ObjPtr<mirror::ObjectArray<mirror::Object>> boot_image_live_objects =
2054         image_writer_->boot_image_live_objects_;
2055     AssignImageBinSlot(boot_image_live_objects, GetDefaultOatIndex(), clean_bin);
2056     work_queue_.emplace_back(boot_image_live_objects, GetDefaultOatIndex());
2057   }
2058 
2059   ProcessWorkQueue();
2060 }
2061 
ProcessInterns(Thread * self)2062 void ImageWriter::LayoutHelper::ProcessInterns(Thread* self) {
2063   // String bins are empty at this point.
2064   DCHECK(std::all_of(bin_objects_.begin(),
2065                      bin_objects_.end(),
2066                      [](const auto& bins) {
2067                        return bins[enum_cast<size_t>(Bin::kString)].empty();
2068                      }));
2069 
2070   // There is only one non-boot image intern table and it's the last one.
2071   InternTable* const intern_table = Runtime::Current()->GetInternTable();
2072   MutexLock mu(self, *Locks::intern_table_lock_);
2073   DCHECK_EQ(std::count_if(intern_table->strong_interns_.tables_.begin(),
2074                           intern_table->strong_interns_.tables_.end(),
2075                           [](const InternTable::Table::InternalTable& table) {
2076                             return !table.IsBootImage();
2077                           }),
2078             1);
2079   DCHECK(!intern_table->strong_interns_.tables_.back().IsBootImage());
2080   const InternTable::UnorderedSet& intern_set = intern_table->strong_interns_.tables_.back().set_;
2081 
2082   // Assign bin slots to all interns with a corresponding StringId in one of the input dex files.
2083   ImageWriter* image_writer = image_writer_;
2084   for (const DexFile* dex_file : image_writer->compiler_options_.GetDexFilesForOatFile()) {
2085     auto it = image_writer->dex_file_oat_index_map_.find(dex_file);
2086     DCHECK(it != image_writer->dex_file_oat_index_map_.end()) << dex_file->GetLocation();
2087     const size_t oat_index = it->second;
2088     // Assign bin slots for strings defined in this dex file in StringId (lexicographical) order.
2089     for (size_t i = 0, count = dex_file->NumStringIds(); i != count; ++i) {
2090       uint32_t utf16_length;
2091       const char* utf8_data = dex_file->GetStringDataAndUtf16Length(dex::StringIndex(i),
2092                                                                     &utf16_length);
2093       uint32_t hash = InternTable::Utf8String::Hash(utf16_length, utf8_data);
2094       auto intern_it =
2095           intern_set.FindWithHash(InternTable::Utf8String(utf16_length, utf8_data), hash);
2096       if (intern_it != intern_set.end()) {
2097         mirror::String* string = intern_it->Read<kWithoutReadBarrier>();
2098         DCHECK(string != nullptr);
2099         DCHECK(!image_writer->IsInBootImage(string));
2100         if (!image_writer->IsImageBinSlotAssigned(string)) {
2101           Bin bin = AssignImageBinSlot(string, oat_index);
2102           DCHECK_EQ(bin, kBinObjects ? Bin::kString : Bin::kRegular);
2103         } else {
2104           // We have already seen this string in a previous dex file.
2105           DCHECK(dex_file != image_writer->compiler_options_.GetDexFilesForOatFile().front());
2106         }
2107       }
2108     }
2109   }
2110 
2111   // String bins have been filled with dex file interns. Record their numbers in image infos.
2112   DCHECK_EQ(bin_objects_.size(), image_writer_->image_infos_.size());
2113   size_t total_dex_file_interns = 0u;
2114   for (size_t oat_index = 0, size = bin_objects_.size(); oat_index != size; ++oat_index) {
2115     size_t num_dex_file_interns = bin_objects_[oat_index][enum_cast<size_t>(Bin::kString)].size();
2116     ImageInfo& image_info = image_writer_->GetImageInfo(oat_index);
2117     DCHECK_EQ(image_info.intern_table_size_, 0u);
2118     image_info.intern_table_size_ = num_dex_file_interns;
2119     total_dex_file_interns += num_dex_file_interns;
2120   }
2121 
2122   // Collect interns that do not have a corresponding StringId in any of the input dex files.
2123   non_dex_file_interns_.reserve(intern_set.size() - total_dex_file_interns);
2124   for (const GcRoot<mirror::String>& root : intern_set) {
2125     mirror::String* string = root.Read<kWithoutReadBarrier>();
2126     if (!image_writer->IsImageBinSlotAssigned(string)) {
2127       non_dex_file_interns_.push_back(string);
2128     }
2129   }
2130   DCHECK_EQ(intern_set.size(), total_dex_file_interns + non_dex_file_interns_.size());
2131 }
2132 
FinalizeInternTables()2133 void ImageWriter::LayoutHelper::FinalizeInternTables() {
2134   // Remove interns that do not have a bin slot assigned. These correspond
2135   // to the DexCache locations excluded in VerifyImageBinSlotsAssigned().
2136   ImageWriter* image_writer = image_writer_;
2137   auto retained_end = std::remove_if(
2138       non_dex_file_interns_.begin(),
2139       non_dex_file_interns_.end(),
2140       [=](mirror::String* string) REQUIRES_SHARED(Locks::mutator_lock_) {
2141         return !image_writer->IsImageBinSlotAssigned(string);
2142       });
2143   non_dex_file_interns_.resize(std::distance(non_dex_file_interns_.begin(), retained_end));
2144 
2145   // Sort `non_dex_file_interns_` based on oat index and bin offset.
2146   ArrayRef<mirror::String*> non_dex_file_interns(non_dex_file_interns_);
2147   std::sort(non_dex_file_interns.begin(),
2148             non_dex_file_interns.end(),
2149             [=](mirror::String* lhs, mirror::String* rhs) REQUIRES_SHARED(Locks::mutator_lock_) {
2150               size_t lhs_oat_index = image_writer->GetOatIndex(lhs);
2151               size_t rhs_oat_index = image_writer->GetOatIndex(rhs);
2152               if (lhs_oat_index != rhs_oat_index) {
2153                 return lhs_oat_index < rhs_oat_index;
2154               }
2155               BinSlot lhs_bin_slot = image_writer->GetImageBinSlot(lhs, lhs_oat_index);
2156               BinSlot rhs_bin_slot = image_writer->GetImageBinSlot(rhs, rhs_oat_index);
2157               return lhs_bin_slot < rhs_bin_slot;
2158             });
2159 
2160   // Allocate and fill intern tables.
2161   size_t ndfi_index = 0u;
2162   DCHECK_EQ(bin_objects_.size(), image_writer->image_infos_.size());
2163   for (size_t oat_index = 0, size = bin_objects_.size(); oat_index != size; ++oat_index) {
2164     // Find the end of `non_dex_file_interns` for this oat file.
2165     size_t ndfi_end = ndfi_index;
2166     while (ndfi_end != non_dex_file_interns.size() &&
2167            image_writer->GetOatIndex(non_dex_file_interns[ndfi_end]) == oat_index) {
2168       ++ndfi_end;
2169     }
2170 
2171     // Calculate final intern table size.
2172     ImageInfo& image_info = image_writer->GetImageInfo(oat_index);
2173     DCHECK_EQ(image_info.intern_table_bytes_, 0u);
2174     size_t num_dex_file_interns = image_info.intern_table_size_;
2175     size_t num_non_dex_file_interns = ndfi_end - ndfi_index;
2176     image_info.intern_table_size_ = num_dex_file_interns + num_non_dex_file_interns;
2177     if (image_info.intern_table_size_ != 0u) {
2178       // Make sure the intern table shall be full by allocating a buffer of the right size.
2179       size_t buffer_size = static_cast<size_t>(
2180           ceil(image_info.intern_table_size_ / kImageInternTableMaxLoadFactor));
2181       image_info.intern_table_buffer_.reset(new GcRoot<mirror::String>[buffer_size]);
2182       DCHECK(image_info.intern_table_buffer_ != nullptr);
2183       image_info.intern_table_.emplace(kImageInternTableMinLoadFactor,
2184                                        kImageInternTableMaxLoadFactor,
2185                                        image_info.intern_table_buffer_.get(),
2186                                        buffer_size);
2187 
2188       // Fill the intern table. Dex file interns are at the start of the bin_objects[.][kString].
2189       InternTable::UnorderedSet& table = *image_info.intern_table_;
2190       const auto& oat_file_strings = bin_objects_[oat_index][enum_cast<size_t>(Bin::kString)];
2191       DCHECK_LE(num_dex_file_interns, oat_file_strings.size());
2192       ArrayRef<mirror::Object* const> dex_file_interns(
2193           oat_file_strings.data(), num_dex_file_interns);
2194       for (mirror::Object* string : dex_file_interns) {
2195         bool inserted = table.insert(GcRoot<mirror::String>(string->AsString())).second;
2196         DCHECK(inserted) << "String already inserted: " << string->AsString()->ToModifiedUtf8();
2197       }
2198       ArrayRef<mirror::String*> current_non_dex_file_interns =
2199           non_dex_file_interns.SubArray(ndfi_index, num_non_dex_file_interns);
2200       for (mirror::String* string : current_non_dex_file_interns) {
2201         bool inserted = table.insert(GcRoot<mirror::String>(string)).second;
2202         DCHECK(inserted) << "String already inserted: " << string->ToModifiedUtf8();
2203       }
2204 
2205       // Record the intern table size in bytes.
2206       image_info.intern_table_bytes_ = table.WriteToMemory(nullptr);
2207     }
2208 
2209     ndfi_index = ndfi_end;
2210   }
2211 }
2212 
ProcessWorkQueue()2213 void ImageWriter::LayoutHelper::ProcessWorkQueue() {
2214   while (!work_queue_.empty()) {
2215     std::pair<ObjPtr<mirror::Object>, size_t> pair = work_queue_.front();
2216     work_queue_.pop_front();
2217     VisitReferences(/*obj=*/ pair.first, /*oat_index=*/ pair.second);
2218   }
2219 }
2220 
SortDirtyObjects(const HashMap<mirror::Object *,uint32_t> & dirty_objects,size_t oat_index)2221 void ImageWriter::LayoutHelper::SortDirtyObjects(
2222     const HashMap<mirror::Object*, uint32_t>& dirty_objects, size_t oat_index) {
2223   constexpr Bin bin = Bin::kKnownDirty;
2224   ImageInfo& image_info = image_writer_->GetImageInfo(oat_index);
2225 
2226   dchecked_vector<mirror::Object*>& known_dirty = bin_objects_[oat_index][enum_cast<size_t>(bin)];
2227   if (known_dirty.empty()) {
2228     return;
2229   }
2230 
2231   // Collect objects and their combined sort_keys.
2232   // Combined key contains sort_key and original offset to ensure deterministic sorting.
2233   using CombinedKey = std::pair<uint32_t, uint32_t>;
2234   using ObjSortPair = std::pair<mirror::Object*, CombinedKey>;
2235   dchecked_vector<ObjSortPair> objects;
2236   objects.reserve(known_dirty.size());
2237   for (mirror::Object* obj : known_dirty) {
2238     const BinSlot bin_slot = image_writer_->GetImageBinSlot(obj, oat_index);
2239     const uint32_t original_offset = bin_slot.GetOffset();
2240     const auto it = dirty_objects.find(obj);
2241     const uint32_t sort_key = (it != dirty_objects.end()) ? it->second : 0;
2242     objects.emplace_back(obj, std::make_pair(sort_key, original_offset));
2243   }
2244   // Sort by combined sort_key.
2245   std::sort(std::begin(objects), std::end(objects), [&](ObjSortPair& lhs, ObjSortPair& rhs) {
2246     return lhs.second < rhs.second;
2247   });
2248 
2249   // Fill known_dirty objects in sorted order, update bin offsets.
2250   known_dirty.clear();
2251   size_t offset = 0;
2252   for (const ObjSortPair& entry : objects) {
2253     mirror::Object* obj = entry.first;
2254 
2255     known_dirty.push_back(obj);
2256     image_writer_->UpdateImageBinSlotOffset(obj, oat_index, offset);
2257 
2258     const size_t aligned_object_size = RoundUp(obj->SizeOf<kVerifyNone>(), kObjectAlignment);
2259     offset += aligned_object_size;
2260   }
2261   DCHECK_EQ(offset, image_info.GetBinSlotSize(bin));
2262 }
2263 
VerifyImageBinSlotsAssigned()2264 void ImageWriter::LayoutHelper::VerifyImageBinSlotsAssigned() {
2265   dchecked_vector<mirror::Object*> carveout;
2266   JavaVMExt* vm = nullptr;
2267   if (image_writer_->compiler_options_.IsAppImage()) {
2268     // Exclude boot class path dex caches that are not part of the boot image.
2269     // Also exclude their locations if they have not been visited through another path.
2270     ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
2271     Thread* self = Thread::Current();
2272     vm = down_cast<JNIEnvExt*>(self->GetJniEnv())->GetVm();
2273     ReaderMutexLock mu(self, *Locks::dex_lock_);
2274     for (const auto& entry : class_linker->GetDexCachesData()) {
2275       const ClassLinker::DexCacheData& data = entry.second;
2276       auto dex_cache = DecodeWeakGlobalWithoutRB<mirror::DexCache>(vm, self, data.weak_root);
2277       if (dex_cache == nullptr ||
2278           image_writer_->IsInBootImage(dex_cache.Ptr()) ||
2279           ContainsElement(image_writer_->compiler_options_.GetDexFilesForOatFile(),
2280                           dex_cache->GetDexFile())) {
2281         continue;
2282       }
2283       CHECK(!image_writer_->IsImageBinSlotAssigned(dex_cache.Ptr()));
2284       carveout.push_back(dex_cache.Ptr());
2285       ObjPtr<mirror::String> location = dex_cache->GetLocation<kVerifyNone, kWithoutReadBarrier>();
2286       if (!image_writer_->IsImageBinSlotAssigned(location.Ptr())) {
2287         carveout.push_back(location.Ptr());
2288       }
2289     }
2290   }
2291 
2292   dchecked_vector<mirror::Object*> missed_objects;
2293   auto ensure_bin_slots_assigned = [&](mirror::Object* obj)
2294       REQUIRES_SHARED(Locks::mutator_lock_) {
2295     if (!image_writer_->IsInBootImage(obj)) {
2296       if (!UNLIKELY(image_writer_->IsImageBinSlotAssigned(obj))) {
2297         // Ignore the `carveout` objects.
2298         if (ContainsElement(carveout, obj)) {
2299           return;
2300         }
2301         // Ignore finalizer references for the dalvik.system.DexFile objects referenced by
2302         // the app class loader.
2303         ObjPtr<mirror::Class> klass = obj->GetClass<kVerifyNone, kWithoutReadBarrier>();
2304         if (klass->IsFinalizerReferenceClass<kVerifyNone>()) {
2305           ObjPtr<mirror::Class> reference_class =
2306               klass->GetSuperClass<kVerifyNone, kWithoutReadBarrier>();
2307           DCHECK(reference_class->DescriptorEquals("Ljava/lang/ref/Reference;"));
2308           ArtField* ref_field = reference_class->FindDeclaredInstanceField(
2309               "referent", "Ljava/lang/Object;");
2310           CHECK(ref_field != nullptr);
2311           ObjPtr<mirror::Object> ref = ref_field->GetObject<kWithoutReadBarrier>(obj);
2312           CHECK(ref != nullptr);
2313           CHECK(image_writer_->IsImageBinSlotAssigned(ref.Ptr()));
2314           ObjPtr<mirror::Class> ref_klass = ref->GetClass<kVerifyNone, kWithoutReadBarrier>();
2315           CHECK(ref_klass == WellKnownClasses::dalvik_system_DexFile.Get<kWithoutReadBarrier>());
2316           // Note: The app class loader is used only for checking against the runtime
2317           // class loader, the dex file cookie is cleared and therefore we do not need
2318           // to run the finalizer even if we implement app image objects collection.
2319           ArtField* field = WellKnownClasses::dalvik_system_DexFile_cookie;
2320           CHECK(field->GetObject<kWithoutReadBarrier>(ref) == nullptr);
2321           return;
2322         }
2323         if (klass->IsStringClass()) {
2324           // Ignore interned strings. These may come from reflection interning method names.
2325           // TODO: Make dex file strings weak interns and GC them before writing the image.
2326           if (IsStronglyInternedString(obj->AsString())) {
2327             return;
2328           }
2329         }
2330         missed_objects.push_back(obj);
2331       }
2332     }
2333   };
2334   Runtime::Current()->GetHeap()->VisitObjects(ensure_bin_slots_assigned);
2335   if (!missed_objects.empty()) {
2336     const gc::Verification* v = Runtime::Current()->GetHeap()->GetVerification();
2337     size_t num_missed_objects = missed_objects.size();
2338     size_t num_paths = std::min<size_t>(num_missed_objects, 5u);  // Do not flood the output.
2339     ArrayRef<mirror::Object*> missed_objects_head =
2340         ArrayRef<mirror::Object*>(missed_objects).SubArray(/*pos=*/ 0u, /*length=*/ num_paths);
2341     for (mirror::Object* obj : missed_objects_head) {
2342       LOG(ERROR) << "Image object without assigned bin slot: "
2343           << mirror::Object::PrettyTypeOf(obj) << " " << obj
2344           << " " << v->FirstPathFromRootSet(obj);
2345     }
2346     LOG(FATAL) << "Found " << num_missed_objects << " objects without assigned bin slots.";
2347   }
2348 }
2349 
FinalizeBinSlotOffsets()2350 void ImageWriter::LayoutHelper::FinalizeBinSlotOffsets() {
2351   // Calculate bin slot offsets and adjust for region padding if needed.
2352   const size_t region_size = image_writer_->region_size_;
2353   const size_t num_image_infos = image_writer_->image_infos_.size();
2354   for (size_t oat_index = 0; oat_index != num_image_infos; ++oat_index) {
2355     ImageInfo& image_info = image_writer_->image_infos_[oat_index];
2356     size_t bin_offset = image_writer_->image_objects_offset_begin_;
2357 
2358     for (size_t i = 0; i != kNumberOfBins; ++i) {
2359       Bin bin = enum_cast<Bin>(i);
2360       switch (bin) {
2361         case Bin::kArtMethodClean:
2362         case Bin::kArtMethodDirty: {
2363           bin_offset = RoundUp(bin_offset, ArtMethod::Alignment(image_writer_->target_ptr_size_));
2364           break;
2365         }
2366         case Bin::kImTable:
2367         case Bin::kIMTConflictTable: {
2368           bin_offset = RoundUp(bin_offset, static_cast<size_t>(image_writer_->target_ptr_size_));
2369           break;
2370         }
2371         default: {
2372           // Normal alignment.
2373         }
2374       }
2375       image_info.bin_slot_offsets_[i] = bin_offset;
2376 
2377       // If the bin is for mirror objects, we may need to add region padding and update offsets.
2378       if (i < enum_cast<size_t>(Bin::kMirrorCount) && region_size != 0u) {
2379         const size_t offset_after_header = bin_offset - sizeof(ImageHeader);
2380         size_t remaining_space =
2381             RoundUp(offset_after_header + 1u, region_size) - offset_after_header;
2382         // Exercise the loop below in debug builds to get coverage.
2383         if (kIsDebugBuild || remaining_space < image_info.bin_slot_sizes_[i]) {
2384           // The bin crosses a region boundary. Add padding if needed.
2385           size_t object_offset = 0u;
2386           size_t padding = 0u;
2387           for (mirror::Object* object : bin_objects_[oat_index][i]) {
2388             BinSlot bin_slot = image_writer_->GetImageBinSlot(object, oat_index);
2389             DCHECK_EQ(enum_cast<size_t>(bin_slot.GetBin()), i);
2390             DCHECK_EQ(bin_slot.GetOffset() + padding, object_offset);
2391             size_t object_size = RoundUp(object->SizeOf<kVerifyNone>(), kObjectAlignment);
2392 
2393             auto add_padding = [&](bool tail_region) {
2394               DCHECK_NE(remaining_space, 0u);
2395               DCHECK_LT(remaining_space, region_size);
2396               DCHECK_ALIGNED(remaining_space, kObjectAlignment);
2397               // TODO When copying to heap regions, leave the tail region padding zero-filled.
2398               if (!tail_region || true) {
2399                 image_info.padding_offsets_.push_back(bin_offset + object_offset);
2400               }
2401               image_info.bin_slot_sizes_[i] += remaining_space;
2402               padding += remaining_space;
2403               object_offset += remaining_space;
2404               remaining_space = region_size;
2405             };
2406             if (object_size > remaining_space) {
2407               // Padding needed if we're not at region boundary (with a multi-region object).
2408               if (remaining_space != region_size) {
2409                 // TODO: Instead of adding padding, we should consider reordering the bins
2410                 // or objects to reduce wasted space.
2411                 add_padding(/*tail_region=*/ false);
2412               }
2413               DCHECK_EQ(remaining_space, region_size);
2414               // For huge objects, adjust the remaining space to hold the object and some more.
2415               if (object_size > region_size) {
2416                 remaining_space = RoundUp(object_size + 1u, region_size);
2417               }
2418             } else if (remaining_space == object_size) {
2419               // Move to the next region, no padding needed.
2420               remaining_space += region_size;
2421             }
2422             DCHECK_GT(remaining_space, object_size);
2423             remaining_space -= object_size;
2424             image_writer_->UpdateImageBinSlotOffset(object, oat_index, object_offset);
2425             object_offset += object_size;
2426             // Add padding to the tail region of huge objects if not region-aligned.
2427             if (object_size > region_size && remaining_space != region_size) {
2428               DCHECK(!IsAlignedParam(object_size, region_size));
2429               add_padding(/*tail_region=*/ true);
2430             }
2431           }
2432           image_writer_->region_alignment_wasted_ += padding;
2433           image_info.image_end_ += padding;
2434         }
2435       }
2436       bin_offset += image_info.bin_slot_sizes_[i];
2437     }
2438     // NOTE: There may be additional padding between the bin slots and the intern table.
2439     DCHECK_EQ(
2440         image_info.image_end_,
2441         image_info.GetBinSizeSum(Bin::kMirrorCount) + image_writer_->image_objects_offset_begin_);
2442   }
2443 
2444   VLOG(image) << "Space wasted for region alignment " << image_writer_->region_alignment_wasted_;
2445 }
2446 
CollectStringReferenceInfo()2447 void ImageWriter::LayoutHelper::CollectStringReferenceInfo() {
2448   size_t total_string_refs = 0u;
2449 
2450   const size_t num_image_infos = image_writer_->image_infos_.size();
2451   for (size_t oat_index = 0; oat_index != num_image_infos; ++oat_index) {
2452     ImageInfo& image_info = image_writer_->image_infos_[oat_index];
2453     DCHECK(image_info.string_reference_offsets_.empty());
2454     image_info.string_reference_offsets_.reserve(image_info.num_string_references_);
2455 
2456     for (size_t i = 0; i < enum_cast<size_t>(Bin::kMirrorCount); ++i) {
2457       for (mirror::Object* obj : bin_objects_[oat_index][i]) {
2458         CollectStringReferenceVisitor visitor(image_writer_,
2459                                               oat_index,
2460                                               &image_info.string_reference_offsets_,
2461                                               obj);
2462         /*
2463          * References to managed strings can occur either in the managed heap or in
2464          * native memory regions. Information about managed references is collected
2465          * by the CollectStringReferenceVisitor and directly added to the image info.
2466          *
2467          * Native references to managed strings can only occur through DexCache
2468          * objects. This is verified by the visitor in debug mode and the references
2469          * are collected separately below.
2470          */
2471         obj->VisitReferences</*kVisitNativeRoots=*/ kIsDebugBuild,
2472                              kVerifyNone,
2473                              kWithoutReadBarrier>(visitor, visitor);
2474       }
2475     }
2476 
2477     total_string_refs += image_info.string_reference_offsets_.size();
2478 
2479     // Check that we collected the same number of string references as we saw in the previous pass.
2480     CHECK_EQ(image_info.string_reference_offsets_.size(), image_info.num_string_references_);
2481   }
2482 
2483   VLOG(compiler) << "Dex2Oat:AppImage:stringReferences = " << total_string_refs;
2484 }
2485 
VisitReferences(ObjPtr<mirror::Object> obj,size_t oat_index)2486 void ImageWriter::LayoutHelper::VisitReferences(ObjPtr<mirror::Object> obj, size_t oat_index) {
2487   size_t old_work_queue_size = work_queue_.size();
2488   VisitReferencesVisitor visitor(this, oat_index);
2489   // Walk references and assign bin slots for them.
2490   obj->VisitReferences</*kVisitNativeRoots=*/ false, kVerifyNone, kWithoutReadBarrier>(
2491       visitor,
2492       visitor);
2493   // Put the added references in the queue in the order in which they were added.
2494   // The visitor just pushes them to the front as it visits them.
2495   DCHECK_LE(old_work_queue_size, work_queue_.size());
2496   size_t num_added = work_queue_.size() - old_work_queue_size;
2497   std::reverse(work_queue_.begin(), work_queue_.begin() + num_added);
2498 }
2499 
TryAssignBinSlot(ObjPtr<mirror::Object> obj,size_t oat_index)2500 bool ImageWriter::LayoutHelper::TryAssignBinSlot(ObjPtr<mirror::Object> obj, size_t oat_index) {
2501   if (obj == nullptr || image_writer_->IsInBootImage(obj.Ptr())) {
2502     // Object is null or already in the image, there is no work to do.
2503     return false;
2504   }
2505   bool assigned = false;
2506   if (!image_writer_->IsImageBinSlotAssigned(obj.Ptr())) {
2507     AssignImageBinSlot(obj.Ptr(), oat_index);
2508     assigned = true;
2509   }
2510   return assigned;
2511 }
2512 
AssignImageBinSlot(ObjPtr<mirror::Object> object,size_t oat_index)2513 ImageWriter::Bin ImageWriter::LayoutHelper::AssignImageBinSlot(ObjPtr<mirror::Object> object,
2514                                                                size_t oat_index) {
2515   DCHECK(object != nullptr);
2516   Bin bin = image_writer_->GetImageBin(object.Ptr());
2517   AssignImageBinSlot(object.Ptr(), oat_index, bin);
2518   return bin;
2519 }
2520 
AssignImageBinSlot(ObjPtr<mirror::Object> object,size_t oat_index,Bin bin)2521 void ImageWriter::LayoutHelper::AssignImageBinSlot(
2522     ObjPtr<mirror::Object> object, size_t oat_index, Bin bin) {
2523   DCHECK(object != nullptr);
2524   DCHECK(!image_writer_->IsInBootImage(object.Ptr()));
2525   DCHECK(!image_writer_->IsImageBinSlotAssigned(object.Ptr()));
2526   image_writer_->AssignImageBinSlot(object.Ptr(), oat_index, bin);
2527   bin_objects_[oat_index][enum_cast<size_t>(bin)].push_back(object.Ptr());
2528 }
2529 
AssertOnly1Thread()2530 static inline void AssertOnly1Thread() REQUIRES(!Locks::thread_list_lock_) {
2531   if (kIsDebugBuild) {
2532     Runtime::Current()->GetThreadList()->CheckOnly1Thread(Thread::Current());
2533   }
2534 }
2535 
CalculateNewObjectOffsets()2536 void ImageWriter::CalculateNewObjectOffsets() {
2537   Thread* const self = Thread::Current();
2538   Runtime* const runtime = Runtime::Current();
2539   gc::Heap* const heap = runtime->GetHeap();
2540 
2541   AssertOnly1Thread();
2542   // Leave space for the header, but do not write it yet, we need to
2543   // know where image_roots is going to end up
2544   image_objects_offset_begin_ = RoundUp(sizeof(ImageHeader), kObjectAlignment);  // 64-bit-alignment
2545 
2546   // Write the image runtime methods.
2547   image_methods_[ImageHeader::kResolutionMethod] = runtime->GetResolutionMethod();
2548   image_methods_[ImageHeader::kImtConflictMethod] = runtime->GetImtConflictMethod();
2549   image_methods_[ImageHeader::kImtUnimplementedMethod] = runtime->GetImtUnimplementedMethod();
2550   image_methods_[ImageHeader::kSaveAllCalleeSavesMethod] =
2551       runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveAllCalleeSaves);
2552   image_methods_[ImageHeader::kSaveRefsOnlyMethod] =
2553       runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveRefsOnly);
2554   image_methods_[ImageHeader::kSaveRefsAndArgsMethod] =
2555       runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveRefsAndArgs);
2556   image_methods_[ImageHeader::kSaveEverythingMethod] =
2557       runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveEverything);
2558   image_methods_[ImageHeader::kSaveEverythingMethodForClinit] =
2559       runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveEverythingForClinit);
2560   image_methods_[ImageHeader::kSaveEverythingMethodForSuspendCheck] =
2561       runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveEverythingForSuspendCheck);
2562   // Visit image methods first to have the main runtime methods in the first image.
2563   for (auto* m : image_methods_) {
2564     CHECK(m != nullptr);
2565     CHECK(m->IsRuntimeMethod());
2566     DCHECK_EQ(!compiler_options_.IsBootImage(), IsInBootImage(m))
2567         << "Trampolines should be in boot image";
2568     if (!IsInBootImage(m)) {
2569       AssignMethodOffset(m, NativeObjectRelocationType::kRuntimeMethod, GetDefaultOatIndex());
2570     }
2571   }
2572 
2573   // Deflate monitors before we visit roots since deflating acquires the monitor lock. Acquiring
2574   // this lock while holding other locks may cause lock order violations.
2575   {
2576     auto deflate_monitor =
2577         // NO_THREAD_SAFETY_ANALYSIS: We don't really hold mutator_lock_ exclusively.
2578         [](mirror::Object* obj) REQUIRES_SHARED(Locks::mutator_lock_)
2579             NO_THREAD_SAFETY_ANALYSIS { Monitor::Deflate(Thread::Current(), obj); };
2580     heap->VisitObjects(deflate_monitor);
2581     // This does not update the MonitorList, which is thus rendered invalid, and is no longer used.
2582   }
2583 
2584   // From this point on, there shall be no GC anymore and no objects shall be allocated.
2585   // We can now assign a BitSlot to each object and store it in its lockword.
2586 
2587   JavaVMExt* vm = down_cast<JNIEnvExt*>(self->GetJniEnv())->GetVm();
2588   if (compiler_options_.IsBootImage() || compiler_options_.IsBootImageExtension()) {
2589     // Record the address of boot image live objects.
2590     auto image_roots = DecodeGlobalWithoutRB<mirror::ObjectArray<mirror::Object>>(
2591         vm, image_roots_[0]);
2592     boot_image_live_objects_ = ObjPtr<ObjectArray<Object>>::DownCast(
2593         image_roots->GetWithoutChecks<kVerifyNone, kWithoutReadBarrier>(
2594             ImageHeader::kBootImageLiveObjects)).Ptr();
2595   }
2596 
2597   // If dirty_image_objects_ is present - try optimizing object layout.
2598   // Parse dirty-image-objects entries and put them in dirty_objects_ map, which is then used in
2599   // `AssignImageBinSlot` method to put the objects in dirty bin.
2600   if (compiler_options_.IsBootImage() && dirty_image_objects_ != nullptr) {
2601     dirty_objects_ = MatchDirtyObjectPaths(*dirty_image_objects_);
2602     LOG(INFO) << ART_FORMAT("Matched {} out of {} dirty-image-objects",
2603                             dirty_objects_.size(),
2604                             dirty_image_objects_->size());
2605   }
2606 
2607   LayoutHelper layout_helper(this);
2608   layout_helper.ProcessDexFileObjects(self);
2609   layout_helper.ProcessRoots(self);
2610   layout_helper.FinalizeInternTables();
2611 
2612   // Sort objects in dirty bin.
2613   if (!dirty_objects_.empty()) {
2614     for (size_t oat_index = 0; oat_index < image_infos_.size(); ++oat_index) {
2615       layout_helper.SortDirtyObjects(dirty_objects_, oat_index);
2616     }
2617   }
2618 
2619   // Verify that all objects have assigned image bin slots.
2620   layout_helper.VerifyImageBinSlotsAssigned();
2621 
2622   // Finalize bin slot offsets. This may add padding for regions.
2623   layout_helper.FinalizeBinSlotOffsets();
2624 
2625   // Collect string reference info for app images.
2626   if (ClassLinker::kAppImageMayContainStrings && compiler_options_.IsAppImage()) {
2627     layout_helper.CollectStringReferenceInfo();
2628   }
2629 
2630   // Calculate image offsets.
2631   size_t image_offset = 0;
2632   for (ImageInfo& image_info : image_infos_) {
2633     image_info.image_begin_ = global_image_begin_ + image_offset;
2634     image_info.image_offset_ = image_offset;
2635     image_info.image_size_ = RoundUp(image_info.CreateImageSections().first, kElfSegmentAlignment);
2636     // There should be no gaps until the next image.
2637     image_offset += image_info.image_size_;
2638   }
2639 
2640   size_t oat_index = 0;
2641   for (ImageInfo& image_info : image_infos_) {
2642     auto image_roots = DecodeGlobalWithoutRB<mirror::ObjectArray<mirror::Object>>(
2643         vm, image_roots_[oat_index]);
2644     image_info.image_roots_address_ = PointerToLowMemUInt32(GetImageAddress(image_roots.Ptr()));
2645     ++oat_index;
2646   }
2647 
2648   // Update the native relocations by adding their bin sums.
2649   for (auto& pair : native_object_relocations_) {
2650     NativeObjectRelocation& relocation = pair.second;
2651     Bin bin_type = BinTypeForNativeRelocationType(relocation.type);
2652     ImageInfo& image_info = GetImageInfo(relocation.oat_index);
2653     relocation.offset += image_info.GetBinSlotOffset(bin_type);
2654   }
2655 
2656   // Update the JNI stub methods by adding their bin sums.
2657   for (auto& pair : jni_stub_map_) {
2658     JniStubMethodRelocation& relocation = pair.second.second;
2659     constexpr Bin bin_type = Bin::kJniStubMethod;
2660     ImageInfo& image_info = GetImageInfo(relocation.oat_index);
2661     relocation.offset += image_info.GetBinSlotOffset(bin_type);
2662   }
2663 }
2664 
2665 std::pair<size_t, dchecked_vector<ImageSection>>
CreateImageSections() const2666 ImageWriter::ImageInfo::CreateImageSections() const {
2667   dchecked_vector<ImageSection> sections(ImageHeader::kSectionCount);
2668 
2669   // Do not round up any sections here that are represented by the bins since it
2670   // will break offsets.
2671 
2672   /*
2673    * Objects section
2674    */
2675   sections[ImageHeader::kSectionObjects] =
2676       ImageSection(0u, image_end_);
2677 
2678   /*
2679    * Field section
2680    */
2681   sections[ImageHeader::kSectionArtFields] =
2682       ImageSection(GetBinSlotOffset(Bin::kArtField), GetBinSlotSize(Bin::kArtField));
2683 
2684   /*
2685    * Method section
2686    */
2687   sections[ImageHeader::kSectionArtMethods] =
2688       ImageSection(GetBinSlotOffset(Bin::kArtMethodClean),
2689                    GetBinSlotSize(Bin::kArtMethodClean) +
2690                    GetBinSlotSize(Bin::kArtMethodDirty));
2691 
2692   /*
2693    * IMT section
2694    */
2695   sections[ImageHeader::kSectionImTables] =
2696       ImageSection(GetBinSlotOffset(Bin::kImTable), GetBinSlotSize(Bin::kImTable));
2697 
2698   /*
2699    * Conflict Tables section
2700    */
2701   sections[ImageHeader::kSectionIMTConflictTables] =
2702       ImageSection(GetBinSlotOffset(Bin::kIMTConflictTable), GetBinSlotSize(Bin::kIMTConflictTable));
2703 
2704   /*
2705    * Runtime Methods section
2706    */
2707   sections[ImageHeader::kSectionRuntimeMethods] =
2708       ImageSection(GetBinSlotOffset(Bin::kRuntimeMethod), GetBinSlotSize(Bin::kRuntimeMethod));
2709 
2710   /*
2711    * JNI Stub Methods section
2712    */
2713   sections[ImageHeader::kSectionJniStubMethods] =
2714       ImageSection(GetBinSlotOffset(Bin::kJniStubMethod), GetBinSlotSize(Bin::kJniStubMethod));
2715 
2716   /*
2717    * Interned Strings section
2718    */
2719 
2720   // Round up to the alignment the string table expects. See HashSet::WriteToMemory.
2721   size_t cur_pos = RoundUp(sections[ImageHeader::kSectionJniStubMethods].End(), sizeof(uint64_t));
2722 
2723   const ImageSection& interned_strings_section =
2724       sections[ImageHeader::kSectionInternedStrings] =
2725           ImageSection(cur_pos, intern_table_bytes_);
2726 
2727   /*
2728    * Class Table section
2729    */
2730 
2731   // Obtain the new position and round it up to the appropriate alignment.
2732   cur_pos = RoundUp(interned_strings_section.End(), sizeof(uint64_t));
2733 
2734   const ImageSection& class_table_section =
2735       sections[ImageHeader::kSectionClassTable] =
2736           ImageSection(cur_pos, class_table_bytes_);
2737 
2738   /*
2739    * String Field Offsets section
2740    */
2741 
2742   // Round up to the alignment of the offsets we are going to store.
2743   cur_pos = RoundUp(class_table_section.End(), sizeof(uint32_t));
2744 
2745   // The size of string_reference_offsets_ can't be used here because it hasn't
2746   // been filled with AppImageReferenceOffsetInfo objects yet.  The
2747   // num_string_references_ value is calculated separately, before we can
2748   // compute the actual offsets.
2749   const ImageSection& string_reference_offsets =
2750       sections[ImageHeader::kSectionStringReferenceOffsets] =
2751           ImageSection(cur_pos, sizeof(string_reference_offsets_[0]) * num_string_references_);
2752 
2753   /*
2754    * DexCache arrays section
2755    */
2756 
2757   // Round up to the alignment dex caches arrays expects.
2758   cur_pos = RoundUp(sections[ImageHeader::kSectionStringReferenceOffsets].End(), sizeof(uint32_t));
2759   // We don't generate dex cache arrays in an image generated by dex2oat.
2760   sections[ImageHeader::kSectionDexCacheArrays] = ImageSection(cur_pos, 0u);
2761 
2762   /*
2763    * Metadata section.
2764    */
2765 
2766   // Round up to the alignment of the offsets we are going to store.
2767   cur_pos = RoundUp(string_reference_offsets.End(), sizeof(uint32_t));
2768 
2769   const ImageSection& metadata_section =
2770       sections[ImageHeader::kSectionMetadata] =
2771           ImageSection(cur_pos, GetBinSlotSize(Bin::kMetadata));
2772 
2773   // Return the number of bytes described by these sections, and the sections
2774   // themselves.
2775   return make_pair(metadata_section.End(), std::move(sections));
2776 }
2777 
CreateHeader(size_t oat_index,size_t component_count)2778 void ImageWriter::CreateHeader(size_t oat_index, size_t component_count) {
2779   ImageInfo& image_info = GetImageInfo(oat_index);
2780   const uint8_t* oat_file_begin = image_info.oat_file_begin_;
2781   const uint8_t* oat_file_end = oat_file_begin + image_info.oat_loaded_size_;
2782   const uint8_t* oat_data_end = image_info.oat_data_begin_ + image_info.oat_size_;
2783 
2784   uint32_t image_reservation_size = image_info.image_size_;
2785   DCHECK_ALIGNED(image_reservation_size, kElfSegmentAlignment);
2786   uint32_t current_component_count = 1u;
2787   if (compiler_options_.IsAppImage()) {
2788     DCHECK_EQ(oat_index, 0u);
2789     DCHECK_EQ(component_count, current_component_count);
2790   } else {
2791     DCHECK(image_infos_.size() == 1u || image_infos_.size() == component_count)
2792         << image_infos_.size() << " " << component_count;
2793     if (oat_index == 0u) {
2794       const ImageInfo& last_info = image_infos_.back();
2795       const uint8_t* end = last_info.oat_file_begin_ + last_info.oat_loaded_size_;
2796       DCHECK_ALIGNED(image_info.image_begin_, kElfSegmentAlignment);
2797       image_reservation_size = dchecked_integral_cast<uint32_t>(
2798           RoundUp(end - image_info.image_begin_, kElfSegmentAlignment));
2799       current_component_count = component_count;
2800     } else {
2801       image_reservation_size = 0u;
2802       current_component_count = 0u;
2803     }
2804   }
2805 
2806   // Compute boot image checksums for the primary component, leave as 0 otherwise.
2807   uint32_t boot_image_components = 0u;
2808   uint32_t boot_image_checksums = 0u;
2809   if (oat_index == 0u) {
2810     const std::vector<gc::space::ImageSpace*>& image_spaces =
2811         Runtime::Current()->GetHeap()->GetBootImageSpaces();
2812     DCHECK_EQ(image_spaces.empty(), compiler_options_.IsBootImage());
2813     for (size_t i = 0u, size = image_spaces.size(); i != size; ) {
2814       const ImageHeader& header = image_spaces[i]->GetImageHeader();
2815       boot_image_components += header.GetComponentCount();
2816       boot_image_checksums ^= header.GetImageChecksum();
2817       DCHECK_LE(header.GetImageSpaceCount(), size - i);
2818       i += header.GetImageSpaceCount();
2819     }
2820   }
2821 
2822   // Create the image sections.
2823   auto section_info_pair = image_info.CreateImageSections();
2824   const size_t image_end = section_info_pair.first;
2825   dchecked_vector<ImageSection>& sections = section_info_pair.second;
2826 
2827   // Finally bitmap section.
2828   const size_t bitmap_bytes = image_info.image_bitmap_.Size();
2829   auto* bitmap_section = &sections[ImageHeader::kSectionImageBitmap];
2830   // The offset of the bitmap section should be aligned to kElfSegmentAlignment to enable mapping
2831   // the section from file to memory. However the section size doesn't have to be rounded up as it
2832   // is located at the end of the file. When mapping file contents to memory, if the last page of
2833   // the mapping is only partially filled with data, the rest will be zero-filled.
2834   *bitmap_section = ImageSection(RoundUp(image_end, kElfSegmentAlignment), bitmap_bytes);
2835   if (VLOG_IS_ON(compiler)) {
2836     LOG(INFO) << "Creating header for " << oat_filenames_[oat_index];
2837     size_t idx = 0;
2838     for (const ImageSection& section : sections) {
2839       LOG(INFO) << static_cast<ImageHeader::ImageSections>(idx) << " " << section;
2840       ++idx;
2841     }
2842     LOG(INFO) << "Methods: clean=" << clean_methods_ << " dirty=" << dirty_methods_;
2843     LOG(INFO) << "Image roots address=" << std::hex << image_info.image_roots_address_ << std::dec;
2844     LOG(INFO) << "Image begin=" << std::hex << reinterpret_cast<uintptr_t>(global_image_begin_)
2845               << " Image offset=" << image_info.image_offset_ << std::dec;
2846     LOG(INFO) << "Oat file begin=" << std::hex << reinterpret_cast<uintptr_t>(oat_file_begin)
2847               << " Oat data begin=" << reinterpret_cast<uintptr_t>(image_info.oat_data_begin_)
2848               << " Oat data end=" << reinterpret_cast<uintptr_t>(oat_data_end)
2849               << " Oat file end=" << reinterpret_cast<uintptr_t>(oat_file_end);
2850   }
2851 
2852   // Create the header, leave 0 for data size since we will fill this in as we are writing the
2853   // image.
2854   new (image_info.image_.Begin()) ImageHeader(
2855       image_reservation_size,
2856       current_component_count,
2857       PointerToLowMemUInt32(image_info.image_begin_),
2858       image_end,
2859       sections.data(),
2860       image_info.image_roots_address_,
2861       image_info.oat_checksum_,
2862       PointerToLowMemUInt32(oat_file_begin),
2863       PointerToLowMemUInt32(image_info.oat_data_begin_),
2864       PointerToLowMemUInt32(oat_data_end),
2865       PointerToLowMemUInt32(oat_file_end),
2866       boot_image_begin_,
2867       boot_image_size_,
2868       boot_image_components,
2869       boot_image_checksums,
2870       target_ptr_size_);
2871 }
2872 
GetImageMethodAddress(ArtMethod * method)2873 ArtMethod* ImageWriter::GetImageMethodAddress(ArtMethod* method) {
2874   NativeObjectRelocation relocation = GetNativeRelocation(method);
2875   const ImageInfo& image_info = GetImageInfo(relocation.oat_index);
2876   CHECK_GE(relocation.offset, image_info.image_end_) << "ArtMethods should be after Objects";
2877   return reinterpret_cast<ArtMethod*>(image_info.image_begin_ + relocation.offset);
2878 }
2879 
GetIntrinsicReferenceAddress(uint32_t intrinsic_data)2880 const void* ImageWriter::GetIntrinsicReferenceAddress(uint32_t intrinsic_data) {
2881   DCHECK(compiler_options_.IsBootImage());
2882   switch (IntrinsicObjects::DecodePatchType(intrinsic_data)) {
2883     case IntrinsicObjects::PatchType::kValueOfArray: {
2884       uint32_t index = IntrinsicObjects::DecodePatchIndex(intrinsic_data);
2885       const uint8_t* base_address =
2886           reinterpret_cast<const uint8_t*>(GetImageAddress(boot_image_live_objects_));
2887       MemberOffset data_offset =
2888           IntrinsicObjects::GetValueOfArrayDataOffset(boot_image_live_objects_, index);
2889       return base_address + data_offset.Uint32Value();
2890     }
2891     case IntrinsicObjects::PatchType::kValueOfObject: {
2892       uint32_t index = IntrinsicObjects::DecodePatchIndex(intrinsic_data);
2893       ObjPtr<mirror::Object> value = IntrinsicObjects::GetValueOfObject(boot_image_live_objects_,
2894                                                                         /* start_index= */ 0u,
2895                                                                         index);
2896       return GetImageAddress(value.Ptr());
2897     }
2898   }
2899   LOG(FATAL) << "UNREACHABLE";
2900   UNREACHABLE();
2901 }
2902 
2903 
2904 class ImageWriter::FixupRootVisitor : public RootVisitor {
2905  public:
FixupRootVisitor(ImageWriter * image_writer)2906   explicit FixupRootVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {
2907   }
2908 
VisitRoots(mirror::Object *** roots,size_t count,const RootInfo & info)2909   void VisitRoots([[maybe_unused]] mirror::Object*** roots,
2910                   [[maybe_unused]] size_t count,
2911                   [[maybe_unused]] const RootInfo& info) override
2912       REQUIRES_SHARED(Locks::mutator_lock_) {
2913     LOG(FATAL) << "Unsupported";
2914   }
2915 
VisitRoots(mirror::CompressedReference<mirror::Object> ** roots,size_t count,const RootInfo & info)2916   void VisitRoots(mirror::CompressedReference<mirror::Object>** roots,
2917                   size_t count,
2918                   [[maybe_unused]] const RootInfo& info) override
2919       REQUIRES_SHARED(Locks::mutator_lock_) {
2920     for (size_t i = 0; i < count; ++i) {
2921       // Copy the reference. Since we do not have the address for recording the relocation,
2922       // it needs to be recorded explicitly by the user of FixupRootVisitor.
2923       ObjPtr<mirror::Object> old_ptr = roots[i]->AsMirrorPtr();
2924       roots[i]->Assign(image_writer_->GetImageAddress(old_ptr.Ptr()));
2925     }
2926   }
2927 
2928  private:
2929   ImageWriter* const image_writer_;
2930 };
2931 
CopyAndFixupImTable(ImTable * orig,ImTable * copy)2932 void ImageWriter::CopyAndFixupImTable(ImTable* orig, ImTable* copy) {
2933   for (size_t i = 0; i < ImTable::kSize; ++i) {
2934     ArtMethod* method = orig->Get(i, target_ptr_size_);
2935     void** address = reinterpret_cast<void**>(copy->AddressOfElement(i, target_ptr_size_));
2936     CopyAndFixupPointer(address, method);
2937     DCHECK_EQ(copy->Get(i, target_ptr_size_), NativeLocationInImage(method));
2938   }
2939 }
2940 
CopyAndFixupImtConflictTable(ImtConflictTable * orig,ImtConflictTable * copy)2941 void ImageWriter::CopyAndFixupImtConflictTable(ImtConflictTable* orig, ImtConflictTable* copy) {
2942   const size_t count = orig->NumEntries(target_ptr_size_);
2943   for (size_t i = 0; i < count; ++i) {
2944     ArtMethod* interface_method = orig->GetInterfaceMethod(i, target_ptr_size_);
2945     ArtMethod* implementation_method = orig->GetImplementationMethod(i, target_ptr_size_);
2946     CopyAndFixupPointer(copy->AddressOfInterfaceMethod(i, target_ptr_size_), interface_method);
2947     CopyAndFixupPointer(
2948         copy->AddressOfImplementationMethod(i, target_ptr_size_), implementation_method);
2949     DCHECK_EQ(copy->GetInterfaceMethod(i, target_ptr_size_),
2950               NativeLocationInImage(interface_method));
2951     DCHECK_EQ(copy->GetImplementationMethod(i, target_ptr_size_),
2952               NativeLocationInImage(implementation_method));
2953   }
2954 }
2955 
CopyAndFixupNativeData(size_t oat_index)2956 void ImageWriter::CopyAndFixupNativeData(size_t oat_index) {
2957   const ImageInfo& image_info = GetImageInfo(oat_index);
2958   // Copy ArtFields and methods to their locations and update the array for convenience.
2959   for (auto& pair : native_object_relocations_) {
2960     NativeObjectRelocation& relocation = pair.second;
2961     // Only work with fields and methods that are in the current oat file.
2962     if (relocation.oat_index != oat_index) {
2963       continue;
2964     }
2965     auto* dest = image_info.image_.Begin() + relocation.offset;
2966     DCHECK_GE(dest, image_info.image_.Begin() + image_info.image_end_);
2967     DCHECK(!IsInBootImage(pair.first));
2968     switch (relocation.type) {
2969       case NativeObjectRelocationType::kRuntimeMethod:
2970       case NativeObjectRelocationType::kArtMethodClean:
2971       case NativeObjectRelocationType::kArtMethodDirty: {
2972         CopyAndFixupMethod(reinterpret_cast<ArtMethod*>(pair.first),
2973                            reinterpret_cast<ArtMethod*>(dest),
2974                            oat_index);
2975         break;
2976       }
2977       case NativeObjectRelocationType::kArtFieldArray: {
2978         // Copy and fix up the entire field array.
2979         auto* src_array = reinterpret_cast<LengthPrefixedArray<ArtField>*>(pair.first);
2980         auto* dest_array = reinterpret_cast<LengthPrefixedArray<ArtField>*>(dest);
2981         size_t size = src_array->size();
2982         memcpy(dest_array, src_array, LengthPrefixedArray<ArtField>::ComputeSize(size));
2983         for (size_t i = 0; i != size; ++i) {
2984           CopyAndFixupReference(
2985               dest_array->At(i).GetDeclaringClassAddressWithoutBarrier(),
2986               src_array->At(i).GetDeclaringClass<kWithoutReadBarrier>());
2987         }
2988         break;
2989       }
2990       case NativeObjectRelocationType::kArtMethodArrayClean:
2991       case NativeObjectRelocationType::kArtMethodArrayDirty: {
2992         // For method arrays, copy just the header since the elements will
2993         // get copied by their corresponding relocations.
2994         size_t size = ArtMethod::Size(target_ptr_size_);
2995         size_t alignment = ArtMethod::Alignment(target_ptr_size_);
2996         memcpy(dest, pair.first, LengthPrefixedArray<ArtMethod>::ComputeSize(0, size, alignment));
2997         // Clear padding to avoid non-deterministic data in the image.
2998         // Historical note: We also did that to placate Valgrind.
2999         reinterpret_cast<LengthPrefixedArray<ArtMethod>*>(dest)->ClearPadding(size, alignment);
3000         break;
3001       }
3002       case NativeObjectRelocationType::kIMTable: {
3003         ImTable* orig_imt = reinterpret_cast<ImTable*>(pair.first);
3004         ImTable* dest_imt = reinterpret_cast<ImTable*>(dest);
3005         CopyAndFixupImTable(orig_imt, dest_imt);
3006         break;
3007       }
3008       case NativeObjectRelocationType::kIMTConflictTable: {
3009         auto* orig_table = reinterpret_cast<ImtConflictTable*>(pair.first);
3010         CopyAndFixupImtConflictTable(
3011             orig_table,
3012             new(dest)ImtConflictTable(orig_table->NumEntries(target_ptr_size_), target_ptr_size_));
3013         break;
3014       }
3015       case NativeObjectRelocationType::kGcRootPointer: {
3016         auto* orig_pointer = reinterpret_cast<GcRoot<mirror::Object>*>(pair.first);
3017         auto* dest_pointer = reinterpret_cast<GcRoot<mirror::Object>*>(dest);
3018         CopyAndFixupReference(dest_pointer->AddressWithoutBarrier(), orig_pointer->Read());
3019         break;
3020       }
3021     }
3022   }
3023   // Fixup the image method roots.
3024   auto* image_header = reinterpret_cast<ImageHeader*>(image_info.image_.Begin());
3025   for (size_t i = 0; i < ImageHeader::kImageMethodsCount; ++i) {
3026     ArtMethod* method = image_methods_[i];
3027     CHECK(method != nullptr);
3028     CopyAndFixupPointer(
3029         reinterpret_cast<void**>(&image_header->image_methods_[i]), method, PointerSize::k32);
3030   }
3031   FixupRootVisitor root_visitor(this);
3032 
3033   // Write the intern table into the image.
3034   if (image_info.intern_table_bytes_ > 0) {
3035     const ImageSection& intern_table_section = image_header->GetInternedStringsSection();
3036     DCHECK(image_info.intern_table_.has_value());
3037     const InternTable::UnorderedSet& intern_table = *image_info.intern_table_;
3038     uint8_t* const intern_table_memory_ptr =
3039         image_info.image_.Begin() + intern_table_section.Offset();
3040     const size_t intern_table_bytes = intern_table.WriteToMemory(intern_table_memory_ptr);
3041     CHECK_EQ(intern_table_bytes, image_info.intern_table_bytes_);
3042     // Fixup the pointers in the newly written intern table to contain image addresses.
3043     InternTable temp_intern_table;
3044     // Note that we require that ReadFromMemory does not make an internal copy of the elements so
3045     // that the VisitRoots() will update the memory directly rather than the copies.
3046     // This also relies on visit roots not doing any verification which could fail after we update
3047     // the roots to be the image addresses.
3048     temp_intern_table.AddTableFromMemory(intern_table_memory_ptr,
3049                                          VoidFunctor(),
3050                                          /*is_boot_image=*/ false);
3051     CHECK_EQ(temp_intern_table.Size(), intern_table.size());
3052     temp_intern_table.VisitRoots(&root_visitor, kVisitRootFlagAllRoots);
3053 
3054     if (kIsDebugBuild) {
3055       MutexLock lock(Thread::Current(), *Locks::intern_table_lock_);
3056       CHECK(!temp_intern_table.strong_interns_.tables_.empty());
3057       // The UnorderedSet was inserted at the beginning.
3058       CHECK_EQ(temp_intern_table.strong_interns_.tables_[0].Size(), intern_table.size());
3059     }
3060   }
3061 
3062   // Write the class table(s) into the image. class_table_bytes_ may be 0 if there are multiple
3063   // class loaders. Writing multiple class tables into the image is currently unsupported.
3064   if (image_info.class_table_bytes_ > 0u) {
3065     const ImageSection& class_table_section = image_header->GetClassTableSection();
3066     uint8_t* const class_table_memory_ptr =
3067         image_info.image_.Begin() + class_table_section.Offset();
3068 
3069     DCHECK(image_info.class_table_.has_value());
3070     const ClassTable::ClassSet& table = *image_info.class_table_;
3071     CHECK_EQ(table.size(), image_info.class_table_size_);
3072     const size_t class_table_bytes = table.WriteToMemory(class_table_memory_ptr);
3073     CHECK_EQ(class_table_bytes, image_info.class_table_bytes_);
3074 
3075     // Fixup the pointers in the newly written class table to contain image addresses. See
3076     // above comment for intern tables.
3077     ClassTable temp_class_table;
3078     temp_class_table.ReadFromMemory(class_table_memory_ptr);
3079     CHECK_EQ(temp_class_table.NumReferencedZygoteClasses(), table.size());
3080     UnbufferedRootVisitor visitor(&root_visitor, RootInfo(kRootUnknown));
3081     temp_class_table.VisitRoots(visitor);
3082 
3083     if (kIsDebugBuild) {
3084       ReaderMutexLock lock(Thread::Current(), temp_class_table.lock_);
3085       CHECK(!temp_class_table.classes_.empty());
3086       // The ClassSet was inserted at the beginning.
3087       CHECK_EQ(temp_class_table.classes_[0].size(), table.size());
3088     }
3089   }
3090 }
3091 
CopyAndFixupJniStubMethods(size_t oat_index)3092 void ImageWriter::CopyAndFixupJniStubMethods(size_t oat_index) {
3093   const ImageInfo& image_info = GetImageInfo(oat_index);
3094   // Copy method's address to JniStubMethods section.
3095   for (auto& pair : jni_stub_map_) {
3096     JniStubMethodRelocation& relocation = pair.second.second;
3097     // Only work with JNI stubs that are in the current oat file.
3098     if (relocation.oat_index != oat_index) {
3099       continue;
3100     }
3101     void** address = reinterpret_cast<void**>(image_info.image_.Begin() + relocation.offset);
3102     ArtMethod* method = pair.second.first;
3103     CopyAndFixupPointer(address, method);
3104   }
3105 }
3106 
CopyAndFixupMethodPointerArray(mirror::PointerArray * arr)3107 void ImageWriter::CopyAndFixupMethodPointerArray(mirror::PointerArray* arr) {
3108   // Pointer arrays are processed early and each is visited just once.
3109   // Therefore we know that this array has not been copied yet.
3110   mirror::Object* dst = CopyObject</*kCheckIfDone=*/ false>(arr);
3111   DCHECK(dst != nullptr);
3112   DCHECK(arr->IsIntArray() || arr->IsLongArray())
3113       << arr->GetClass<kVerifyNone, kWithoutReadBarrier>()->PrettyClass() << " " << arr;
3114   // Fixup int and long pointers for the ArtMethod or ArtField arrays.
3115   const size_t num_elements = arr->GetLength();
3116   CopyAndFixupReference(dst->GetFieldObjectReferenceAddr<kVerifyNone>(Class::ClassOffset()),
3117                         arr->GetClass<kVerifyNone, kWithoutReadBarrier>());
3118   auto* dest_array = down_cast<mirror::PointerArray*>(dst);
3119   for (size_t i = 0, count = num_elements; i < count; ++i) {
3120     void* elem = arr->GetElementPtrSize<void*>(i, target_ptr_size_);
3121     if (kIsDebugBuild && elem != nullptr && !IsInBootImage(elem)) {
3122       auto it = native_object_relocations_.find(elem);
3123       if (UNLIKELY(it == native_object_relocations_.end())) {
3124         auto* method = reinterpret_cast<ArtMethod*>(elem);
3125         LOG(FATAL) << "No relocation entry for ArtMethod " << method->PrettyMethod() << " @ "
3126                    << method << " idx=" << i << "/" << num_elements << " with declaring class "
3127                    << Class::PrettyClass(method->GetDeclaringClass<kWithoutReadBarrier>());
3128         UNREACHABLE();
3129       }
3130     }
3131     CopyAndFixupPointer(dest_array->ElementAddress(i, target_ptr_size_), elem);
3132   }
3133 }
3134 
CopyAndFixupObject(Object * obj)3135 void ImageWriter::CopyAndFixupObject(Object* obj) {
3136   if (!IsImageBinSlotAssigned(obj)) {
3137     return;
3138   }
3139   // Some objects (such as method pointer arrays) may have been processed before.
3140   mirror::Object* dst = CopyObject</*kCheckIfDone=*/ true>(obj);
3141   if (dst != nullptr) {
3142     FixupObject(obj, dst);
3143   }
3144 }
3145 
3146 template <bool kCheckIfDone>
CopyObject(Object * obj)3147 inline Object* ImageWriter::CopyObject(Object* obj) {
3148   size_t oat_index = GetOatIndex(obj);
3149   size_t offset = GetImageOffset(obj, oat_index);
3150   ImageInfo& image_info = GetImageInfo(oat_index);
3151   auto* dst = reinterpret_cast<Object*>(image_info.image_.Begin() + offset);
3152   DCHECK_LT(offset, image_info.image_end_);
3153   const auto* src = reinterpret_cast<const uint8_t*>(obj);
3154 
3155   bool done = image_info.image_bitmap_.Set(dst);  // Mark the obj as live.
3156   // Check if the object was already copied, unless the caller indicated that it was not.
3157   if (kCheckIfDone && done) {
3158     return nullptr;
3159   }
3160   DCHECK(!done);
3161 
3162   const size_t n = obj->SizeOf();
3163 
3164   if (kIsDebugBuild && region_size_ != 0u) {
3165     const size_t offset_after_header = offset - sizeof(ImageHeader);
3166     const size_t next_region = RoundUp(offset_after_header, region_size_);
3167     if (offset_after_header != next_region) {
3168       // If the object is not on a region bondary, it must not be cross region.
3169       CHECK_LT(offset_after_header, next_region)
3170           << "offset_after_header=" << offset_after_header << " size=" << n;
3171       CHECK_LE(offset_after_header + n, next_region)
3172           << "offset_after_header=" << offset_after_header << " size=" << n;
3173     }
3174   }
3175   DCHECK_LE(offset + n, image_info.image_.Size());
3176   memcpy(dst, src, n);
3177 
3178   // Write in a hash code of objects which have inflated monitors or a hash code in their monitor
3179   // word.
3180   const auto it = saved_hashcode_map_.find(obj);
3181   dst->SetLockWord(it != saved_hashcode_map_.end() ?
3182       LockWord::FromHashCode(it->second, 0u) : LockWord::Default(), false);
3183   if (kUseBakerReadBarrier && gc::collector::ConcurrentCopying::kGrayDirtyImmuneObjects) {
3184     // Treat all of the objects in the image as marked to avoid unnecessary dirty pages. This is
3185     // safe since we mark all of the objects that may reference non immune objects as gray.
3186     CHECK(dst->AtomicSetMarkBit(0, 1));
3187   }
3188   return dst;
3189 }
3190 
3191 // Rewrite all the references in the copied object to point to their image address equivalent
3192 class ImageWriter::FixupVisitor {
3193  public:
FixupVisitor(ImageWriter * image_writer,Object * copy)3194   FixupVisitor(ImageWriter* image_writer, Object* copy)
3195       : image_writer_(image_writer), copy_(copy) {
3196   }
3197 
3198   // We do not visit native roots. These are handled with other logic.
VisitRootIfNonNull(mirror::CompressedReference<mirror::Object> * root) const3199   void VisitRootIfNonNull(
3200       [[maybe_unused]] mirror::CompressedReference<mirror::Object>* root) const {
3201     LOG(FATAL) << "UNREACHABLE";
3202   }
VisitRoot(mirror::CompressedReference<mirror::Object> * root) const3203   void VisitRoot([[maybe_unused]] mirror::CompressedReference<mirror::Object>* root) const {
3204     LOG(FATAL) << "UNREACHABLE";
3205   }
3206 
operator ()(ObjPtr<Object> obj,MemberOffset offset,bool is_static) const3207   void operator()(ObjPtr<Object> obj, MemberOffset offset, [[maybe_unused]] bool is_static) const
3208       REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
3209     ObjPtr<Object> ref = obj->GetFieldObject<Object, kVerifyNone, kWithoutReadBarrier>(offset);
3210     // Copy the reference and record the fixup if necessary.
3211     image_writer_->CopyAndFixupReference(
3212         copy_->GetFieldObjectReferenceAddr<kVerifyNone>(offset), ref);
3213   }
3214 
3215   // java.lang.ref.Reference visitor.
operator ()(ObjPtr<mirror::Class> klass,ObjPtr<mirror::Reference> ref) const3216   void operator()([[maybe_unused]] ObjPtr<mirror::Class> klass, ObjPtr<mirror::Reference> ref) const
3217       REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
3218     operator()(ref, mirror::Reference::ReferentOffset(), /* is_static */ false);
3219   }
3220 
3221  protected:
3222   ImageWriter* const image_writer_;
3223   mirror::Object* const copy_;
3224 };
3225 
CopyAndFixupObjects()3226 void ImageWriter::CopyAndFixupObjects() {
3227   // Copy and fix up pointer arrays first as they require special treatment.
3228   auto method_pointer_array_visitor =
3229       [&](ObjPtr<mirror::PointerArray> pointer_array) REQUIRES_SHARED(Locks::mutator_lock_) {
3230         CopyAndFixupMethodPointerArray(pointer_array.Ptr());
3231       };
3232   for (ImageInfo& image_info : image_infos_) {
3233     if (image_info.class_table_size_ != 0u) {
3234       DCHECK(image_info.class_table_.has_value());
3235       for (const ClassTable::TableSlot& slot : *image_info.class_table_) {
3236         ObjPtr<mirror::Class> klass = slot.Read<kWithoutReadBarrier>();
3237         DCHECK(klass != nullptr);
3238         // Do not process boot image classes present in app image class table.
3239         DCHECK(!IsInBootImage(klass.Ptr()) || compiler_options_.IsAppImage());
3240         if (!IsInBootImage(klass.Ptr())) {
3241           // Do not fix up method pointer arrays inherited from superclass. If they are part
3242           // of the current image, they were or shall be copied when visiting the superclass.
3243           VisitNewMethodPointerArrays(klass, method_pointer_array_visitor);
3244         }
3245       }
3246     }
3247   }
3248 
3249   auto visitor = [&](Object* obj) REQUIRES_SHARED(Locks::mutator_lock_) {
3250     DCHECK(obj != nullptr);
3251     CopyAndFixupObject(obj);
3252   };
3253   Runtime::Current()->GetHeap()->VisitObjects(visitor);
3254 
3255   // Fill the padding objects since they are required for in order traversal of the image space.
3256   for (ImageInfo& image_info : image_infos_) {
3257     for (const size_t start_offset : image_info.padding_offsets_) {
3258       const size_t offset_after_header = start_offset - sizeof(ImageHeader);
3259       size_t remaining_space =
3260           RoundUp(offset_after_header + 1u, region_size_) - offset_after_header;
3261       DCHECK_NE(remaining_space, 0u);
3262       DCHECK_LT(remaining_space, region_size_);
3263       Object* dst = reinterpret_cast<Object*>(image_info.image_.Begin() + start_offset);
3264       ObjPtr<Class> object_class = GetClassRoot<mirror::Object, kWithoutReadBarrier>();
3265       DCHECK_ALIGNED_PARAM(remaining_space, object_class->GetObjectSize());
3266       Object* end = dst + remaining_space / object_class->GetObjectSize();
3267       Class* image_object_class = GetImageAddress(object_class.Ptr());
3268       while (dst != end) {
3269         dst->SetClass<kVerifyNone>(image_object_class);
3270         dst->SetLockWord<kVerifyNone>(LockWord::Default(), /*as_volatile=*/ false);
3271         image_info.image_bitmap_.Set(dst);  // Mark the obj as live.
3272         ++dst;
3273       }
3274     }
3275   }
3276 
3277   // We no longer need the hashcode map, values have already been copied to target objects.
3278   saved_hashcode_map_.clear();
3279 }
3280 
3281 class ImageWriter::FixupClassVisitor final : public FixupVisitor {
3282  public:
FixupClassVisitor(ImageWriter * image_writer,Object * copy)3283   FixupClassVisitor(ImageWriter* image_writer, Object* copy)
3284       : FixupVisitor(image_writer, copy) {}
3285 
operator ()(ObjPtr<Object> obj,MemberOffset offset,bool is_static) const3286   void operator()(ObjPtr<Object> obj, MemberOffset offset, [[maybe_unused]] bool is_static) const
3287       REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
3288     DCHECK(obj->IsClass());
3289     FixupVisitor::operator()(obj, offset, /*is_static*/false);
3290   }
3291 
operator ()(ObjPtr<mirror::Class> klass,ObjPtr<mirror::Reference> ref) const3292   void operator()([[maybe_unused]] ObjPtr<mirror::Class> klass,
3293                   [[maybe_unused]] ObjPtr<mirror::Reference> ref) const
3294       REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
3295     LOG(FATAL) << "Reference not expected here.";
3296   }
3297 };
3298 
GetNativeRelocation(void * obj)3299 ImageWriter::NativeObjectRelocation ImageWriter::GetNativeRelocation(void* obj) {
3300   DCHECK(obj != nullptr);
3301   DCHECK(!IsInBootImage(obj));
3302   auto it = native_object_relocations_.find(obj);
3303   CHECK(it != native_object_relocations_.end()) << obj << " spaces "
3304       << Runtime::Current()->GetHeap()->DumpSpaces();
3305   return it->second;
3306 }
3307 
3308 template <typename T>
PrettyPrint(T * ptr)3309 std::string PrettyPrint(T* ptr) REQUIRES_SHARED(Locks::mutator_lock_) {
3310   std::ostringstream oss;
3311   oss << ptr;
3312   return oss.str();
3313 }
3314 
3315 template <>
PrettyPrint(ArtMethod * method)3316 std::string PrettyPrint(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_) {
3317   return ArtMethod::PrettyMethod(method);
3318 }
3319 
3320 template <typename T>
NativeLocationInImage(T * obj)3321 T* ImageWriter::NativeLocationInImage(T* obj) {
3322   if (obj == nullptr || IsInBootImage(obj)) {
3323     return obj;
3324   } else {
3325     NativeObjectRelocation relocation = GetNativeRelocation(obj);
3326     const ImageInfo& image_info = GetImageInfo(relocation.oat_index);
3327     return reinterpret_cast<T*>(image_info.image_begin_ + relocation.offset);
3328   }
3329 }
3330 
NativeLocationInImage(ArtField * src_field)3331 ArtField* ImageWriter::NativeLocationInImage(ArtField* src_field) {
3332   // Fields are not individually stored in the native relocation map. Use the field array.
3333   ObjPtr<mirror::Class> declaring_class = src_field->GetDeclaringClass<kWithoutReadBarrier>();
3334   LengthPrefixedArray<ArtField>* src_fields =
3335       src_field->IsStatic() ? declaring_class->GetSFieldsPtr() : declaring_class->GetIFieldsPtr();
3336   DCHECK(src_fields != nullptr);
3337   LengthPrefixedArray<ArtField>* dst_fields = NativeLocationInImage(src_fields);
3338   DCHECK(dst_fields != nullptr);
3339   size_t field_offset =
3340       reinterpret_cast<uint8_t*>(src_field) - reinterpret_cast<uint8_t*>(src_fields);
3341   return reinterpret_cast<ArtField*>(reinterpret_cast<uint8_t*>(dst_fields) + field_offset);
3342 }
3343 
3344 class ImageWriter::NativeLocationVisitor {
3345  public:
NativeLocationVisitor(ImageWriter * image_writer)3346   explicit NativeLocationVisitor(ImageWriter* image_writer)
3347       : image_writer_(image_writer) {}
3348 
3349   template <typename T>
operator ()(T * ptr,void ** dest_addr) const3350   T* operator()(T* ptr, void** dest_addr) const REQUIRES_SHARED(Locks::mutator_lock_) {
3351     if (ptr != nullptr) {
3352       image_writer_->CopyAndFixupPointer(dest_addr, ptr);
3353     }
3354     // TODO: The caller shall overwrite the value stored by CopyAndFixupPointer()
3355     // with the value we return here. We should try to avoid the duplicate work.
3356     return image_writer_->NativeLocationInImage(ptr);
3357   }
3358 
3359  private:
3360   ImageWriter* const image_writer_;
3361 };
3362 
FixupClass(mirror::Class * orig,mirror::Class * copy)3363 void ImageWriter::FixupClass(mirror::Class* orig, mirror::Class* copy) {
3364   orig->FixupNativePointers(copy, target_ptr_size_, NativeLocationVisitor(this));
3365   FixupClassVisitor visitor(this, copy);
3366   ObjPtr<mirror::Object>(orig)->VisitReferences<
3367       /*kVisitNativeRoots=*/ false, kVerifyNone, kWithoutReadBarrier>(visitor, visitor);
3368 
3369   if (kBitstringSubtypeCheckEnabled && !compiler_options_.IsBootImage()) {
3370     // When we call SubtypeCheck::EnsureInitialize, it Assigns new bitstring
3371     // values to the parent of that class.
3372     //
3373     // Every time this happens, the parent class has to mutate to increment
3374     // the "Next" value.
3375     //
3376     // If any of these parents are in the boot image, the changes [in the parents]
3377     // would be lost when the app image is reloaded.
3378     //
3379     // To prevent newly loaded classes (not in the app image) from being reassigned
3380     // the same bitstring value as an existing app image class, uninitialize
3381     // all the classes in the app image.
3382     //
3383     // On startup, the class linker will then re-initialize all the app
3384     // image bitstrings. See also ClassLinker::AddImageSpace.
3385     //
3386     // FIXME: Deal with boot image extensions.
3387     MutexLock subtype_check_lock(Thread::Current(), *Locks::subtype_check_lock_);
3388     // Lock every time to prevent a dcheck failure when we suspend with the lock held.
3389     SubtypeCheck<mirror::Class*>::ForceUninitialize(copy);
3390   }
3391 
3392   // Remove the clinitThreadId. This is required for image determinism.
3393   copy->SetClinitThreadId(static_cast<pid_t>(0));
3394   // We never emit kRetryVerificationAtRuntime, instead we mark the class as
3395   // resolved and the class will therefore be re-verified at runtime.
3396   if (orig->ShouldVerifyAtRuntime()) {
3397     copy->SetStatusInternal(ClassStatus::kResolved);
3398   }
3399 }
3400 
FixupObject(Object * orig,Object * copy)3401 void ImageWriter::FixupObject(Object* orig, Object* copy) {
3402   DCHECK(orig != nullptr);
3403   DCHECK(copy != nullptr);
3404   if (kUseBakerReadBarrier) {
3405     orig->AssertReadBarrierState();
3406   }
3407   ObjPtr<mirror::Class> klass = orig->GetClass<kVerifyNone, kWithoutReadBarrier>();
3408   if (klass->IsClassClass()) {
3409     FixupClass(orig->AsClass<kVerifyNone>().Ptr(), down_cast<mirror::Class*>(copy));
3410   } else {
3411     ObjPtr<mirror::ObjectArray<mirror::Class>> class_roots =
3412         Runtime::Current()->GetClassLinker()->GetClassRoots<kWithoutReadBarrier>();
3413     if (klass == GetClassRoot<mirror::String, kWithoutReadBarrier>(class_roots)) {
3414       // Make sure all image strings have the hash code calculated, even if they are not interned.
3415       down_cast<mirror::String*>(copy)->GetHashCode();
3416     } else if (klass == GetClassRoot<mirror::Method, kWithoutReadBarrier>(class_roots) ||
3417         klass == GetClassRoot<mirror::Constructor, kWithoutReadBarrier>(class_roots)) {
3418       // Need to update the ArtMethod.
3419       auto* dest = down_cast<mirror::Executable*>(copy);
3420       auto* src = down_cast<mirror::Executable*>(orig);
3421       ArtMethod* src_method = src->GetArtMethod();
3422       CopyAndFixupPointer(dest, mirror::Executable::ArtMethodOffset(), src_method);
3423     } else if (klass == GetClassRoot<mirror::FieldVarHandle, kWithoutReadBarrier>(class_roots) ||
3424          klass == GetClassRoot<mirror::StaticFieldVarHandle, kWithoutReadBarrier>(class_roots)) {
3425       // Need to update the ArtField.
3426       auto* dest = down_cast<mirror::FieldVarHandle*>(copy);
3427       auto* src = down_cast<mirror::FieldVarHandle*>(orig);
3428       ArtField* src_field = src->GetArtField();
3429       CopyAndFixupPointer(dest, mirror::FieldVarHandle::ArtFieldOffset(), src_field);
3430     } else if (klass == GetClassRoot<mirror::DexCache, kWithoutReadBarrier>(class_roots)) {
3431       down_cast<mirror::DexCache*>(copy)->SetDexFile(nullptr);
3432       down_cast<mirror::DexCache*>(copy)->ResetNativeArrays();
3433     } else if (klass->IsClassLoaderClass()) {
3434       mirror::ClassLoader* copy_loader = down_cast<mirror::ClassLoader*>(copy);
3435       // If src is a ClassLoader, set the class table to null so that it gets recreated by the
3436       // ClassLinker.
3437       copy_loader->SetClassTable(nullptr);
3438       // Also set allocator to null to be safe. The allocator is created when we create the class
3439       // table. We also never expect to unload things in the image since they are held live as
3440       // roots.
3441       copy_loader->SetAllocator(nullptr);
3442     }
3443     FixupVisitor visitor(this, copy);
3444     orig->VisitReferences</*kVisitNativeRoots=*/ false, kVerifyNone, kWithoutReadBarrier>(
3445         visitor, visitor);
3446   }
3447 }
3448 
GetOatAddress(StubType type) const3449 const uint8_t* ImageWriter::GetOatAddress(StubType type) const {
3450   DCHECK_LE(type, StubType::kLast);
3451   // If we are compiling a boot image extension or app image,
3452   // we need to use the stubs of the primary boot image.
3453   if (!compiler_options_.IsBootImage()) {
3454     // Use the current image pointers.
3455     const std::vector<gc::space::ImageSpace*>& image_spaces =
3456         Runtime::Current()->GetHeap()->GetBootImageSpaces();
3457     DCHECK(!image_spaces.empty());
3458     const OatFile* oat_file = image_spaces[0]->GetOatFile();
3459     CHECK(oat_file != nullptr);
3460     const OatHeader& header = oat_file->GetOatHeader();
3461     return header.GetOatAddress(type);
3462   }
3463   const ImageInfo& primary_image_info = GetImageInfo(0);
3464   return GetOatAddressForOffset(primary_image_info.GetStubOffset(type), primary_image_info);
3465 }
3466 
GetQuickCode(ArtMethod * method,const ImageInfo & image_info)3467 const uint8_t* ImageWriter::GetQuickCode(ArtMethod* method, const ImageInfo& image_info) {
3468   DCHECK(!method->IsResolutionMethod()) << method->PrettyMethod();
3469   DCHECK_NE(method, Runtime::Current()->GetImtConflictMethod()) << method->PrettyMethod();
3470   DCHECK(!method->IsImtUnimplementedMethod()) << method->PrettyMethod();
3471   DCHECK(method->IsInvokable()) << method->PrettyMethod();
3472   DCHECK(!IsInBootImage(method)) << method->PrettyMethod();
3473 
3474   // Use original code if it exists. Otherwise, set the code pointer to the resolution
3475   // trampoline.
3476 
3477   // Quick entrypoint:
3478   const void* quick_oat_entry_point =
3479       method->GetEntryPointFromQuickCompiledCodePtrSize(target_ptr_size_);
3480   const uint8_t* quick_code;
3481 
3482   if (UNLIKELY(IsInBootImage(method->GetDeclaringClass<kWithoutReadBarrier>().Ptr()))) {
3483     DCHECK(method->IsCopied());
3484     // If the code is not in the oat file corresponding to this image (e.g. default methods)
3485     quick_code = reinterpret_cast<const uint8_t*>(quick_oat_entry_point);
3486   } else {
3487     uint32_t quick_oat_code_offset = PointerToLowMemUInt32(quick_oat_entry_point);
3488     quick_code = GetOatAddressForOffset(quick_oat_code_offset, image_info);
3489   }
3490 
3491   bool still_needs_clinit_check = method->StillNeedsClinitCheck<kWithoutReadBarrier>();
3492 
3493   if (quick_code == nullptr) {
3494     // If we don't have code, use generic jni / interpreter.
3495     if (method->IsNative()) {
3496       // The generic JNI trampolines performs class initialization check if needed.
3497       quick_code = GetOatAddress(StubType::kQuickGenericJNITrampoline);
3498     } else if (CanMethodUseNterp(method, compiler_options_.GetInstructionSet())) {
3499       // The nterp trampoline doesn't do initialization checks, so install the
3500       // resolution stub if needed.
3501       if (still_needs_clinit_check) {
3502         quick_code = GetOatAddress(StubType::kQuickResolutionTrampoline);
3503       } else {
3504         quick_code = GetOatAddress(StubType::kNterpTrampoline);
3505       }
3506     } else {
3507       // The interpreter brige performs class initialization check if needed.
3508       quick_code = GetOatAddress(StubType::kQuickToInterpreterBridge);
3509     }
3510   } else if (still_needs_clinit_check && !compiler_options_.ShouldCompileWithClinitCheck(method)) {
3511     // If we do have code but the method needs a class initialization check before calling
3512     // that code, install the resolution stub that will perform the check.
3513     quick_code = GetOatAddress(StubType::kQuickResolutionTrampoline);
3514   }
3515   return quick_code;
3516 }
3517 
ResetNterpFastPathFlags(uint32_t access_flags,ArtMethod * orig,InstructionSet isa)3518 static inline uint32_t ResetNterpFastPathFlags(
3519     uint32_t access_flags, ArtMethod* orig, InstructionSet isa)
3520     REQUIRES_SHARED(Locks::mutator_lock_) {
3521   DCHECK(orig != nullptr);
3522   DCHECK(!orig->IsProxyMethod());  // `UnstartedRuntime` does not support creating proxy classes.
3523   DCHECK(!orig->IsRuntimeMethod());
3524 
3525   // Clear old nterp fast path flags.
3526   access_flags = ArtMethod::ClearNterpFastPathFlags(access_flags);
3527 
3528   // Check if nterp fast paths are available on the target ISA.
3529   std::string_view shorty = orig->GetShortyView();  // Use orig, copy's class not yet ready.
3530   uint32_t new_nterp_flags = GetNterpFastPathFlags(shorty, access_flags, isa);
3531 
3532   // Add the new nterp fast path flags, if any.
3533   return access_flags | new_nterp_flags;
3534 }
3535 
CopyAndFixupMethod(ArtMethod * orig,ArtMethod * copy,size_t oat_index)3536 void ImageWriter::CopyAndFixupMethod(ArtMethod* orig,
3537                                      ArtMethod* copy,
3538                                      size_t oat_index) {
3539   memcpy(copy, orig, ArtMethod::Size(target_ptr_size_));
3540 
3541   CopyAndFixupReference(copy->GetDeclaringClassAddressWithoutBarrier(),
3542                         orig->GetDeclaringClassUnchecked<kWithoutReadBarrier>());
3543 
3544   if (!orig->IsRuntimeMethod()) {
3545     uint32_t access_flags = orig->GetAccessFlags();
3546     if (ArtMethod::IsAbstract(access_flags)) {
3547       // Ignore the single-implementation info for abstract method.
3548       // TODO: handle fixup of single-implementation method for abstract method.
3549       access_flags = ArtMethod::SetHasSingleImplementation(access_flags, /*single_impl=*/ false);
3550       copy->SetSingleImplementation(nullptr, target_ptr_size_);
3551     } else if (mark_memory_shared_methods_ && LIKELY(!ArtMethod::IsIntrinsic(access_flags))) {
3552       access_flags = ArtMethod::SetMemorySharedMethod(access_flags);
3553       copy->SetHotCounter();
3554     }
3555 
3556     InstructionSet isa = compiler_options_.GetInstructionSet();
3557     if (isa != kRuntimeISA) {
3558       access_flags = ResetNterpFastPathFlags(access_flags, orig, isa);
3559     } else {
3560       DCHECK_EQ(access_flags, ResetNterpFastPathFlags(access_flags, orig, isa));
3561     }
3562     copy->SetAccessFlags(access_flags);
3563   }
3564 
3565   // OatWriter replaces the code_ with an offset value. Here we re-adjust to a pointer relative to
3566   // oat_begin_
3567 
3568   // The resolution method has a special trampoline to call.
3569   Runtime* runtime = Runtime::Current();
3570   const void* quick_code;
3571   if (orig->IsRuntimeMethod()) {
3572     ImtConflictTable* orig_table = orig->GetImtConflictTable(target_ptr_size_);
3573     if (orig_table != nullptr) {
3574       // Special IMT conflict method, normal IMT conflict method or unimplemented IMT method.
3575       quick_code = GetOatAddress(StubType::kQuickIMTConflictTrampoline);
3576       CopyAndFixupPointer(copy, ArtMethod::DataOffset(target_ptr_size_), orig_table);
3577     } else if (UNLIKELY(orig == runtime->GetResolutionMethod())) {
3578       quick_code = GetOatAddress(StubType::kQuickResolutionTrampoline);
3579       // Set JNI entrypoint for resolving @CriticalNative methods called from compiled code .
3580       const void* jni_code = GetOatAddress(StubType::kJNIDlsymLookupCriticalTrampoline);
3581       copy->SetEntryPointFromJniPtrSize(jni_code, target_ptr_size_);
3582     } else {
3583       bool found_one = false;
3584       for (size_t i = 0; i < static_cast<size_t>(CalleeSaveType::kLastCalleeSaveType); ++i) {
3585         auto idx = static_cast<CalleeSaveType>(i);
3586         if (runtime->HasCalleeSaveMethod(idx) && runtime->GetCalleeSaveMethod(idx) == orig) {
3587           found_one = true;
3588           break;
3589         }
3590       }
3591       CHECK(found_one) << "Expected to find callee save method but got " << orig->PrettyMethod();
3592       CHECK(copy->IsRuntimeMethod());
3593       CHECK(copy->GetEntryPointFromQuickCompiledCodePtrSize(target_ptr_size_) == nullptr);
3594       quick_code = nullptr;
3595     }
3596   } else {
3597     // We assume all methods have code. If they don't currently then we set them to the use the
3598     // resolution trampoline. Abstract methods never have code and so we need to make sure their
3599     // use results in an AbstractMethodError. We use the interpreter to achieve this.
3600     if (UNLIKELY(!orig->IsInvokable())) {
3601       quick_code = GetOatAddress(StubType::kQuickToInterpreterBridge);
3602     } else {
3603       const ImageInfo& image_info = image_infos_[oat_index];
3604       quick_code = GetQuickCode(orig, image_info);
3605 
3606       // JNI entrypoint:
3607       if (orig->IsNative()) {
3608         // Find boot JNI stub for those methods that skipped AOT compilation and don't need
3609         // clinit check.
3610         bool still_needs_clinit_check = orig->StillNeedsClinitCheck<kWithoutReadBarrier>();
3611         if (!still_needs_clinit_check &&
3612             !compiler_options_.IsBootImage() &&
3613             quick_code == GetOatAddress(StubType::kQuickGenericJNITrampoline)) {
3614           ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
3615           const void* boot_jni_stub = class_linker->FindBootJniStub(orig);
3616           if (boot_jni_stub != nullptr) {
3617             quick_code = boot_jni_stub;
3618           }
3619         }
3620         // The native method's pointer is set to a stub to lookup via dlsym.
3621         // Note this is not the code_ pointer, that is handled above.
3622         StubType stub_type = orig->IsCriticalNative() ? StubType::kJNIDlsymLookupCriticalTrampoline
3623                                                       : StubType::kJNIDlsymLookupTrampoline;
3624         copy->SetEntryPointFromJniPtrSize(GetOatAddress(stub_type), target_ptr_size_);
3625       } else if (!orig->HasCodeItem()) {
3626         CHECK(copy->GetDataPtrSize(target_ptr_size_) == nullptr);
3627       } else {
3628         CHECK(copy->GetDataPtrSize(target_ptr_size_) != nullptr);
3629       }
3630     }
3631   }
3632   if (quick_code != nullptr) {
3633     copy->SetEntryPointFromQuickCompiledCodePtrSize(quick_code, target_ptr_size_);
3634   }
3635 }
3636 
GetBinSizeSum(Bin up_to) const3637 size_t ImageWriter::ImageInfo::GetBinSizeSum(Bin up_to) const {
3638   DCHECK_LE(static_cast<size_t>(up_to), kNumberOfBins);
3639   return std::accumulate(&bin_slot_sizes_[0],
3640                          &bin_slot_sizes_[0] + static_cast<size_t>(up_to),
3641                          /*init*/ static_cast<size_t>(0));
3642 }
3643 
BinSlot(uint32_t lockword)3644 ImageWriter::BinSlot::BinSlot(uint32_t lockword) : lockword_(lockword) {
3645   // These values may need to get updated if more bins are added to the enum Bin
3646   static_assert(kBinBits == 3, "wrong number of bin bits");
3647   static_assert(kBinShift == 27, "wrong number of shift");
3648   static_assert(sizeof(BinSlot) == sizeof(LockWord), "BinSlot/LockWord must have equal sizes");
3649 
3650   DCHECK_LT(GetBin(), Bin::kMirrorCount);
3651   DCHECK_ALIGNED(GetOffset(), kObjectAlignment);
3652 }
3653 
BinSlot(Bin bin,uint32_t index)3654 ImageWriter::BinSlot::BinSlot(Bin bin, uint32_t index)
3655     : BinSlot(index | (static_cast<uint32_t>(bin) << kBinShift)) {
3656   DCHECK_EQ(index, GetOffset());
3657 }
3658 
GetBin() const3659 ImageWriter::Bin ImageWriter::BinSlot::GetBin() const {
3660   return static_cast<Bin>((lockword_ & kBinMask) >> kBinShift);
3661 }
3662 
GetOffset() const3663 uint32_t ImageWriter::BinSlot::GetOffset() const {
3664   return lockword_ & ~kBinMask;
3665 }
3666 
BinTypeForNativeRelocationType(NativeObjectRelocationType type)3667 ImageWriter::Bin ImageWriter::BinTypeForNativeRelocationType(NativeObjectRelocationType type) {
3668   switch (type) {
3669     case NativeObjectRelocationType::kArtFieldArray:
3670       return Bin::kArtField;
3671     case NativeObjectRelocationType::kArtMethodClean:
3672     case NativeObjectRelocationType::kArtMethodArrayClean:
3673       return Bin::kArtMethodClean;
3674     case NativeObjectRelocationType::kArtMethodDirty:
3675     case NativeObjectRelocationType::kArtMethodArrayDirty:
3676       return Bin::kArtMethodDirty;
3677     case NativeObjectRelocationType::kRuntimeMethod:
3678       return Bin::kRuntimeMethod;
3679     case NativeObjectRelocationType::kIMTable:
3680       return Bin::kImTable;
3681     case NativeObjectRelocationType::kIMTConflictTable:
3682       return Bin::kIMTConflictTable;
3683     case NativeObjectRelocationType::kGcRootPointer:
3684       return Bin::kMetadata;
3685   }
3686 }
3687 
GetOatIndex(mirror::Object * obj) const3688 size_t ImageWriter::GetOatIndex(mirror::Object* obj) const {
3689   if (!IsMultiImage()) {
3690     DCHECK(oat_index_map_.empty());
3691     return GetDefaultOatIndex();
3692   }
3693   auto it = oat_index_map_.find(obj);
3694   DCHECK(it != oat_index_map_.end()) << obj;
3695   return it->second;
3696 }
3697 
GetOatIndexForDexFile(const DexFile * dex_file) const3698 size_t ImageWriter::GetOatIndexForDexFile(const DexFile* dex_file) const {
3699   if (!IsMultiImage()) {
3700     return GetDefaultOatIndex();
3701   }
3702   auto it = dex_file_oat_index_map_.find(dex_file);
3703   DCHECK(it != dex_file_oat_index_map_.end()) << dex_file->GetLocation();
3704   return it->second;
3705 }
3706 
GetOatIndexForClass(ObjPtr<mirror::Class> klass) const3707 size_t ImageWriter::GetOatIndexForClass(ObjPtr<mirror::Class> klass) const {
3708   while (klass->IsArrayClass()) {
3709     klass = klass->GetComponentType<kVerifyNone, kWithoutReadBarrier>();
3710   }
3711   if (UNLIKELY(klass->IsPrimitive())) {
3712     DCHECK((klass->GetDexCache<kVerifyNone, kWithoutReadBarrier>()) == nullptr);
3713     return GetDefaultOatIndex();
3714   } else {
3715     DCHECK((klass->GetDexCache<kVerifyNone, kWithoutReadBarrier>()) != nullptr);
3716     return GetOatIndexForDexFile(&klass->GetDexFile());
3717   }
3718 }
3719 
UpdateOatFileLayout(size_t oat_index,size_t oat_loaded_size,size_t oat_data_offset,size_t oat_data_size)3720 void ImageWriter::UpdateOatFileLayout(size_t oat_index,
3721                                       size_t oat_loaded_size,
3722                                       size_t oat_data_offset,
3723                                       size_t oat_data_size) {
3724   DCHECK_GE(oat_loaded_size, oat_data_offset);
3725   DCHECK_GE(oat_loaded_size - oat_data_offset, oat_data_size);
3726 
3727   const uint8_t* images_end = image_infos_.back().image_begin_ + image_infos_.back().image_size_;
3728   DCHECK(images_end != nullptr);  // Image space must be ready.
3729   for (const ImageInfo& info : image_infos_) {
3730     DCHECK_LE(info.image_begin_ + info.image_size_, images_end);
3731   }
3732 
3733   ImageInfo& cur_image_info = GetImageInfo(oat_index);
3734   cur_image_info.oat_file_begin_ = images_end + cur_image_info.oat_offset_;
3735   cur_image_info.oat_loaded_size_ = oat_loaded_size;
3736   cur_image_info.oat_data_begin_ = cur_image_info.oat_file_begin_ + oat_data_offset;
3737   cur_image_info.oat_size_ = oat_data_size;
3738 
3739   if (compiler_options_.IsAppImage()) {
3740     CHECK_EQ(oat_filenames_.size(), 1u) << "App image should have no next image.";
3741     return;
3742   }
3743 
3744   // Update the oat_offset of the next image info.
3745   if (oat_index + 1u != oat_filenames_.size()) {
3746     // There is a following one.
3747     ImageInfo& next_image_info = GetImageInfo(oat_index + 1u);
3748     next_image_info.oat_offset_ = cur_image_info.oat_offset_ + oat_loaded_size;
3749   }
3750 }
3751 
UpdateOatFileHeader(size_t oat_index,const OatHeader & oat_header)3752 void ImageWriter::UpdateOatFileHeader(size_t oat_index, const OatHeader& oat_header) {
3753   ImageInfo& cur_image_info = GetImageInfo(oat_index);
3754   cur_image_info.oat_checksum_ = oat_header.GetChecksum();
3755 
3756   if (oat_index == GetDefaultOatIndex()) {
3757     // Primary oat file, read the trampolines.
3758     cur_image_info.SetStubOffset(StubType::kJNIDlsymLookupTrampoline,
3759                                  oat_header.GetJniDlsymLookupTrampolineOffset());
3760     cur_image_info.SetStubOffset(StubType::kJNIDlsymLookupCriticalTrampoline,
3761                                  oat_header.GetJniDlsymLookupCriticalTrampolineOffset());
3762     cur_image_info.SetStubOffset(StubType::kQuickGenericJNITrampoline,
3763                                  oat_header.GetQuickGenericJniTrampolineOffset());
3764     cur_image_info.SetStubOffset(StubType::kQuickIMTConflictTrampoline,
3765                                  oat_header.GetQuickImtConflictTrampolineOffset());
3766     cur_image_info.SetStubOffset(StubType::kQuickResolutionTrampoline,
3767                                  oat_header.GetQuickResolutionTrampolineOffset());
3768     cur_image_info.SetStubOffset(StubType::kQuickToInterpreterBridge,
3769                                  oat_header.GetQuickToInterpreterBridgeOffset());
3770     cur_image_info.SetStubOffset(StubType::kNterpTrampoline,
3771                                  oat_header.GetNterpTrampolineOffset());
3772   }
3773 }
3774 
ImageWriter(const CompilerOptions & compiler_options,uintptr_t image_begin,ImageHeader::StorageMode image_storage_mode,const std::vector<std::string> & oat_filenames,const HashMap<const DexFile *,size_t> & dex_file_oat_index_map,jobject class_loader,const std::vector<std::string> * dirty_image_objects)3775 ImageWriter::ImageWriter(const CompilerOptions& compiler_options,
3776                          uintptr_t image_begin,
3777                          ImageHeader::StorageMode image_storage_mode,
3778                          const std::vector<std::string>& oat_filenames,
3779                          const HashMap<const DexFile*, size_t>& dex_file_oat_index_map,
3780                          jobject class_loader,
3781                          const std::vector<std::string>* dirty_image_objects)
3782     : compiler_options_(compiler_options),
3783       target_ptr_size_(InstructionSetPointerSize(compiler_options.GetInstructionSet())),
3784       // If we're compiling a boot image and we have a profile, set methods as being shared
3785       // memory (to avoid dirtying them with hotness counter). We expect important methods
3786       // to be AOT, and non-important methods to be run in the interpreter.
3787       mark_memory_shared_methods_(
3788           CompilerFilter::DependsOnProfile(compiler_options_.GetCompilerFilter()) &&
3789               (compiler_options_.IsBootImage() || compiler_options_.IsBootImageExtension())),
3790       boot_image_begin_(Runtime::Current()->GetHeap()->GetBootImagesStartAddress()),
3791       boot_image_size_(Runtime::Current()->GetHeap()->GetBootImagesSize()),
3792       global_image_begin_(reinterpret_cast<uint8_t*>(image_begin)),
3793       image_objects_offset_begin_(0),
3794       image_infos_(oat_filenames.size()),
3795       jni_stub_map_(JniStubKeyHash(compiler_options.GetInstructionSet()),
3796                     JniStubKeyEquals(compiler_options.GetInstructionSet())),
3797       dirty_methods_(0u),
3798       clean_methods_(0u),
3799       app_class_loader_(class_loader),
3800       boot_image_live_objects_(nullptr),
3801       image_roots_(),
3802       image_storage_mode_(image_storage_mode),
3803       oat_filenames_(oat_filenames),
3804       dex_file_oat_index_map_(dex_file_oat_index_map),
3805       dirty_image_objects_(dirty_image_objects) {
3806   DCHECK(compiler_options.IsBootImage() ||
3807          compiler_options.IsBootImageExtension() ||
3808          compiler_options.IsAppImage());
3809   DCHECK_EQ(compiler_options.IsBootImage(), boot_image_begin_ == 0u);
3810   DCHECK_EQ(compiler_options.IsBootImage(), boot_image_size_ == 0u);
3811   CHECK_NE(image_begin, 0U);
3812   std::fill_n(image_methods_, arraysize(image_methods_), nullptr);
3813   CHECK_EQ(compiler_options.IsBootImage(),
3814            Runtime::Current()->GetHeap()->GetBootImageSpaces().empty())
3815       << "Compiling a boot image should occur iff there are no boot image spaces loaded";
3816   if (compiler_options_.IsAppImage()) {
3817     // Make sure objects are not crossing region boundaries for app images.
3818     region_size_ = gc::space::RegionSpace::kRegionSize;
3819   }
3820 }
3821 
~ImageWriter()3822 ImageWriter::~ImageWriter() {
3823   if (!image_roots_.empty()) {
3824     Thread* self = Thread::Current();
3825     JavaVMExt* vm = down_cast<JNIEnvExt*>(self->GetJniEnv())->GetVm();
3826     for (jobject image_roots : image_roots_) {
3827       vm->DeleteGlobalRef(self, image_roots);
3828     }
3829   }
3830 }
3831 
ImageInfo()3832 ImageWriter::ImageInfo::ImageInfo()
3833     : intern_table_(),
3834       class_table_() {}
3835 
3836 template <typename DestType>
CopyAndFixupReference(DestType * dest,ObjPtr<mirror::Object> src)3837 void ImageWriter::CopyAndFixupReference(DestType* dest, ObjPtr<mirror::Object> src) {
3838   static_assert(std::is_same<DestType, mirror::CompressedReference<mirror::Object>>::value ||
3839                     std::is_same<DestType, mirror::HeapReference<mirror::Object>>::value,
3840                 "DestType must be a Compressed-/HeapReference<Object>.");
3841   dest->Assign(GetImageAddress(src.Ptr()));
3842 }
3843 
3844 template <typename ValueType>
CopyAndFixupPointer(void ** target,ValueType src_value,PointerSize pointer_size)3845 void ImageWriter::CopyAndFixupPointer(
3846     void** target, ValueType src_value, PointerSize pointer_size) {
3847   DCHECK(src_value != nullptr);
3848   void* new_value = NativeLocationInImage(src_value);
3849   DCHECK(new_value != nullptr);
3850   if (pointer_size == PointerSize::k32) {
3851     *reinterpret_cast<uint32_t*>(target) = reinterpret_cast32<uint32_t>(new_value);
3852   } else {
3853     *reinterpret_cast<uint64_t*>(target) = reinterpret_cast64<uint64_t>(new_value);
3854   }
3855 }
3856 
3857 template <typename ValueType>
CopyAndFixupPointer(void ** target,ValueType src_value)3858 void ImageWriter::CopyAndFixupPointer(void** target, ValueType src_value)
3859     REQUIRES_SHARED(Locks::mutator_lock_) {
3860   CopyAndFixupPointer(target, src_value, target_ptr_size_);
3861 }
3862 
3863 template <typename ValueType>
CopyAndFixupPointer(void * object,MemberOffset offset,ValueType src_value,PointerSize pointer_size)3864 void ImageWriter::CopyAndFixupPointer(
3865     void* object, MemberOffset offset, ValueType src_value, PointerSize pointer_size) {
3866   void** target =
3867       reinterpret_cast<void**>(reinterpret_cast<uint8_t*>(object) + offset.Uint32Value());
3868   return CopyAndFixupPointer(target, src_value, pointer_size);
3869 }
3870 
3871 template <typename ValueType>
CopyAndFixupPointer(void * object,MemberOffset offset,ValueType src_value)3872 void ImageWriter::CopyAndFixupPointer(void* object, MemberOffset offset, ValueType src_value) {
3873   return CopyAndFixupPointer(object, offset, src_value, target_ptr_size_);
3874 }
3875 
3876 }  // namespace linker
3877 }  // namespace art
3878