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