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