xref: /aosp_15_r20/art/runtime/gc/space/image_space.cc (revision 795d594fd825385562da6b089ea9b2033f3abf5a)
1 /*
2  * Copyright (C) 2011 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "image_space.h"
18 
19 #include <sys/statvfs.h>
20 #include <sys/types.h>
21 #include <unistd.h>
22 
23 #include <array>
24 #include <memory>
25 #include <optional>
26 #include <random>
27 #include <string>
28 #include <vector>
29 
30 #include "android-base/logging.h"
31 #include "android-base/stringprintf.h"
32 #include "android-base/strings.h"
33 #include "android-base/unique_fd.h"
34 #include "arch/instruction_set.h"
35 #include "art_field-inl.h"
36 #include "art_method-inl.h"
37 #include "base/array_ref.h"
38 #include "base/bit_memory_region.h"
39 #include "base/callee_save_type.h"
40 #include "base/file_utils.h"
41 #include "base/globals.h"
42 #include "base/macros.h"
43 #include "base/memfd.h"
44 #include "base/os.h"
45 #include "base/pointer_size.h"
46 #include "base/stl_util.h"
47 #include "base/systrace.h"
48 #include "base/time_utils.h"
49 #include "base/utils.h"
50 #include "class_root-inl.h"
51 #include "dex/art_dex_file_loader.h"
52 #include "dex/dex_file_loader.h"
53 #include "exec_utils.h"
54 #include "gc/accounting/space_bitmap-inl.h"
55 #include "gc/task_processor.h"
56 #include "intern_table-inl.h"
57 #include "mirror/class-inl.h"
58 #include "mirror/executable-inl.h"
59 #include "mirror/object-inl.h"
60 #include "mirror/object-refvisitor-inl.h"
61 #include "mirror/var_handle.h"
62 #include "oat/image-inl.h"
63 #include "oat/image.h"
64 #include "oat/oat.h"
65 #include "oat/oat_file.h"
66 #include "profile/profile_compilation_info.h"
67 #include "runtime.h"
68 #include "runtime_globals.h"
69 #include "space-inl.h"
70 
71 namespace art HIDDEN {
72 namespace gc {
73 namespace space {
74 
75 namespace {
76 
77 using ::android::base::Join;
78 using ::android::base::StringAppendF;
79 using ::android::base::StringPrintf;
80 
81 // We do not allow the boot image and extensions to take more than 1GiB. They are
82 // supposed to be much smaller and allocating more that this would likely fail anyway.
83 static constexpr size_t kMaxTotalImageReservationSize = 1 * GB;
84 
85 }  // namespace
86 
87 Atomic<uint32_t> ImageSpace::bitmap_index_(0);
88 
ImageSpace(const std::string & image_filename,const char * image_location,const std::vector<std::string> & profile_files,MemMap && mem_map,accounting::ContinuousSpaceBitmap && live_bitmap,uint8_t * end)89 ImageSpace::ImageSpace(const std::string& image_filename,
90                        const char* image_location,
91                        const std::vector<std::string>& profile_files,
92                        MemMap&& mem_map,
93                        accounting::ContinuousSpaceBitmap&& live_bitmap,
94                        uint8_t* end)
95     : MemMapSpace(image_filename,
96                   std::move(mem_map),
97                   mem_map.Begin(),
98                   end,
99                   end,
100                   kGcRetentionPolicyNeverCollect),
101       live_bitmap_(std::move(live_bitmap)),
102       oat_file_non_owned_(nullptr),
103       image_location_(image_location),
104       profile_files_(profile_files) {
105   DCHECK(live_bitmap_.IsValid());
106 }
107 
ChooseRelocationOffsetDelta(int32_t min_delta,int32_t max_delta)108 static int32_t ChooseRelocationOffsetDelta(int32_t min_delta, int32_t max_delta) {
109   CHECK_ALIGNED(min_delta, kElfSegmentAlignment);
110   CHECK_ALIGNED(max_delta, kElfSegmentAlignment);
111   CHECK_LT(min_delta, max_delta);
112 
113   int32_t r = GetRandomNumber<int32_t>(min_delta, max_delta);
114   if (r % 2 == 0) {
115     r = RoundUp(r, kElfSegmentAlignment);
116   } else {
117     r = RoundDown(r, kElfSegmentAlignment);
118   }
119   CHECK_LE(min_delta, r);
120   CHECK_GE(max_delta, r);
121   CHECK_ALIGNED(r, kElfSegmentAlignment);
122   return r;
123 }
124 
ChooseRelocationOffsetDelta()125 static int32_t ChooseRelocationOffsetDelta() {
126   return ChooseRelocationOffsetDelta(ART_BASE_ADDRESS_MIN_DELTA, ART_BASE_ADDRESS_MAX_DELTA);
127 }
128 
FindImageFilenameImpl(const char * image_location,const InstructionSet image_isa,bool * has_system,std::string * system_filename)129 static bool FindImageFilenameImpl(const char* image_location,
130                                   const InstructionSet image_isa,
131                                   bool* has_system,
132                                   std::string* system_filename) {
133   *has_system = false;
134 
135   // image_location = /system/framework/boot.art
136   // system_image_location = /system/framework/<image_isa>/boot.art
137   std::string system_image_filename(GetSystemImageFilename(image_location, image_isa));
138   if (OS::FileExists(system_image_filename.c_str())) {
139     *system_filename = system_image_filename;
140     *has_system = true;
141   }
142 
143   return *has_system;
144 }
145 
FindImageFilename(const char * image_location,const InstructionSet image_isa,std::string * system_filename,bool * has_system)146 bool ImageSpace::FindImageFilename(const char* image_location,
147                                    const InstructionSet image_isa,
148                                    std::string* system_filename,
149                                    bool* has_system) {
150   return FindImageFilenameImpl(image_location,
151                                image_isa,
152                                has_system,
153                                system_filename);
154 }
155 
ReadSpecificImageHeader(File * image_file,const char * file_description,ImageHeader * image_header,std::string * error_msg)156 static bool ReadSpecificImageHeader(File* image_file,
157                                     const char* file_description,
158                                     /*out*/ImageHeader* image_header,
159                                     /*out*/std::string* error_msg) {
160   if (!image_file->PreadFully(image_header, sizeof(ImageHeader), /*offset=*/ 0)) {
161     *error_msg = StringPrintf("Unable to read image header from \"%s\"", file_description);
162     return false;
163   }
164   if (!image_header->IsValid()) {
165     *error_msg = StringPrintf("Image header from \"%s\" is invalid", file_description);
166     return false;
167   }
168   return true;
169 }
170 
ReadSpecificImageHeader(const char * filename,ImageHeader * image_header,std::string * error_msg)171 static bool ReadSpecificImageHeader(const char* filename,
172                                     /*out*/ImageHeader* image_header,
173                                     /*out*/std::string* error_msg) {
174   std::unique_ptr<File> image_file(OS::OpenFileForReading(filename));
175   if (image_file.get() == nullptr) {
176     *error_msg = StringPrintf("Unable to open file \"%s\" for reading image header", filename);
177     return false;
178   }
179   return ReadSpecificImageHeader(image_file.get(), filename, image_header, error_msg);
180 }
181 
ReadSpecificImageHeader(const char * filename,std::string * error_msg)182 static std::unique_ptr<ImageHeader> ReadSpecificImageHeader(const char* filename,
183                                                             std::string* error_msg) {
184   std::unique_ptr<ImageHeader> hdr(new ImageHeader);
185   if (!ReadSpecificImageHeader(filename, hdr.get(), error_msg)) {
186     return nullptr;
187   }
188   return hdr;
189 }
190 
VerifyImageAllocations()191 void ImageSpace::VerifyImageAllocations() {
192   uint8_t* current = Begin() + RoundUp(sizeof(ImageHeader), kObjectAlignment);
193   while (current < End()) {
194     CHECK_ALIGNED(current, kObjectAlignment);
195     auto* obj = reinterpret_cast<mirror::Object*>(current);
196     CHECK(obj->GetClass() != nullptr) << "Image object at address " << obj << " has null class";
197     CHECK(live_bitmap_.Test(obj)) << obj->PrettyTypeOf();
198     if (kUseBakerReadBarrier) {
199       obj->AssertReadBarrierState();
200     }
201     current += RoundUp(obj->SizeOf(), kObjectAlignment);
202   }
203 }
204 
205 // Helper class for relocating from one range of memory to another.
206 class RelocationRange {
207  public:
208   RelocationRange(const RelocationRange&) = default;
RelocationRange(uintptr_t source,uintptr_t dest,uintptr_t length)209   RelocationRange(uintptr_t source, uintptr_t dest, uintptr_t length)
210       : source_(source),
211         dest_(dest),
212         length_(length) {}
213 
InSource(uintptr_t address) const214   bool InSource(uintptr_t address) const {
215     return address - source_ < length_;
216   }
217 
InDest(const void * dest) const218   bool InDest(const void* dest) const {
219     return InDest(reinterpret_cast<uintptr_t>(dest));
220   }
221 
InDest(uintptr_t address) const222   bool InDest(uintptr_t address) const {
223     return address - dest_ < length_;
224   }
225 
226   // Translate a source address to the destination space.
ToDest(uintptr_t address) const227   uintptr_t ToDest(uintptr_t address) const {
228     DCHECK(InSource(address));
229     return address + Delta();
230   }
231 
232   template <typename T>
ToDest(T * src) const233   T* ToDest(T* src) const {
234     return reinterpret_cast<T*>(ToDest(reinterpret_cast<uintptr_t>(src)));
235   }
236 
237   // Returns the delta between the dest from the source.
Delta() const238   uintptr_t Delta() const {
239     return dest_ - source_;
240   }
241 
Source() const242   uintptr_t Source() const {
243     return source_;
244   }
245 
Dest() const246   uintptr_t Dest() const {
247     return dest_;
248   }
249 
Length() const250   uintptr_t Length() const {
251     return length_;
252   }
253 
254  private:
255   const uintptr_t source_;
256   const uintptr_t dest_;
257   const uintptr_t length_;
258 };
259 
operator <<(std::ostream & os,const RelocationRange & reloc)260 std::ostream& operator<<(std::ostream& os, const RelocationRange& reloc) {
261   return os << "(" << reinterpret_cast<const void*>(reloc.Source()) << "-"
262             << reinterpret_cast<const void*>(reloc.Source() + reloc.Length()) << ")->("
263             << reinterpret_cast<const void*>(reloc.Dest()) << "-"
264             << reinterpret_cast<const void*>(reloc.Dest() + reloc.Length()) << ")";
265 }
266 
267 template <PointerSize kPointerSize, typename HeapVisitor, typename NativeVisitor>
268 class ImageSpace::PatchObjectVisitor final {
269  public:
PatchObjectVisitor(HeapVisitor heap_visitor,NativeVisitor native_visitor)270   explicit PatchObjectVisitor(HeapVisitor heap_visitor, NativeVisitor native_visitor)
271       : heap_visitor_(heap_visitor), native_visitor_(native_visitor) {}
272 
VisitClass(ObjPtr<mirror::Class> klass,ObjPtr<mirror::Class> class_class)273   void VisitClass(ObjPtr<mirror::Class> klass, ObjPtr<mirror::Class> class_class)
274       REQUIRES_SHARED(Locks::mutator_lock_) {
275     // A mirror::Class object consists of
276     //  - instance fields inherited from j.l.Object,
277     //  - instance fields inherited from j.l.Class,
278     //  - embedded tables (vtable, interface method table),
279     //  - static fields of the class itself.
280     // The reference fields are at the start of each field section (this is how the
281     // ClassLinker orders fields; except when that would create a gap between superclass
282     // fields and the first reference of the subclass due to alignment, it can be filled
283     // with smaller fields - but that's not the case for j.l.Object and j.l.Class).
284 
285     DCHECK_ALIGNED(klass.Ptr(), kObjectAlignment);
286     static_assert(IsAligned<kHeapReferenceSize>(kObjectAlignment), "Object alignment check.");
287     // First, patch the `klass->klass_`, known to be a reference to the j.l.Class.class.
288     // This should be the only reference field in j.l.Object and we assert that below.
289     DCHECK_EQ(class_class,
290               heap_visitor_(klass->GetClass<kVerifyNone, kWithoutReadBarrier>()));
291     klass->SetFieldObjectWithoutWriteBarrier<
292         /*kTransactionActive=*/ false,
293         /*kCheckTransaction=*/ true,
294         kVerifyNone>(mirror::Object::ClassOffset(), class_class);
295     // Then patch the reference instance fields described by j.l.Class.class.
296     // Use the sizeof(Object) to determine where these reference fields start;
297     // this is the same as `class_class->GetFirstReferenceInstanceFieldOffset()`
298     // after patching but the j.l.Class may not have been patched yet.
299     size_t num_reference_instance_fields = class_class->NumReferenceInstanceFields<kVerifyNone>();
300     DCHECK_NE(num_reference_instance_fields, 0u);
301     static_assert(IsAligned<kHeapReferenceSize>(sizeof(mirror::Object)), "Size alignment check.");
302     MemberOffset instance_field_offset(sizeof(mirror::Object));
303     for (size_t i = 0; i != num_reference_instance_fields; ++i) {
304       PatchReferenceField(klass, instance_field_offset);
305       static_assert(sizeof(mirror::HeapReference<mirror::Object>) == kHeapReferenceSize,
306                     "Heap reference sizes equality check.");
307       instance_field_offset =
308           MemberOffset(instance_field_offset.Uint32Value() + kHeapReferenceSize);
309     }
310     // Now that we have patched the `super_class_`, if this is the j.l.Class.class,
311     // we can get a reference to j.l.Object.class and assert that it has only one
312     // reference instance field (the `klass_` patched above).
313     if (kIsDebugBuild && klass == class_class) {
314       ObjPtr<mirror::Class> object_class =
315           klass->GetSuperClass<kVerifyNone, kWithoutReadBarrier>();
316       CHECK_EQ(object_class->NumReferenceInstanceFields<kVerifyNone>(), 1u);
317     }
318     // Then patch static fields.
319     size_t num_reference_static_fields = klass->NumReferenceStaticFields<kVerifyNone>();
320     if (num_reference_static_fields != 0u) {
321       MemberOffset static_field_offset =
322           klass->GetFirstReferenceStaticFieldOffset<kVerifyNone>(kPointerSize);
323       for (size_t i = 0; i != num_reference_static_fields; ++i) {
324         PatchReferenceField(klass, static_field_offset);
325         static_assert(sizeof(mirror::HeapReference<mirror::Object>) == kHeapReferenceSize,
326                       "Heap reference sizes equality check.");
327         static_field_offset =
328             MemberOffset(static_field_offset.Uint32Value() + kHeapReferenceSize);
329       }
330     }
331     // Then patch native pointers.
332     klass->FixupNativePointers<kVerifyNone>(klass.Ptr(), kPointerSize, *this);
333   }
334 
335   template <typename T>
operator ()(T * ptr,void ** dest_addr) const336   T* operator()(T* ptr, [[maybe_unused]] void** dest_addr) const {
337     return (ptr != nullptr) ? native_visitor_(ptr) : nullptr;
338   }
339 
VisitPointerArray(ObjPtr<mirror::PointerArray> pointer_array)340   void VisitPointerArray(ObjPtr<mirror::PointerArray> pointer_array)
341       REQUIRES_SHARED(Locks::mutator_lock_) {
342     // Fully patch the pointer array, including the `klass_` field.
343     PatchReferenceField</*kMayBeNull=*/ false>(pointer_array, mirror::Object::ClassOffset());
344 
345     int32_t length = pointer_array->GetLength<kVerifyNone>();
346     for (int32_t i = 0; i != length; ++i) {
347       ArtMethod** method_entry = reinterpret_cast<ArtMethod**>(
348           pointer_array->ElementAddress<kVerifyNone>(i, kPointerSize));
349       PatchNativePointer</*kMayBeNull=*/ false>(method_entry);
350     }
351   }
352 
VisitObject(mirror::Object * object)353   void VisitObject(mirror::Object* object) REQUIRES_SHARED(Locks::mutator_lock_) {
354     // Visit all reference fields.
355     object->VisitReferences</*kVisitNativeRoots=*/ false,
356                             kVerifyNone,
357                             kWithoutReadBarrier>(*this, *this);
358     // This function should not be called for classes.
359     DCHECK(!object->IsClass<kVerifyNone>());
360   }
361 
362   // Visitor for VisitReferences().
operator ()(ObjPtr<mirror::Object> object,MemberOffset field_offset,bool is_static) const363   ALWAYS_INLINE void operator()(ObjPtr<mirror::Object> object,
364                                 MemberOffset field_offset,
365                                 bool is_static)
366       const REQUIRES_SHARED(Locks::mutator_lock_) {
367     DCHECK(!is_static);
368     PatchReferenceField(object, field_offset);
369   }
370   // Visitor for VisitReferences(), java.lang.ref.Reference case.
operator ()(ObjPtr<mirror::Class> klass,ObjPtr<mirror::Reference> ref) const371   ALWAYS_INLINE void operator()(ObjPtr<mirror::Class> klass, ObjPtr<mirror::Reference> ref) const
372       REQUIRES_SHARED(Locks::mutator_lock_) {
373     DCHECK(klass->IsTypeOfReferenceClass());
374     this->operator()(ref, mirror::Reference::ReferentOffset(), /*is_static=*/ false);
375   }
376   // Ignore class native roots; not called from VisitReferences() for kVisitNativeRoots == false.
VisitRootIfNonNull(mirror::CompressedReference<mirror::Object> * root) const377   void VisitRootIfNonNull(
378       [[maybe_unused]] mirror::CompressedReference<mirror::Object>* root) const {}
VisitRoot(mirror::CompressedReference<mirror::Object> * root) const379   void VisitRoot([[maybe_unused]] mirror::CompressedReference<mirror::Object>* root) const {}
380 
VisitNativeDexCacheArray(mirror::NativeArray<T> * array)381   template <typename T> void VisitNativeDexCacheArray(mirror::NativeArray<T>* array)
382       REQUIRES_SHARED(Locks::mutator_lock_) {
383     if (array == nullptr) {
384       return;
385     }
386     DCHECK_ALIGNED(array, static_cast<size_t>(kPointerSize));
387     uint32_t size = (kPointerSize == PointerSize::k32)
388         ? reinterpret_cast<uint32_t*>(array)[-1]
389         : dchecked_integral_cast<uint32_t>(reinterpret_cast<uint64_t*>(array)[-1]);
390     for (uint32_t i = 0; i < size; ++i) {
391       PatchNativePointer(array->GetPtrEntryPtrSize(i, kPointerSize));
392     }
393   }
394 
VisitGcRootDexCacheArray(mirror::GcRootArray<T> * array)395   template <typename T> void VisitGcRootDexCacheArray(mirror::GcRootArray<T>* array)
396       REQUIRES_SHARED(Locks::mutator_lock_) {
397     if (array == nullptr) {
398       return;
399     }
400     DCHECK_ALIGNED(array, sizeof(GcRoot<T>));
401     static_assert(sizeof(GcRoot<T>) == sizeof(uint32_t));
402     uint32_t size = reinterpret_cast<uint32_t*>(array)[-1];
403     for (uint32_t i = 0; i < size; ++i) {
404       PatchGcRoot(array->GetGcRootAddress(i));
405     }
406   }
407 
VisitDexCacheArrays(ObjPtr<mirror::DexCache> dex_cache)408   void VisitDexCacheArrays(ObjPtr<mirror::DexCache> dex_cache)
409       REQUIRES_SHARED(Locks::mutator_lock_) {
410     mirror::NativeArray<ArtMethod>* old_resolved_methods = dex_cache->GetResolvedMethodsArray();
411     if (old_resolved_methods != nullptr) {
412       mirror::NativeArray<ArtMethod>* resolved_methods = native_visitor_(old_resolved_methods);
413       dex_cache->SetResolvedMethodsArray(resolved_methods);
414       VisitNativeDexCacheArray(resolved_methods);
415     }
416 
417     mirror::NativeArray<ArtField>* old_resolved_fields = dex_cache->GetResolvedFieldsArray();
418     if (old_resolved_fields != nullptr) {
419       mirror::NativeArray<ArtField>* resolved_fields = native_visitor_(old_resolved_fields);
420       dex_cache->SetResolvedFieldsArray(resolved_fields);
421       VisitNativeDexCacheArray(resolved_fields);
422     }
423 
424     mirror::GcRootArray<mirror::String>* old_strings = dex_cache->GetStringsArray();
425     if (old_strings != nullptr) {
426       mirror::GcRootArray<mirror::String>* strings = native_visitor_(old_strings);
427       dex_cache->SetStringsArray(strings);
428       VisitGcRootDexCacheArray(strings);
429     }
430 
431     mirror::GcRootArray<mirror::Class>* old_types = dex_cache->GetResolvedTypesArray();
432     if (old_types != nullptr) {
433       mirror::GcRootArray<mirror::Class>* types = native_visitor_(old_types);
434       dex_cache->SetResolvedTypesArray(types);
435       VisitGcRootDexCacheArray(types);
436     }
437   }
438 
439   template <bool kMayBeNull = true, typename T>
PatchGcRoot(GcRoot<T> * root) const440   ALWAYS_INLINE void PatchGcRoot(/*inout*/GcRoot<T>* root) const
441       REQUIRES_SHARED(Locks::mutator_lock_) {
442     static_assert(sizeof(GcRoot<mirror::Class*>) == sizeof(uint32_t), "GcRoot size check");
443     T* old_value = root->template Read<kWithoutReadBarrier>();
444     DCHECK(kMayBeNull || old_value != nullptr);
445     if (!kMayBeNull || old_value != nullptr) {
446       *root = GcRoot<T>(heap_visitor_(old_value));
447     }
448   }
449 
450   template <bool kMayBeNull = true, typename T>
PatchNativePointer(T ** entry) const451   ALWAYS_INLINE void PatchNativePointer(/*inout*/T** entry) const {
452     if (kPointerSize == PointerSize::k64) {
453       uint64_t* raw_entry = reinterpret_cast<uint64_t*>(entry);
454       T* old_value = reinterpret_cast64<T*>(*raw_entry);
455       DCHECK(kMayBeNull || old_value != nullptr);
456       if (!kMayBeNull || old_value != nullptr) {
457         T* new_value = native_visitor_(old_value);
458         *raw_entry = reinterpret_cast64<uint64_t>(new_value);
459       }
460     } else {
461       uint32_t* raw_entry = reinterpret_cast<uint32_t*>(entry);
462       T* old_value = reinterpret_cast32<T*>(*raw_entry);
463       DCHECK(kMayBeNull || old_value != nullptr);
464       if (!kMayBeNull || old_value != nullptr) {
465         T* new_value = native_visitor_(old_value);
466         *raw_entry = reinterpret_cast32<uint32_t>(new_value);
467       }
468     }
469   }
470 
471   template <bool kMayBeNull = true>
PatchReferenceField(ObjPtr<mirror::Object> object,MemberOffset offset) const472   ALWAYS_INLINE void PatchReferenceField(ObjPtr<mirror::Object> object, MemberOffset offset) const
473       REQUIRES_SHARED(Locks::mutator_lock_) {
474     ObjPtr<mirror::Object> old_value =
475         object->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(offset);
476     DCHECK(kMayBeNull || old_value != nullptr);
477     if (!kMayBeNull || old_value != nullptr) {
478       ObjPtr<mirror::Object> new_value = heap_visitor_(old_value.Ptr());
479       object->SetFieldObjectWithoutWriteBarrier</*kTransactionActive=*/ false,
480                                                 /*kCheckTransaction=*/ true,
481                                                 kVerifyNone>(offset, new_value);
482     }
483   }
484 
485  private:
486   // Heap objects visitor.
487   HeapVisitor heap_visitor_;
488 
489   // Native objects visitor.
490   NativeVisitor native_visitor_;
491 };
492 
493 template <typename ReferenceVisitor>
494 class ImageSpace::ClassTableVisitor final {
495  public:
ClassTableVisitor(const ReferenceVisitor & reference_visitor)496   explicit ClassTableVisitor(const ReferenceVisitor& reference_visitor)
497       : reference_visitor_(reference_visitor) {}
498 
VisitRoot(mirror::CompressedReference<mirror::Object> * root) const499   void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
500       REQUIRES_SHARED(Locks::mutator_lock_) {
501     DCHECK(root->AsMirrorPtr() != nullptr);
502     root->Assign(reference_visitor_(root->AsMirrorPtr()));
503   }
504 
505  private:
506   ReferenceVisitor reference_visitor_;
507 };
508 
509 class ImageSpace::RemapInternedStringsVisitor {
510  public:
RemapInternedStringsVisitor(const SafeMap<mirror::String *,mirror::String * > & intern_remap)511   explicit RemapInternedStringsVisitor(
512       const SafeMap<mirror::String*, mirror::String*>& intern_remap)
513       REQUIRES_SHARED(Locks::mutator_lock_)
514       : intern_remap_(intern_remap),
515         string_class_(GetStringClass()) {}
516 
517   // Visitor for VisitReferences().
operator ()(ObjPtr<mirror::Object> object,MemberOffset field_offset,bool is_static) const518   ALWAYS_INLINE void operator()(ObjPtr<mirror::Object> object,
519                                 MemberOffset field_offset,
520                                 [[maybe_unused]] bool is_static) const
521       REQUIRES_SHARED(Locks::mutator_lock_) {
522     ObjPtr<mirror::Object> old_value =
523         object->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(field_offset);
524     if (old_value != nullptr &&
525         old_value->GetClass<kVerifyNone, kWithoutReadBarrier>() == string_class_) {
526       auto it = intern_remap_.find(old_value->AsString().Ptr());
527       if (it != intern_remap_.end()) {
528         mirror::String* new_value = it->second;
529         object->SetFieldObjectWithoutWriteBarrier</*kTransactionActive=*/ false,
530                                                   /*kCheckTransaction=*/ true,
531                                                   kVerifyNone>(field_offset, new_value);
532       }
533     }
534   }
535   // Visitor for VisitReferences(), java.lang.ref.Reference case.
operator ()(ObjPtr<mirror::Class> klass,ObjPtr<mirror::Reference> ref) const536   ALWAYS_INLINE void operator()(ObjPtr<mirror::Class> klass, ObjPtr<mirror::Reference> ref) const
537       REQUIRES_SHARED(Locks::mutator_lock_) {
538     DCHECK(klass->IsTypeOfReferenceClass());
539     this->operator()(ref, mirror::Reference::ReferentOffset(), /*is_static=*/ false);
540   }
541   // Ignore class native roots; not called from VisitReferences() for kVisitNativeRoots == false.
VisitRootIfNonNull(mirror::CompressedReference<mirror::Object> * root) const542   void VisitRootIfNonNull(
543       [[maybe_unused]] mirror::CompressedReference<mirror::Object>* root) const {}
VisitRoot(mirror::CompressedReference<mirror::Object> * root) const544   void VisitRoot([[maybe_unused]] mirror::CompressedReference<mirror::Object>* root) const {}
545 
546  private:
GetStringClass()547   mirror::Class* GetStringClass() REQUIRES_SHARED(Locks::mutator_lock_) {
548     DCHECK(!intern_remap_.empty());
549     return intern_remap_.begin()->first->GetClass<kVerifyNone, kWithoutReadBarrier>();
550   }
551 
552   const SafeMap<mirror::String*, mirror::String*>& intern_remap_;
553   mirror::Class* const string_class_;
554 };
555 
556 // Helper class encapsulating loading, so we can access private ImageSpace members (this is a
557 // nested class), but not declare functions in the header.
558 class ImageSpace::Loader {
559  public:
InitAppImage(const char * image_filename,const char * image_location,const OatFile * oat_file,ArrayRef<ImageSpace * const> boot_image_spaces,std::string * error_msg)560   static std::unique_ptr<ImageSpace> InitAppImage(const char* image_filename,
561                                                   const char* image_location,
562                                                   const OatFile* oat_file,
563                                                   ArrayRef<ImageSpace* const> boot_image_spaces,
564                                                   /*out*/std::string* error_msg)
565         REQUIRES(!Locks::mutator_lock_) {
566     TimingLogger logger(__PRETTY_FUNCTION__, /*precise=*/ true, VLOG_IS_ON(image));
567 
568     if (gPageSize != kMinPageSize) {
569       *error_msg = "Loading app image is only supported on devices with 4K page size";
570       return nullptr;
571     }
572 
573     std::unique_ptr<ImageSpace> space = Init(image_filename,
574                                              image_location,
575                                              &logger,
576                                              /*image_reservation=*/ nullptr,
577                                              error_msg);
578     if (space != nullptr) {
579       space->oat_file_non_owned_ = oat_file;
580       const ImageHeader& image_header = space->GetImageHeader();
581 
582       // Check the oat file checksum.
583       const uint32_t oat_checksum = oat_file->GetOatHeader().GetChecksum();
584       const uint32_t image_oat_checksum = image_header.GetOatChecksum();
585       // Note image_oat_checksum is 0 for images generated by the runtime.
586       if (image_oat_checksum != 0u && oat_checksum != image_oat_checksum) {
587         *error_msg = StringPrintf("Oat checksum 0x%x does not match the image one 0x%x in image %s",
588                                   oat_checksum,
589                                   image_oat_checksum,
590                                   image_filename);
591         return nullptr;
592       }
593       size_t boot_image_space_dependencies;
594       if (!ValidateBootImageChecksum(image_filename,
595                                      image_header,
596                                      oat_file,
597                                      boot_image_spaces,
598                                      &boot_image_space_dependencies,
599                                      error_msg)) {
600         DCHECK(!error_msg->empty());
601         return nullptr;
602       }
603 
604       uint32_t expected_reservation_size = RoundUp(image_header.GetImageSize(),
605           kElfSegmentAlignment);
606       if (!CheckImageReservationSize(*space, expected_reservation_size, error_msg) ||
607           !CheckImageComponentCount(*space, /*expected_component_count=*/ 1u, error_msg)) {
608         return nullptr;
609       }
610 
611       {
612         TimingLogger::ScopedTiming timing("RelocateImage", &logger);
613         const PointerSize pointer_size = image_header.GetPointerSize();
614         uint32_t boot_image_begin =
615             reinterpret_cast32<uint32_t>(boot_image_spaces.front()->Begin());
616         bool result;
617         if (pointer_size == PointerSize::k64) {
618           result = RelocateInPlace<PointerSize::k64>(boot_image_begin,
619                                                      space->GetMemMap()->Begin(),
620                                                      space->GetLiveBitmap(),
621                                                      oat_file,
622                                                      error_msg);
623         } else {
624           result = RelocateInPlace<PointerSize::k32>(boot_image_begin,
625                                                      space->GetMemMap()->Begin(),
626                                                      space->GetLiveBitmap(),
627                                                      oat_file,
628                                                      error_msg);
629         }
630         if (!result) {
631           return nullptr;
632         }
633       }
634 
635       DCHECK_LE(boot_image_space_dependencies, boot_image_spaces.size());
636       if (boot_image_space_dependencies != boot_image_spaces.size()) {
637         TimingLogger::ScopedTiming timing("DeduplicateInternedStrings", &logger);
638         // There shall be no duplicates with boot image spaces this app image depends on.
639         ArrayRef<ImageSpace* const> old_spaces =
640             boot_image_spaces.SubArray(/*pos=*/ boot_image_space_dependencies);
641         SafeMap<mirror::String*, mirror::String*> intern_remap;
642         ScopedObjectAccess soa(Thread::Current());
643         RemoveInternTableDuplicates(old_spaces, space.get(), &intern_remap);
644         if (!intern_remap.empty()) {
645           RemapInternedStringDuplicates(intern_remap, space.get());
646         }
647       }
648 
649       const ImageHeader& primary_header = boot_image_spaces.front()->GetImageHeader();
650       static_assert(static_cast<size_t>(ImageHeader::kResolutionMethod) == 0u);
651       for (size_t i = 0u; i != static_cast<size_t>(ImageHeader::kImageMethodsCount); ++i) {
652         ImageHeader::ImageMethod method = static_cast<ImageHeader::ImageMethod>(i);
653         CHECK_EQ(primary_header.GetImageMethod(method), image_header.GetImageMethod(method))
654             << method;
655       }
656 
657       VLOG(image) << "ImageSpace::Loader::InitAppImage exiting " << *space.get();
658     }
659     if (VLOG_IS_ON(image)) {
660       logger.Dump(LOG_STREAM(INFO));
661     }
662     return space;
663   }
664 
Init(const char * image_filename,const char * image_location,TimingLogger * logger,MemMap * image_reservation,std::string * error_msg)665   static std::unique_ptr<ImageSpace> Init(const char* image_filename,
666                                           const char* image_location,
667                                           TimingLogger* logger,
668                                           /*inout*/MemMap* image_reservation,
669                                           /*out*/std::string* error_msg) {
670     CHECK(image_filename != nullptr);
671     CHECK(image_location != nullptr);
672 
673     std::unique_ptr<File> file;
674     {
675       TimingLogger::ScopedTiming timing("OpenImageFile", logger);
676       file.reset(OS::OpenFileForReading(image_filename));
677       if (file == nullptr) {
678         *error_msg = StringPrintf("Failed to open '%s'", image_filename);
679         return nullptr;
680       }
681     }
682     return Init(file.get(),
683                 image_filename,
684                 image_location,
685                 /*profile_files=*/ {},
686                 /*allow_direct_mapping=*/ true,
687                 logger,
688                 image_reservation,
689                 error_msg);
690   }
691 
Init(File * file,const char * image_filename,const char * image_location,const std::vector<std::string> & profile_files,bool allow_direct_mapping,TimingLogger * logger,MemMap * image_reservation,std::string * error_msg)692   static std::unique_ptr<ImageSpace> Init(File* file,
693                                           const char* image_filename,
694                                           const char* image_location,
695                                           const std::vector<std::string>& profile_files,
696                                           bool allow_direct_mapping,
697                                           TimingLogger* logger,
698                                           /*inout*/MemMap* image_reservation,
699                                           /*out*/std::string* error_msg) {
700     CHECK(image_filename != nullptr);
701     CHECK(image_location != nullptr);
702 
703     VLOG(image) << "ImageSpace::Init entering image_filename=" << image_filename;
704 
705     ImageHeader image_header;
706     {
707       TimingLogger::ScopedTiming timing("ReadImageHeader", logger);
708       bool success = file->PreadFully(&image_header, sizeof(image_header), /*offset=*/ 0u);
709       if (!success || !image_header.IsValid()) {
710         *error_msg = StringPrintf("Invalid image header in '%s'", image_filename);
711         return nullptr;
712       }
713     }
714     // Check that the file is larger or equal to the header size + data size.
715     const uint64_t image_file_size = static_cast<uint64_t>(file->GetLength());
716     if (image_file_size < sizeof(ImageHeader) + image_header.GetDataSize()) {
717       *error_msg = StringPrintf(
718           "Image file truncated: %" PRIu64 " vs. %" PRIu64 ".",
719            image_file_size,
720            static_cast<uint64_t>(sizeof(ImageHeader) + image_header.GetDataSize()));
721       return nullptr;
722     }
723 
724     if (VLOG_IS_ON(startup)) {
725       LOG(INFO) << "Dumping image sections";
726       for (size_t i = 0; i < ImageHeader::kSectionCount; ++i) {
727         const auto section_idx = static_cast<ImageHeader::ImageSections>(i);
728         auto& section = image_header.GetImageSection(section_idx);
729         LOG(INFO) << section_idx << " start="
730             << reinterpret_cast<void*>(image_header.GetImageBegin() + section.Offset()) << " "
731             << section;
732       }
733     }
734 
735     const auto& bitmap_section = image_header.GetImageBitmapSection();
736     // The location we want to map from is the first aligned page after the end of the stored
737     // (possibly compressed) data.
738     const size_t image_bitmap_offset =
739         RoundUp(sizeof(ImageHeader) + image_header.GetDataSize(), kElfSegmentAlignment);
740     const size_t end_of_bitmap = image_bitmap_offset + bitmap_section.Size();
741     if (end_of_bitmap != image_file_size) {
742       *error_msg = StringPrintf(
743           "Image file size does not equal end of bitmap: size=%" PRIu64 " vs. %zu.",
744           image_file_size,
745           end_of_bitmap);
746       return nullptr;
747     }
748 
749     // GetImageBegin is the preferred address to map the image. If we manage to map the
750     // image at the image begin, the amount of fixup work required is minimized.
751     // If it is pic we will retry with error_msg for the2 failure case. Pass a null error_msg to
752     // avoid reading proc maps for a mapping failure and slowing everything down.
753     // For the boot image, we have already reserved the memory and we load the image
754     // into the `image_reservation`.
755     MemMap map = LoadImageFile(
756         image_filename,
757         image_location,
758         image_header,
759         file->Fd(),
760         allow_direct_mapping,
761         logger,
762         image_reservation,
763         error_msg);
764     if (!map.IsValid()) {
765       DCHECK(!error_msg->empty());
766       return nullptr;
767     }
768     DCHECK_EQ(0, memcmp(&image_header, map.Begin(), sizeof(ImageHeader)));
769 
770     MemMap image_bitmap_map = MemMap::MapFile(bitmap_section.Size(),
771                                               PROT_READ,
772                                               MAP_PRIVATE,
773                                               file->Fd(),
774                                               image_bitmap_offset,
775                                               /*low_4gb=*/ false,
776                                               image_filename,
777                                               error_msg);
778     if (!image_bitmap_map.IsValid()) {
779       *error_msg = StringPrintf("Failed to map image bitmap: %s", error_msg->c_str());
780       return nullptr;
781     }
782     const uint32_t bitmap_index = ImageSpace::bitmap_index_.fetch_add(1);
783     std::string bitmap_name(StringPrintf("imagespace %s live-bitmap %u",
784                                          image_filename,
785                                          bitmap_index));
786     // Bitmap only needs to cover until the end of the mirror objects section.
787     const ImageSection& image_objects = image_header.GetObjectsSection();
788     // We only want the mirror object, not the ArtFields and ArtMethods.
789     uint8_t* const image_end = map.Begin() + image_objects.End();
790     accounting::ContinuousSpaceBitmap bitmap;
791     {
792       TimingLogger::ScopedTiming timing("CreateImageBitmap", logger);
793       bitmap = accounting::ContinuousSpaceBitmap::CreateFromMemMap(
794           bitmap_name,
795           std::move(image_bitmap_map),
796           reinterpret_cast<uint8_t*>(map.Begin()),
797           // Make sure the bitmap is aligned to card size instead of just bitmap word size.
798           RoundUp(image_objects.End(), gc::accounting::CardTable::kCardSize));
799       if (!bitmap.IsValid()) {
800         *error_msg = StringPrintf("Could not create bitmap '%s'", bitmap_name.c_str());
801         return nullptr;
802       }
803     }
804     // We only want the mirror object, not the ArtFields and ArtMethods.
805     std::unique_ptr<ImageSpace> space(new ImageSpace(image_filename,
806                                                      image_location,
807                                                      profile_files,
808                                                      std::move(map),
809                                                      std::move(bitmap),
810                                                      image_end));
811     return space;
812   }
813 
CheckImageComponentCount(const ImageSpace & space,uint32_t expected_component_count,std::string * error_msg)814   static bool CheckImageComponentCount(const ImageSpace& space,
815                                        uint32_t expected_component_count,
816                                        /*out*/std::string* error_msg) {
817     const ImageHeader& header = space.GetImageHeader();
818     if (header.GetComponentCount() != expected_component_count) {
819       *error_msg = StringPrintf("Unexpected component count in %s, received %u, expected %u",
820                                 space.GetImageFilename().c_str(),
821                                 header.GetComponentCount(),
822                                 expected_component_count);
823       return false;
824     }
825     return true;
826   }
827 
CheckImageReservationSize(const ImageSpace & space,uint32_t expected_reservation_size,std::string * error_msg)828   static bool CheckImageReservationSize(const ImageSpace& space,
829                                         uint32_t expected_reservation_size,
830                                         /*out*/std::string* error_msg) {
831     const ImageHeader& header = space.GetImageHeader();
832     if (header.GetImageReservationSize() != expected_reservation_size) {
833       *error_msg = StringPrintf("Unexpected reservation size in %s, received %u, expected %u",
834                                 space.GetImageFilename().c_str(),
835                                 header.GetImageReservationSize(),
836                                 expected_reservation_size);
837       return false;
838     }
839     return true;
840   }
841 
842   template <typename Container>
RemoveInternTableDuplicates(const Container & old_spaces,ImageSpace * new_space,SafeMap<mirror::String *,mirror::String * > * intern_remap)843   static void RemoveInternTableDuplicates(
844       const Container& old_spaces,
845       /*inout*/ImageSpace* new_space,
846       /*inout*/SafeMap<mirror::String*, mirror::String*>* intern_remap)
847       REQUIRES_SHARED(Locks::mutator_lock_) {
848     const ImageSection& new_interns = new_space->GetImageHeader().GetInternedStringsSection();
849     if (new_interns.Size() != 0u) {
850       const uint8_t* new_data = new_space->Begin() + new_interns.Offset();
851       size_t new_read_count;
852       InternTable::UnorderedSet new_set(new_data, /*make_copy_of_data=*/ false, &new_read_count);
853       for (const auto& old_space : old_spaces) {
854         const ImageSection& old_interns = old_space->GetImageHeader().GetInternedStringsSection();
855         if (old_interns.Size() != 0u) {
856           const uint8_t* old_data = old_space->Begin() + old_interns.Offset();
857           size_t old_read_count;
858           InternTable::UnorderedSet old_set(
859               old_data, /*make_copy_of_data=*/ false, &old_read_count);
860           RemoveDuplicates(old_set, &new_set, intern_remap);
861         }
862       }
863     }
864   }
865 
RemapInternedStringDuplicates(const SafeMap<mirror::String *,mirror::String * > & intern_remap,ImageSpace * new_space)866   static void RemapInternedStringDuplicates(
867       const SafeMap<mirror::String*, mirror::String*>& intern_remap,
868       ImageSpace* new_space) REQUIRES_SHARED(Locks::mutator_lock_) {
869     RemapInternedStringsVisitor visitor(intern_remap);
870     static_assert(IsAligned<kObjectAlignment>(sizeof(ImageHeader)), "Header alignment check");
871     uint32_t objects_end = new_space->GetImageHeader().GetObjectsSection().Size();
872     DCHECK_ALIGNED(objects_end, kObjectAlignment);
873     for (uint32_t pos = sizeof(ImageHeader); pos != objects_end; ) {
874       mirror::Object* object = reinterpret_cast<mirror::Object*>(new_space->Begin() + pos);
875       object->VisitReferences</*kVisitNativeRoots=*/ false,
876                               kVerifyNone,
877                               kWithoutReadBarrier>(visitor, visitor);
878       pos += RoundUp(object->SizeOf<kVerifyNone>(), kObjectAlignment);
879     }
880   }
881 
882  private:
883   // Remove duplicates found in the `old_set` from the `new_set`.
884   // Record the removed Strings for remapping. No read barriers are needed as the
885   // tables are either just being loaded and not yet a part of the heap, or boot
886   // image intern tables with non-moveable Strings used when loading an app image.
RemoveDuplicates(const InternTable::UnorderedSet & old_set,InternTable::UnorderedSet * new_set,SafeMap<mirror::String *,mirror::String * > * intern_remap)887   static void RemoveDuplicates(const InternTable::UnorderedSet& old_set,
888                                /*inout*/InternTable::UnorderedSet* new_set,
889                                /*inout*/SafeMap<mirror::String*, mirror::String*>* intern_remap)
890       REQUIRES_SHARED(Locks::mutator_lock_) {
891     if (old_set.size() < new_set->size()) {
892       for (const GcRoot<mirror::String>& old_s : old_set) {
893         auto new_it = new_set->find(old_s);
894         if (UNLIKELY(new_it != new_set->end())) {
895           intern_remap->Put(new_it->Read<kWithoutReadBarrier>(), old_s.Read<kWithoutReadBarrier>());
896           new_set->erase(new_it);
897         }
898       }
899     } else {
900       for (auto new_it = new_set->begin(), end = new_set->end(); new_it != end; ) {
901         auto old_it = old_set.find(*new_it);
902         if (UNLIKELY(old_it != old_set.end())) {
903           intern_remap->Put(new_it->Read<kWithoutReadBarrier>(),
904                             old_it->Read<kWithoutReadBarrier>());
905           new_it = new_set->erase(new_it);
906         } else {
907           ++new_it;
908         }
909       }
910     }
911   }
912 
ValidateBootImageChecksum(const char * image_filename,const ImageHeader & image_header,const OatFile * oat_file,ArrayRef<ImageSpace * const> boot_image_spaces,size_t * boot_image_space_dependencies,std::string * error_msg)913   static bool ValidateBootImageChecksum(const char* image_filename,
914                                         const ImageHeader& image_header,
915                                         const OatFile* oat_file,
916                                         ArrayRef<ImageSpace* const> boot_image_spaces,
917                                         /*out*/size_t* boot_image_space_dependencies,
918                                         /*out*/std::string* error_msg) {
919     // Use the boot image component count to calculate the checksum from
920     // the appropriate number of boot image chunks.
921     uint32_t boot_image_component_count = image_header.GetBootImageComponentCount();
922     size_t expected_image_component_count = ImageSpace::GetNumberOfComponents(boot_image_spaces);
923     if (boot_image_component_count > expected_image_component_count) {
924       *error_msg = StringPrintf("Too many boot image dependencies (%u > %zu) in image %s",
925                                 boot_image_component_count,
926                                 expected_image_component_count,
927                                 image_filename);
928       return false;
929     }
930     uint32_t checksum = 0u;
931     size_t chunk_count = 0u;
932     size_t space_pos = 0u;
933     uint64_t boot_image_size = 0u;
934     for (size_t component_count = 0u; component_count != boot_image_component_count; ) {
935       const ImageHeader& current_header = boot_image_spaces[space_pos]->GetImageHeader();
936       if (current_header.GetComponentCount() > boot_image_component_count - component_count) {
937         *error_msg = StringPrintf("Boot image component count in %s ends in the middle of a chunk, "
938                                       "%u is between %zu and %zu",
939                                   image_filename,
940                                   boot_image_component_count,
941                                   component_count,
942                                   component_count + current_header.GetComponentCount());
943         return false;
944       }
945       component_count += current_header.GetComponentCount();
946       checksum ^= current_header.GetImageChecksum();
947       chunk_count += 1u;
948       space_pos += current_header.GetImageSpaceCount();
949       boot_image_size += current_header.GetImageReservationSize();
950     }
951     if (image_header.GetBootImageChecksum() != checksum) {
952       *error_msg = StringPrintf("Boot image checksum mismatch (0x%08x != 0x%08x) in image %s",
953                                 image_header.GetBootImageChecksum(),
954                                 checksum,
955                                 image_filename);
956       return false;
957     }
958     if (image_header.GetBootImageSize() != boot_image_size) {
959       *error_msg = StringPrintf("Boot image size mismatch (0x%08x != 0x%08" PRIx64 ") in image %s",
960                                 image_header.GetBootImageSize(),
961                                 boot_image_size,
962                                 image_filename);
963       return false;
964     }
965     // Oat checksums, if present, have already been validated, so we know that
966     // they match the loaded image spaces. Therefore, we just verify that they
967     // are consistent in the number of boot image chunks they list by looking
968     // for the kImageChecksumPrefix at the start of each component.
969     const char* oat_boot_class_path_checksums =
970         oat_file->GetOatHeader().GetStoreValueByKey(OatHeader::kBootClassPathChecksumsKey);
971     if (oat_boot_class_path_checksums != nullptr) {
972       size_t oat_bcp_chunk_count = 0u;
973       while (*oat_boot_class_path_checksums == kImageChecksumPrefix) {
974         oat_bcp_chunk_count += 1u;
975         // Find the start of the next component if any.
976         const char* separator = strchr(oat_boot_class_path_checksums, ':');
977         oat_boot_class_path_checksums = (separator != nullptr) ? separator + 1u : "";
978       }
979       if (oat_bcp_chunk_count != chunk_count) {
980         *error_msg = StringPrintf("Boot image chunk count mismatch (%zu != %zu) in image %s",
981                                   oat_bcp_chunk_count,
982                                   chunk_count,
983                                   image_filename);
984         return false;
985       }
986     }
987     *boot_image_space_dependencies = space_pos;
988     return true;
989   }
990 
LoadImageFile(const char * image_filename,const char * image_location,const ImageHeader & image_header,int fd,bool allow_direct_mapping,TimingLogger * logger,MemMap * image_reservation,std::string * error_msg)991   static MemMap LoadImageFile(const char* image_filename,
992                               const char* image_location,
993                               const ImageHeader& image_header,
994                               int fd,
995                               bool allow_direct_mapping,
996                               TimingLogger* logger,
997                               /*inout*/MemMap* image_reservation,
998                               /*out*/std::string* error_msg) {
999     TimingLogger::ScopedTiming timing("MapImageFile", logger);
1000 
1001     // The runtime might not be available at this point if we're running dex2oat or oatdump, in
1002     // which case we just truncate the madvise optimization limit completely.
1003     Runtime* runtime = Runtime::Current();
1004     const size_t madvise_size_limit = runtime ? runtime->GetMadviseWillNeedSizeArt() : 0;
1005 
1006     const bool is_compressed = image_header.HasCompressedBlock();
1007     if (!is_compressed && allow_direct_mapping) {
1008       uint8_t* address = (image_reservation != nullptr) ? image_reservation->Begin() : nullptr;
1009       // The reserved memory size is aligned up to kElfSegmentAlignment to ensure
1010       // that the next reserved area will be aligned to the value.
1011       MemMap map = MemMap::MapFileAtAddress(
1012           address,
1013           CondRoundUp<kPageSizeAgnostic>(image_header.GetImageSize(), kElfSegmentAlignment),
1014           PROT_READ | PROT_WRITE,
1015           MAP_PRIVATE,
1016           fd,
1017           /*start=*/0,
1018           /*low_4gb=*/true,
1019           image_filename,
1020           /*reuse=*/false,
1021           image_reservation,
1022           error_msg);
1023       if (map.IsValid()) {
1024         Runtime::MadviseFileForRange(
1025             madvise_size_limit, map.Size(), map.Begin(), map.End(), image_filename);
1026       }
1027       return map;
1028     }
1029 
1030     // Reserve output and copy/decompress into it.
1031     // The reserved memory size is aligned up to kElfSegmentAlignment to ensure
1032     // that the next reserved area will be aligned to the value.
1033     MemMap map = MemMap::MapAnonymous(image_location,
1034                                       CondRoundUp<kPageSizeAgnostic>(image_header.GetImageSize(),
1035                                                                      kElfSegmentAlignment),
1036                                       PROT_READ | PROT_WRITE,
1037                                       /*low_4gb=*/ true,
1038                                       image_reservation,
1039                                       error_msg);
1040     if (map.IsValid()) {
1041       const size_t stored_size = image_header.GetDataSize();
1042       MemMap temp_map = MemMap::MapFile(sizeof(ImageHeader) + stored_size,
1043                                         PROT_READ,
1044                                         MAP_PRIVATE,
1045                                         fd,
1046                                         /*start=*/ 0,
1047                                         /*low_4gb=*/ false,
1048                                         image_filename,
1049                                         error_msg);
1050       if (!temp_map.IsValid()) {
1051         DCHECK(error_msg == nullptr || !error_msg->empty());
1052         return MemMap::Invalid();
1053       }
1054 
1055       Runtime::MadviseFileForRange(
1056           madvise_size_limit, temp_map.Size(), temp_map.Begin(), temp_map.End(), image_filename);
1057 
1058       if (is_compressed) {
1059         memcpy(map.Begin(), &image_header, sizeof(ImageHeader));
1060 
1061         Runtime::ScopedThreadPoolUsage stpu;
1062         ThreadPool* const pool = stpu.GetThreadPool();
1063         const uint64_t start = NanoTime();
1064         Thread* const self = Thread::Current();
1065         static constexpr size_t kMinBlocks = 2u;
1066         const bool use_parallel = pool != nullptr && image_header.GetBlockCount() >= kMinBlocks;
1067         bool failed_decompression = false;
1068         for (const ImageHeader::Block& block : image_header.GetBlocks(temp_map.Begin())) {
1069           auto function = [&](Thread*) {
1070             const uint64_t start2 = NanoTime();
1071             ScopedTrace trace("LZ4 decompress block");
1072             bool result = block.Decompress(/*out_ptr=*/map.Begin(),
1073                                            /*in_ptr=*/temp_map.Begin(),
1074                                            error_msg);
1075             if (!result) {
1076               failed_decompression = true;
1077               if (error_msg != nullptr) {
1078                 *error_msg = "Failed to decompress image block " + *error_msg;
1079               }
1080             }
1081             VLOG(image) << "Decompress block " << block.GetDataSize() << " -> "
1082                         << block.GetImageSize() << " in " << PrettyDuration(NanoTime() - start2);
1083           };
1084           if (use_parallel) {
1085             pool->AddTask(self, new FunctionTask(std::move(function)));
1086           } else {
1087             function(self);
1088           }
1089         }
1090         if (use_parallel) {
1091           ScopedTrace trace("Waiting for workers");
1092           pool->Wait(self, true, false);
1093         }
1094         const uint64_t time = NanoTime() - start;
1095         // Add one 1 ns to prevent possible divide by 0.
1096         VLOG(image) << "Decompressing image took " << PrettyDuration(time) << " ("
1097                     << PrettySize(static_cast<uint64_t>(map.Size()) * MsToNs(1000) / (time + 1))
1098                     << "/s)";
1099         if (failed_decompression) {
1100           DCHECK(error_msg == nullptr || !error_msg->empty());
1101           return MemMap::Invalid();
1102         }
1103       } else {
1104         DCHECK(!allow_direct_mapping);
1105         // We do not allow direct mapping for boot image extensions compiled to a memfd.
1106         // This prevents wasting memory by kernel keeping the contents of the file alive
1107         // despite these contents being unreachable once the file descriptor is closed
1108         // and mmapped memory is copied for all existing mappings.
1109         //
1110         // Most pages would be copied during relocation while there is only one mapping.
1111         // We could use MAP_SHARED for relocation and then msync() and remap MAP_PRIVATE
1112         // as required for forking from zygote, but there would still be some pages
1113         // wasted anyway and we want to avoid that. (For example, static synchronized
1114         // methods use the class object for locking and thus modify its lockword.)
1115 
1116         // No other process should race to overwrite the extension in memfd.
1117         DCHECK_EQ(memcmp(temp_map.Begin(), &image_header, sizeof(ImageHeader)), 0);
1118         memcpy(map.Begin(), temp_map.Begin(), temp_map.Size());
1119       }
1120     }
1121 
1122     return map;
1123   }
1124 
1125   class EmptyRange {
1126    public:
InSource(uintptr_t) const1127     ALWAYS_INLINE bool InSource(uintptr_t) const { return false; }
InDest(uintptr_t) const1128     ALWAYS_INLINE bool InDest(uintptr_t) const { return false; }
ToDest(uintptr_t) const1129     ALWAYS_INLINE uintptr_t ToDest(uintptr_t) const {
1130       LOG(FATAL) << "Unreachable";
1131       UNREACHABLE();
1132     }
1133   };
1134 
1135   template <typename Range0, typename Range1 = EmptyRange, typename Range2 = EmptyRange>
1136   class ForwardAddress {
1137    public:
ForwardAddress(const Range0 & range0=Range0 (),const Range1 & range1=Range1 (),const Range2 & range2=Range2 ())1138     explicit ForwardAddress(const Range0& range0 = Range0(),
1139                             const Range1& range1 = Range1(),
1140                             const Range2& range2 = Range2())
1141         : range0_(range0), range1_(range1), range2_(range2) {}
1142 
1143     // Return the relocated address of a heap object.
1144     // Null checks must be performed in the caller (for performance reasons).
1145     template <typename T>
operator ()(T * src) const1146     ALWAYS_INLINE T* operator()(T* src) const {
1147       DCHECK(src != nullptr);
1148       const uintptr_t uint_src = reinterpret_cast<uintptr_t>(src);
1149       if (range2_.InSource(uint_src)) {
1150         return reinterpret_cast<T*>(range2_.ToDest(uint_src));
1151       }
1152       if (range1_.InSource(uint_src)) {
1153         return reinterpret_cast<T*>(range1_.ToDest(uint_src));
1154       }
1155       CHECK(range0_.InSource(uint_src))
1156           << reinterpret_cast<const void*>(src) << " not in "
1157           << reinterpret_cast<const void*>(range0_.Source()) << "-"
1158           << reinterpret_cast<const void*>(range0_.Source() + range0_.Length());
1159       return reinterpret_cast<T*>(range0_.ToDest(uint_src));
1160     }
1161 
1162    private:
1163     const Range0 range0_;
1164     const Range1 range1_;
1165     const Range2 range2_;
1166   };
1167 
1168   template <typename Forward>
1169   class FixupRootVisitor {
1170    public:
1171     template<typename... Args>
FixupRootVisitor(Args...args)1172     explicit FixupRootVisitor(Args... args) : forward_(args...) {}
1173 
VisitRootIfNonNull(mirror::CompressedReference<mirror::Object> * root) const1174     ALWAYS_INLINE void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
1175         REQUIRES_SHARED(Locks::mutator_lock_) {
1176       if (!root->IsNull()) {
1177         VisitRoot(root);
1178       }
1179     }
1180 
VisitRoot(mirror::CompressedReference<mirror::Object> * root) const1181     ALWAYS_INLINE void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
1182         REQUIRES_SHARED(Locks::mutator_lock_) {
1183       mirror::Object* ref = root->AsMirrorPtr();
1184       mirror::Object* new_ref = forward_(ref);
1185       if (ref != new_ref) {
1186         root->Assign(new_ref);
1187       }
1188     }
1189 
1190    private:
1191     Forward forward_;
1192   };
1193 
1194   template <typename Forward>
1195   class FixupObjectVisitor {
1196    public:
FixupObjectVisitor(gc::accounting::ContinuousSpaceBitmap * visited,const Forward & forward)1197     explicit FixupObjectVisitor(gc::accounting::ContinuousSpaceBitmap* visited,
1198                                 const Forward& forward)
1199         : visited_(visited), forward_(forward) {}
1200 
1201     // Fix up separately since we also need to fix up method entrypoints.
VisitRootIfNonNull(mirror::CompressedReference<mirror::Object> * root) const1202     ALWAYS_INLINE void VisitRootIfNonNull(
1203         [[maybe_unused]] mirror::CompressedReference<mirror::Object>* root) const {}
1204 
VisitRoot(mirror::CompressedReference<mirror::Object> * root) const1205     ALWAYS_INLINE void VisitRoot(
1206         [[maybe_unused]] mirror::CompressedReference<mirror::Object>* root) const {}
1207 
operator ()(ObjPtr<mirror::Object> obj,MemberOffset offset,bool is_static) const1208     ALWAYS_INLINE void operator()(ObjPtr<mirror::Object> obj,
1209                                   MemberOffset offset,
1210                                   [[maybe_unused]] bool is_static) const NO_THREAD_SAFETY_ANALYSIS {
1211       // Space is not yet added to the heap, don't do a read barrier.
1212       mirror::Object* ref = obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(
1213           offset);
1214       if (ref != nullptr) {
1215         // Use SetFieldObjectWithoutWriteBarrier to avoid card marking since we are writing to the
1216         // image.
1217         obj->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(offset, forward_(ref));
1218       }
1219     }
1220 
1221     // java.lang.ref.Reference visitor.
operator ()(ObjPtr<mirror::Class> klass,ObjPtr<mirror::Reference> ref) const1222     ALWAYS_INLINE void operator()(ObjPtr<mirror::Class> klass, ObjPtr<mirror::Reference> ref) const
1223         REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
1224       DCHECK(klass->IsTypeOfReferenceClass());
1225       this->operator()(ref, mirror::Reference::ReferentOffset(), /*is_static=*/ false);
1226     }
1227 
operator ()(mirror::Object * obj) const1228     void operator()(mirror::Object* obj) const
1229         NO_THREAD_SAFETY_ANALYSIS {
1230       if (!visited_->Set(obj)) {
1231         // Not already visited.
1232         obj->VisitReferences</*visit native roots*/false, kVerifyNone, kWithoutReadBarrier>(
1233             *this,
1234             *this);
1235         CHECK(!obj->IsClass());
1236       }
1237     }
1238 
1239    private:
1240     gc::accounting::ContinuousSpaceBitmap* const visited_;
1241     Forward forward_;
1242   };
1243 
1244   // Relocate an image space mapped at target_base which possibly used to be at a different base
1245   // address. In place means modifying a single ImageSpace in place rather than relocating from
1246   // one ImageSpace to another.
1247   template <PointerSize kPointerSize>
RelocateInPlace(uint32_t boot_image_begin,uint8_t * target_base,accounting::ContinuousSpaceBitmap * bitmap,const OatFile * app_oat_file,std::string * error_msg)1248   static bool RelocateInPlace(uint32_t boot_image_begin,
1249                               uint8_t* target_base,
1250                               accounting::ContinuousSpaceBitmap* bitmap,
1251                               const OatFile* app_oat_file,
1252                               std::string* error_msg) {
1253     DCHECK(error_msg != nullptr);
1254     // Set up sections.
1255     ImageHeader* image_header = reinterpret_cast<ImageHeader*>(target_base);
1256     const uint32_t boot_image_size = image_header->GetBootImageSize();
1257     const ImageSection& objects_section = image_header->GetObjectsSection();
1258     // Where the app image objects are mapped to.
1259     uint8_t* objects_location = target_base + objects_section.Offset();
1260     TimingLogger logger(__FUNCTION__, true, false);
1261     RelocationRange boot_image(image_header->GetBootImageBegin(),
1262                                boot_image_begin,
1263                                boot_image_size);
1264     // Metadata is everything after the objects section, use exclusion to be safe.
1265     RelocationRange app_image_metadata(
1266         reinterpret_cast<uintptr_t>(image_header->GetImageBegin()) + objects_section.End(),
1267         reinterpret_cast<uintptr_t>(target_base) + objects_section.End(),
1268         image_header->GetImageSize() - objects_section.End());
1269     // App image heap objects, may be mapped in the heap.
1270     RelocationRange app_image_objects(
1271         reinterpret_cast<uintptr_t>(image_header->GetImageBegin()) + objects_section.Offset(),
1272         reinterpret_cast<uintptr_t>(objects_location),
1273         objects_section.Size());
1274     // Use the oat data section since this is where the OatFile::Begin is.
1275     RelocationRange app_oat(reinterpret_cast<uintptr_t>(image_header->GetOatDataBegin()),
1276                             // Not necessarily in low 4GB.
1277                             reinterpret_cast<uintptr_t>(app_oat_file->Begin()),
1278                             image_header->GetOatDataEnd() - image_header->GetOatDataBegin());
1279     VLOG(image) << "App image metadata " << app_image_metadata;
1280     VLOG(image) << "App image objects " << app_image_objects;
1281     VLOG(image) << "App oat " << app_oat;
1282     VLOG(image) << "Boot image " << boot_image;
1283     // True if we need to fixup any heap pointers.
1284     const bool fixup_image = boot_image.Delta() != 0 || app_image_metadata.Delta() != 0 ||
1285         app_image_objects.Delta() != 0;
1286     if (!fixup_image) {
1287       // Nothing to fix up.
1288       return true;
1289     }
1290 
1291     // TODO: Assert that the app image does not contain any Method, Constructor,
1292     // FieldVarHandle or StaticFieldVarHandle. These require extra relocation
1293     // for the `ArtMethod*` and `ArtField*` pointers they contain.
1294 
1295     using ForwardObject = ForwardAddress<RelocationRange, RelocationRange>;
1296     ForwardObject forward_object(boot_image, app_image_objects);
1297     ForwardObject forward_metadata(boot_image, app_image_metadata);
1298     using ForwardCode = ForwardAddress<RelocationRange, RelocationRange>;
1299     ForwardCode forward_code(boot_image, app_oat);
1300     PatchObjectVisitor<kPointerSize, ForwardObject, ForwardCode> patch_object_visitor(
1301         forward_object,
1302         forward_metadata);
1303     if (fixup_image) {
1304       // Two pass approach, fix up all classes first, then fix up non class-objects.
1305       // The visited bitmap is used to ensure that pointer arrays are not forwarded twice.
1306       gc::accounting::ContinuousSpaceBitmap visited_bitmap(
1307           gc::accounting::ContinuousSpaceBitmap::Create("Relocate bitmap",
1308                                                         target_base,
1309                                                         image_header->GetImageSize()));
1310       {
1311         TimingLogger::ScopedTiming timing("Fixup classes", &logger);
1312         const auto& class_table_section = image_header->GetClassTableSection();
1313         if (class_table_section.Size() > 0u) {
1314           ScopedObjectAccess soa(Thread::Current());
1315           ScopedDebugDisallowReadBarriers sddrb(Thread::Current());
1316           ObjPtr<mirror::ObjectArray<mirror::Object>> image_roots = app_image_objects.ToDest(
1317               image_header->GetImageRoots<kWithoutReadBarrier>().Ptr());
1318           int32_t class_roots_index = enum_cast<int32_t>(ImageHeader::kClassRoots);
1319           DCHECK_LT(class_roots_index, image_roots->GetLength<kVerifyNone>());
1320           ObjPtr<mirror::ObjectArray<mirror::Class>> class_roots =
1321               ObjPtr<mirror::ObjectArray<mirror::Class>>::DownCast(boot_image.ToDest(
1322                   image_roots->GetWithoutChecks<kVerifyNone,
1323                                                 kWithoutReadBarrier>(class_roots_index).Ptr()));
1324           ObjPtr<mirror::Class> class_class =
1325               GetClassRoot<mirror::Class, kWithoutReadBarrier>(class_roots);
1326           ClassTableVisitor class_table_visitor(forward_object);
1327           size_t read_count = 0u;
1328           const uint8_t* data = target_base + class_table_section.Offset();
1329           // We avoid making a copy of the data since we want modifications to be propagated to the
1330           // memory map.
1331           ClassTable::ClassSet temp_set(data, /*make_copy_of_data=*/ false, &read_count);
1332           for (ClassTable::TableSlot& slot : temp_set) {
1333             slot.VisitRoot(class_table_visitor);
1334             ObjPtr<mirror::Class> klass = slot.Read<kWithoutReadBarrier>();
1335             if (!app_image_objects.InDest(klass.Ptr())) {
1336               continue;
1337             }
1338             const bool already_marked = visited_bitmap.Set(klass.Ptr());
1339             CHECK(!already_marked) << "App image class already visited";
1340             patch_object_visitor.VisitClass(klass, class_class);
1341             // Then patch the non-embedded vtable and iftable.
1342             ObjPtr<mirror::PointerArray> vtable =
1343                 klass->GetVTable<kVerifyNone, kWithoutReadBarrier>();
1344             if (vtable != nullptr &&
1345                 app_image_objects.InDest(vtable.Ptr()) &&
1346                 !visited_bitmap.Set(vtable.Ptr())) {
1347               patch_object_visitor.VisitPointerArray(vtable);
1348             }
1349             ObjPtr<mirror::IfTable> iftable = klass->GetIfTable<kVerifyNone, kWithoutReadBarrier>();
1350             if (iftable != nullptr && app_image_objects.InDest(iftable.Ptr())) {
1351               // Avoid processing the fields of iftable since we will process them later anyways
1352               // below.
1353               int32_t ifcount = klass->GetIfTableCount<kVerifyNone>();
1354               for (int32_t i = 0; i != ifcount; ++i) {
1355                 ObjPtr<mirror::PointerArray> unpatched_ifarray =
1356                     iftable->GetMethodArrayOrNull<kVerifyNone, kWithoutReadBarrier>(i);
1357                 if (unpatched_ifarray != nullptr) {
1358                   // The iftable has not been patched, so we need to explicitly adjust the pointer.
1359                   ObjPtr<mirror::PointerArray> ifarray = forward_object(unpatched_ifarray.Ptr());
1360                   if (app_image_objects.InDest(ifarray.Ptr()) &&
1361                       !visited_bitmap.Set(ifarray.Ptr())) {
1362                     patch_object_visitor.VisitPointerArray(ifarray);
1363                   }
1364                 }
1365               }
1366             }
1367           }
1368         }
1369       }
1370 
1371       // Fixup objects may read fields in the boot image so we hold the mutator lock (although it is
1372       // probably not required).
1373       TimingLogger::ScopedTiming timing("Fixup objects", &logger);
1374       ScopedObjectAccess soa(Thread::Current());
1375       ScopedDebugDisallowReadBarriers sddrb(Thread::Current());
1376       // Need to update the image to be at the target base.
1377       uintptr_t objects_begin = reinterpret_cast<uintptr_t>(target_base + objects_section.Offset());
1378       uintptr_t objects_end = reinterpret_cast<uintptr_t>(target_base + objects_section.End());
1379       FixupObjectVisitor<ForwardObject> fixup_object_visitor(&visited_bitmap, forward_object);
1380       bitmap->VisitMarkedRange(objects_begin, objects_end, fixup_object_visitor);
1381       // Fixup image roots.
1382       CHECK(app_image_objects.InSource(reinterpret_cast<uintptr_t>(
1383           image_header->GetImageRoots<kWithoutReadBarrier>().Ptr())));
1384       image_header->RelocateImageReferences(app_image_objects.Delta());
1385       image_header->RelocateBootImageReferences(boot_image.Delta());
1386       CHECK_EQ(image_header->GetImageBegin(), target_base);
1387 
1388       // Fix up dex cache arrays.
1389       ObjPtr<mirror::ObjectArray<mirror::DexCache>> dex_caches =
1390           image_header->GetImageRoot<kWithoutReadBarrier>(ImageHeader::kDexCaches)
1391               ->AsObjectArray<mirror::DexCache, kVerifyNone>();
1392       for (int32_t i = 0, count = dex_caches->GetLength(); i < count; ++i) {
1393         ObjPtr<mirror::DexCache> dex_cache =
1394             dex_caches->GetWithoutChecks<kVerifyNone, kWithoutReadBarrier>(i);
1395         patch_object_visitor.VisitDexCacheArrays(dex_cache);
1396       }
1397     }
1398     {
1399       // Only touches objects in the app image, no need for mutator lock.
1400       TimingLogger::ScopedTiming timing("Fixup methods", &logger);
1401       ScopedDebugDisallowReadBarriers sddrb(Thread::Current());
1402       image_header->VisitPackedArtMethods([&](ArtMethod& method) NO_THREAD_SAFETY_ANALYSIS {
1403         // TODO: Consider a separate visitor for runtime vs normal methods.
1404         if (UNLIKELY(method.IsRuntimeMethod())) {
1405           ImtConflictTable* table = method.GetImtConflictTable(kPointerSize);
1406           if (table != nullptr) {
1407             ImtConflictTable* new_table = forward_metadata(table);
1408             if (table != new_table) {
1409               method.SetImtConflictTable(new_table, kPointerSize);
1410             }
1411           }
1412         } else {
1413           patch_object_visitor.PatchGcRoot(&method.DeclaringClassRoot());
1414           if (method.IsNative()) {
1415             const void* old_native_code = method.GetEntryPointFromJniPtrSize(kPointerSize);
1416             const void* new_native_code = forward_code(old_native_code);
1417             if (old_native_code != new_native_code) {
1418               method.SetEntryPointFromJniPtrSize(new_native_code, kPointerSize);
1419             }
1420           }
1421         }
1422         const void* old_code = method.GetEntryPointFromQuickCompiledCodePtrSize(kPointerSize);
1423         const void* new_code = forward_code(old_code);
1424         if (old_code != new_code) {
1425           method.SetEntryPointFromQuickCompiledCode(new_code);
1426         }
1427       }, target_base, kPointerSize);
1428     }
1429     if (fixup_image) {
1430       {
1431         // Only touches objects in the app image, no need for mutator lock.
1432         TimingLogger::ScopedTiming timing("Fixup fields", &logger);
1433         ScopedDebugDisallowReadBarriers sddrb(Thread::Current());
1434         image_header->VisitPackedArtFields([&](ArtField& field) NO_THREAD_SAFETY_ANALYSIS {
1435           patch_object_visitor.template PatchGcRoot</*kMayBeNull=*/ false>(
1436               &field.DeclaringClassRoot());
1437         }, target_base);
1438       }
1439       {
1440         TimingLogger::ScopedTiming timing("Fixup imt", &logger);
1441         ScopedDebugDisallowReadBarriers sddrb(Thread::Current());
1442         image_header->VisitPackedImTables(forward_metadata, target_base, kPointerSize);
1443       }
1444       {
1445         TimingLogger::ScopedTiming timing("Fixup conflict tables", &logger);
1446         ScopedDebugDisallowReadBarriers sddrb(Thread::Current());
1447         image_header->VisitPackedImtConflictTables(forward_metadata, target_base, kPointerSize);
1448       }
1449       // Fix up the intern table.
1450       const auto& intern_table_section = image_header->GetInternedStringsSection();
1451       if (intern_table_section.Size() > 0u) {
1452         TimingLogger::ScopedTiming timing("Fixup intern table", &logger);
1453         ScopedObjectAccess soa(Thread::Current());
1454         ScopedDebugDisallowReadBarriers sddrb(Thread::Current());
1455         // Fixup the pointers in the newly written intern table to contain image addresses.
1456         InternTable temp_intern_table;
1457         // Note that we require that ReadFromMemory does not make an internal copy of the elements
1458         // so that the VisitRoots() will update the memory directly rather than the copies.
1459         temp_intern_table.AddTableFromMemory(target_base + intern_table_section.Offset(),
1460                                              [&](InternTable::UnorderedSet& strings)
1461             REQUIRES_SHARED(Locks::mutator_lock_) {
1462           for (GcRoot<mirror::String>& root : strings) {
1463             root = GcRoot<mirror::String>(forward_object(root.Read<kWithoutReadBarrier>()));
1464           }
1465         }, /*is_boot_image=*/ false);
1466       }
1467     }
1468     if (VLOG_IS_ON(image)) {
1469       logger.Dump(LOG_STREAM(INFO));
1470     }
1471     return true;
1472   }
1473 };
1474 
AppendImageChecksum(uint32_t component_count,uint32_t checksum,std::string * checksums)1475 void ImageSpace::AppendImageChecksum(uint32_t component_count,
1476                                      uint32_t checksum,
1477                                      /*inout*/ std::string* checksums) {
1478   static_assert(ImageSpace::kImageChecksumPrefix == 'i', "Format prefix check.");
1479   StringAppendF(checksums, "i;%u/%08x", component_count, checksum);
1480 }
1481 
CheckAndRemoveImageChecksum(uint32_t component_count,uint32_t checksum,std::string_view * oat_checksums,std::string * error_msg)1482 static bool CheckAndRemoveImageChecksum(uint32_t component_count,
1483                                         uint32_t checksum,
1484                                         /*inout*/std::string_view* oat_checksums,
1485                                         /*out*/std::string* error_msg) {
1486   std::string image_checksum;
1487   ImageSpace::AppendImageChecksum(component_count, checksum, &image_checksum);
1488   if (!oat_checksums->starts_with(image_checksum)) {
1489     *error_msg = StringPrintf("Image checksum mismatch, expected %s to start with %s",
1490                               std::string(*oat_checksums).c_str(),
1491                               image_checksum.c_str());
1492     return false;
1493   }
1494   oat_checksums->remove_prefix(image_checksum.size());
1495   return true;
1496 }
1497 
GetPrimaryImageLocation()1498 std::string ImageSpace::BootImageLayout::GetPrimaryImageLocation() {
1499   DCHECK(!image_locations_.empty());
1500   std::string location = image_locations_[0];
1501   size_t profile_separator_pos = location.find(kProfileSeparator);
1502   if (profile_separator_pos != std::string::npos) {
1503     location.resize(profile_separator_pos);
1504   }
1505   if (location.find('/') == std::string::npos) {
1506     // No path, so use the path from the first boot class path component.
1507     size_t slash_pos = boot_class_path_.empty()
1508         ? std::string::npos
1509         : boot_class_path_[0].rfind('/');
1510     if (slash_pos == std::string::npos) {
1511       return std::string();
1512     }
1513     location.insert(0u, boot_class_path_[0].substr(0u, slash_pos + 1u));
1514   }
1515   return location;
1516 }
1517 
VerifyImageLocation(ArrayRef<const std::string> components,size_t * named_components_count,std::string * error_msg)1518 bool ImageSpace::BootImageLayout::VerifyImageLocation(
1519     ArrayRef<const std::string> components,
1520     /*out*/size_t* named_components_count,
1521     /*out*/std::string* error_msg) {
1522   DCHECK(named_components_count != nullptr);
1523 
1524   // Validate boot class path. Require a path and non-empty name in each component.
1525   for (const std::string& bcp_component : boot_class_path_) {
1526     size_t bcp_slash_pos = bcp_component.rfind('/');
1527     if (bcp_slash_pos == std::string::npos || bcp_slash_pos == bcp_component.size() - 1u) {
1528       *error_msg = StringPrintf("Invalid boot class path component: %s", bcp_component.c_str());
1529       return false;
1530     }
1531   }
1532 
1533   // Validate the format of image location components.
1534   size_t components_size = components.size();
1535   if (components_size == 0u) {
1536     *error_msg = "Empty image location.";
1537     return false;
1538   }
1539   size_t wildcards_start = components_size;  // No wildcards.
1540   for (size_t i = 0; i != components_size; ++i) {
1541     const std::string& component = components[i];
1542     DCHECK(!component.empty());  // Guaranteed by Split().
1543     std::vector<std::string> parts = android::base::Split(component, {kProfileSeparator});
1544     size_t wildcard_pos = component.find('*');
1545     if (wildcard_pos == std::string::npos) {
1546       if (wildcards_start != components.size()) {
1547         *error_msg =
1548             StringPrintf("Image component without wildcard after component with wildcard: %s",
1549                          component.c_str());
1550         return false;
1551       }
1552       for (size_t j = 0; j < parts.size(); j++) {
1553         if (parts[j].empty()) {
1554           *error_msg = StringPrintf("Missing component and/or profile name in %s",
1555                                     component.c_str());
1556           return false;
1557         }
1558         if (parts[j].back() == '/') {
1559           *error_msg = StringPrintf("%s name ends with path separator: %s",
1560                                     j == 0 ? "Image component" : "Profile",
1561                                     component.c_str());
1562           return false;
1563         }
1564       }
1565     } else {
1566       if (parts.size() > 1) {
1567         *error_msg = StringPrintf("Unsupproted wildcard (*) and profile delimiter (!) in %s",
1568                                   component.c_str());
1569         return false;
1570       }
1571       if (wildcards_start == components_size) {
1572         wildcards_start = i;
1573       }
1574       // Wildcard must be the last character.
1575       if (wildcard_pos != component.size() - 1u) {
1576         *error_msg = StringPrintf("Unsupported wildcard (*) position in %s", component.c_str());
1577         return false;
1578       }
1579       // And it must be either plain wildcard or preceded by a path separator.
1580       if (component.size() != 1u && component[wildcard_pos - 1u] != '/') {
1581         *error_msg = StringPrintf("Non-plain wildcard (*) not preceded by path separator '/': %s",
1582                                   component.c_str());
1583         return false;
1584       }
1585       if (i == 0) {
1586         *error_msg = StringPrintf("Primary component contains wildcard (*): %s", component.c_str());
1587         return false;
1588       }
1589     }
1590   }
1591 
1592   *named_components_count = wildcards_start;
1593   return true;
1594 }
1595 
MatchNamedComponents(ArrayRef<const std::string> named_components,std::vector<NamedComponentLocation> * named_component_locations,std::string * error_msg)1596 bool ImageSpace::BootImageLayout::MatchNamedComponents(
1597     ArrayRef<const std::string> named_components,
1598     /*out*/std::vector<NamedComponentLocation>* named_component_locations,
1599     /*out*/std::string* error_msg) {
1600   DCHECK(!named_components.empty());
1601   DCHECK(named_component_locations->empty());
1602   named_component_locations->reserve(named_components.size());
1603   size_t bcp_component_count = boot_class_path_.size();
1604   size_t bcp_pos = 0;
1605   std::string base_name;
1606   for (size_t i = 0, size = named_components.size(); i != size; ++i) {
1607     std::string component = named_components[i];
1608     std::vector<std::string> profile_filenames;  // Empty.
1609     std::vector<std::string> parts = android::base::Split(component, {kProfileSeparator});
1610     for (size_t j = 0; j < parts.size(); j++) {
1611       if (j == 0) {
1612         component = std::move(parts[j]);
1613         DCHECK(!component.empty());  // Checked by VerifyImageLocation()
1614       } else {
1615         profile_filenames.push_back(std::move(parts[j]));
1616         DCHECK(!profile_filenames.back().empty());  // Checked by VerifyImageLocation()
1617       }
1618     }
1619     size_t slash_pos = component.rfind('/');
1620     std::string base_location;
1621     if (i == 0u) {
1622       // The primary boot image name is taken as provided. It forms the base
1623       // for expanding the extension filenames.
1624       if (slash_pos != std::string::npos) {
1625         base_name = component.substr(slash_pos + 1u);
1626         base_location = component;
1627       } else {
1628         base_name = component;
1629         base_location = GetBcpComponentPath(0u) + component;
1630       }
1631     } else {
1632       std::string to_match;
1633       if (slash_pos != std::string::npos) {
1634         // If we have the full path, we just need to match the filename to the BCP component.
1635         base_location = component.substr(0u, slash_pos + 1u) + base_name;
1636         to_match = component;
1637       }
1638       while (true) {
1639         if (slash_pos == std::string::npos) {
1640           // If we do not have a full path, we need to update the path based on the BCP location.
1641           std::string path = GetBcpComponentPath(bcp_pos);
1642           to_match = path + component;
1643           base_location = path + base_name;
1644         }
1645         if (ExpandLocation(base_location, bcp_pos) == to_match) {
1646           break;
1647         }
1648         ++bcp_pos;
1649         if (bcp_pos == bcp_component_count) {
1650           *error_msg = StringPrintf("Image component %s does not match a boot class path component",
1651                                     component.c_str());
1652           return false;
1653         }
1654       }
1655     }
1656     for (std::string& profile_filename : profile_filenames) {
1657       if (profile_filename.find('/') == std::string::npos) {
1658         profile_filename.insert(/*pos*/ 0u, GetBcpComponentPath(bcp_pos));
1659       }
1660     }
1661     NamedComponentLocation location;
1662     location.base_location = base_location;
1663     location.bcp_index = bcp_pos;
1664     location.profile_filenames = profile_filenames;
1665     named_component_locations->push_back(location);
1666     ++bcp_pos;
1667   }
1668   return true;
1669 }
1670 
ValidateBootImageChecksum(const char * file_description,const ImageHeader & header,std::string * error_msg)1671 bool ImageSpace::BootImageLayout::ValidateBootImageChecksum(const char* file_description,
1672                                                             const ImageHeader& header,
1673                                                             /*out*/std::string* error_msg) {
1674   uint32_t boot_image_component_count = header.GetBootImageComponentCount();
1675   if (chunks_.empty() != (boot_image_component_count == 0u)) {
1676     *error_msg = StringPrintf("Unexpected boot image component count in %s: %u, %s",
1677                               file_description,
1678                               boot_image_component_count,
1679                               chunks_.empty() ? "should be 0" : "should not be 0");
1680     return false;
1681   }
1682   uint32_t component_count = 0u;
1683   uint32_t composite_checksum = 0u;
1684   uint64_t boot_image_size = 0u;
1685   for (const ImageChunk& chunk : chunks_) {
1686     if (component_count == boot_image_component_count) {
1687       break;  // Hit the component count.
1688     }
1689     if (chunk.start_index != component_count) {
1690       break;  // End of contiguous chunks, fail below; same as reaching end of `chunks_`.
1691     }
1692     if (chunk.component_count > boot_image_component_count - component_count) {
1693       *error_msg = StringPrintf("Boot image component count in %s ends in the middle of a chunk, "
1694                                     "%u is between %u and %u",
1695                                 file_description,
1696                                 boot_image_component_count,
1697                                 component_count,
1698                                 component_count + chunk.component_count);
1699       return false;
1700     }
1701     component_count += chunk.component_count;
1702     composite_checksum ^= chunk.checksum;
1703     boot_image_size += chunk.reservation_size;
1704   }
1705   DCHECK_LE(component_count, boot_image_component_count);
1706   if (component_count != boot_image_component_count) {
1707     *error_msg = StringPrintf("Missing boot image components for checksum in %s: %u > %u",
1708                               file_description,
1709                               boot_image_component_count,
1710                               component_count);
1711     return false;
1712   }
1713   if (composite_checksum != header.GetBootImageChecksum()) {
1714     *error_msg = StringPrintf("Boot image checksum mismatch in %s: 0x%08x != 0x%08x",
1715                               file_description,
1716                               header.GetBootImageChecksum(),
1717                               composite_checksum);
1718     return false;
1719   }
1720   if (boot_image_size != header.GetBootImageSize()) {
1721     *error_msg = StringPrintf("Boot image size mismatch in %s: 0x%08x != 0x%08" PRIx64,
1722                               file_description,
1723                               header.GetBootImageSize(),
1724                               boot_image_size);
1725     return false;
1726   }
1727   return true;
1728 }
1729 
ValidateHeader(const ImageHeader & header,size_t bcp_index,const char * file_description,std::string * error_msg)1730 bool ImageSpace::BootImageLayout::ValidateHeader(const ImageHeader& header,
1731                                                  size_t bcp_index,
1732                                                  const char* file_description,
1733                                                  /*out*/std::string* error_msg) {
1734   size_t bcp_component_count = boot_class_path_.size();
1735   DCHECK_LT(bcp_index, bcp_component_count);
1736   size_t allowed_component_count = bcp_component_count - bcp_index;
1737   DCHECK_LE(total_reservation_size_, kMaxTotalImageReservationSize);
1738   size_t allowed_reservation_size = kMaxTotalImageReservationSize - total_reservation_size_;
1739 
1740   if (header.GetComponentCount() == 0u ||
1741       header.GetComponentCount() > allowed_component_count) {
1742     *error_msg = StringPrintf("Unexpected component count in %s, received %u, "
1743                                   "expected non-zero and <= %zu",
1744                               file_description,
1745                               header.GetComponentCount(),
1746                               allowed_component_count);
1747     return false;
1748   }
1749   if (header.GetImageReservationSize() > allowed_reservation_size) {
1750     *error_msg = StringPrintf("Reservation size too big in %s: %u > %zu",
1751                               file_description,
1752                               header.GetImageReservationSize(),
1753                               allowed_reservation_size);
1754     return false;
1755   }
1756   if (!ValidateBootImageChecksum(file_description, header, error_msg)) {
1757     return false;
1758   }
1759 
1760   return true;
1761 }
1762 
ValidateOatFile(const std::string & base_location,const std::string & base_filename,size_t bcp_index,size_t component_count,std::string * error_msg)1763 bool ImageSpace::BootImageLayout::ValidateOatFile(
1764     const std::string& base_location,
1765     const std::string& base_filename,
1766     size_t bcp_index,
1767     size_t component_count,
1768     /*out*/std::string* error_msg) {
1769   std::string art_filename = ExpandLocation(base_filename, bcp_index);
1770   std::string art_location = ExpandLocation(base_location, bcp_index);
1771   std::string oat_filename = ImageHeader::GetOatLocationFromImageLocation(art_filename);
1772   std::string oat_location = ImageHeader::GetOatLocationFromImageLocation(art_location);
1773   int oat_fd = bcp_index < boot_class_path_oat_files_.size()
1774       ? boot_class_path_oat_files_[bcp_index].Fd()
1775       : -1;
1776   int vdex_fd = bcp_index < boot_class_path_vdex_files_.size()
1777       ? boot_class_path_vdex_files_[bcp_index].Fd()
1778       : -1;
1779   auto dex_filenames =
1780       ArrayRef<const std::string>(boot_class_path_).SubArray(bcp_index, component_count);
1781   ArrayRef<File> dex_files =
1782       bcp_index + component_count < boot_class_path_files_.size() ?
1783           ArrayRef<File>(boot_class_path_files_).SubArray(bcp_index, component_count) :
1784           ArrayRef<File>();
1785   // We open the oat file here only for validating that it's up-to-date. We don't open it as
1786   // executable or mmap it to a reserved space. This `OatFile` object will be dropped after
1787   // validation, and will not go into the `ImageSpace`.
1788   std::unique_ptr<OatFile> oat_file;
1789   DCHECK_EQ(oat_fd >= 0, vdex_fd >= 0);
1790   if (oat_fd >= 0) {
1791     oat_file.reset(OatFile::Open(
1792         /*zip_fd=*/ -1,
1793         vdex_fd,
1794         oat_fd,
1795         oat_location,
1796         /*executable=*/ false,
1797         /*low_4gb=*/ false,
1798         dex_filenames,
1799         dex_files,
1800         /*reservation=*/ nullptr,
1801         error_msg));
1802   } else {
1803     oat_file.reset(OatFile::Open(
1804         /*zip_fd=*/ -1,
1805         oat_filename,
1806         oat_location,
1807         /*executable=*/ false,
1808         /*low_4gb=*/ false,
1809         dex_filenames,
1810         dex_files,
1811         /*reservation=*/ nullptr,
1812         error_msg));
1813   }
1814   if (oat_file == nullptr) {
1815     *error_msg = StringPrintf("Failed to open oat file '%s' when validating it for image '%s': %s",
1816                               oat_filename.c_str(),
1817                               art_location.c_str(),
1818                               error_msg->c_str());
1819     return false;
1820   }
1821   if (!ImageSpace::ValidateOatFile(
1822           *oat_file, error_msg, dex_filenames, dex_files, apex_versions_)) {
1823     return false;
1824   }
1825   return true;
1826 }
1827 
ReadHeader(const std::string & base_location,const std::string & base_filename,size_t bcp_index,std::string * error_msg)1828 bool ImageSpace::BootImageLayout::ReadHeader(const std::string& base_location,
1829                                              const std::string& base_filename,
1830                                              size_t bcp_index,
1831                                              /*out*/std::string* error_msg) {
1832   DCHECK_LE(next_bcp_index_, bcp_index);
1833   DCHECK_LT(bcp_index, boot_class_path_.size());
1834 
1835   std::string actual_filename = ExpandLocation(base_filename, bcp_index);
1836   int bcp_image_fd = bcp_index < boot_class_path_image_files_.size() ?
1837                          boot_class_path_image_files_[bcp_index].Fd() :
1838                          -1;
1839   ImageHeader header;
1840   // When BCP image is provided as FD, it needs to be dup'ed (since it's stored in unique_fd) so
1841   // that it can later be used in LoadComponents.
1842   auto image_file = bcp_image_fd >= 0
1843       ? std::make_unique<File>(DupCloexec(bcp_image_fd), actual_filename, /*check_usage=*/ false)
1844       : std::unique_ptr<File>(OS::OpenFileForReading(actual_filename.c_str()));
1845   if (!image_file || !image_file->IsOpened()) {
1846     *error_msg = StringPrintf("Unable to open file \"%s\" for reading image header",
1847                               actual_filename.c_str());
1848     return false;
1849   }
1850   if (!ReadSpecificImageHeader(image_file.get(), actual_filename.c_str(), &header, error_msg)) {
1851     return false;
1852   }
1853   const char* file_description = actual_filename.c_str();
1854   if (!ValidateHeader(header, bcp_index, file_description, error_msg)) {
1855     return false;
1856   }
1857 
1858   // Validate oat files. We do it here so that the boot image will be re-compiled in memory if it's
1859   // outdated.
1860   size_t component_count = (header.GetImageSpaceCount() == 1u) ? header.GetComponentCount() : 1u;
1861   for (size_t i = 0; i < header.GetImageSpaceCount(); i++) {
1862     if (!ValidateOatFile(base_location, base_filename, bcp_index + i, component_count, error_msg)) {
1863       return false;
1864     }
1865   }
1866 
1867   if (chunks_.empty()) {
1868     base_address_ = reinterpret_cast32<uint32_t>(header.GetImageBegin());
1869   }
1870   ImageChunk chunk;
1871   chunk.base_location = base_location;
1872   chunk.base_filename = base_filename;
1873   chunk.start_index = bcp_index;
1874   chunk.component_count = header.GetComponentCount();
1875   chunk.image_space_count = header.GetImageSpaceCount();
1876   chunk.reservation_size = header.GetImageReservationSize();
1877   chunk.checksum = header.GetImageChecksum();
1878   chunk.boot_image_component_count = header.GetBootImageComponentCount();
1879   chunk.boot_image_checksum = header.GetBootImageChecksum();
1880   chunk.boot_image_size = header.GetBootImageSize();
1881   chunks_.push_back(std::move(chunk));
1882   next_bcp_index_ = bcp_index + header.GetComponentCount();
1883   total_component_count_ += header.GetComponentCount();
1884   total_reservation_size_ += header.GetImageReservationSize();
1885   return true;
1886 }
1887 
CompileBootclasspathElements(const std::string & base_location,const std::string & base_filename,size_t bcp_index,const std::vector<std::string> & profile_filenames,ArrayRef<const std::string> dependencies,std::string * error_msg)1888 bool ImageSpace::BootImageLayout::CompileBootclasspathElements(
1889     const std::string& base_location,
1890     const std::string& base_filename,
1891     size_t bcp_index,
1892     const std::vector<std::string>& profile_filenames,
1893     ArrayRef<const std::string> dependencies,
1894     /*out*/std::string* error_msg) {
1895   DCHECK_LE(total_component_count_, next_bcp_index_);
1896   DCHECK_LE(next_bcp_index_, bcp_index);
1897   size_t bcp_component_count = boot_class_path_.size();
1898   DCHECK_LT(bcp_index, bcp_component_count);
1899   DCHECK(!profile_filenames.empty());
1900   if (total_component_count_ != bcp_index) {
1901     // We require all previous BCP components to have a boot image space (primary or extension).
1902     *error_msg = "Cannot compile extension because of missing dependencies.";
1903     return false;
1904   }
1905   Runtime* runtime = Runtime::Current();
1906   if (!runtime->IsImageDex2OatEnabled()) {
1907     *error_msg = "Cannot compile bootclasspath because dex2oat for image compilation is disabled.";
1908     return false;
1909   }
1910 
1911   // Check dependencies.
1912   DCHECK_EQ(dependencies.empty(), bcp_index == 0);
1913   size_t dependency_component_count = 0;
1914   for (size_t i = 0, size = dependencies.size(); i != size; ++i) {
1915     if (chunks_.size() == i || chunks_[i].start_index != dependency_component_count) {
1916       *error_msg = StringPrintf("Missing extension dependency \"%s\"", dependencies[i].c_str());
1917       return false;
1918     }
1919     dependency_component_count += chunks_[i].component_count;
1920   }
1921 
1922   // Collect locations from the profile.
1923   std::set<std::string> dex_locations;
1924   for (const std::string& profile_filename : profile_filenames) {
1925     std::unique_ptr<File> profile_file(OS::OpenFileForReading(profile_filename.c_str()));
1926     if (profile_file == nullptr) {
1927       *error_msg = StringPrintf("Failed to open profile file \"%s\" for reading, error: %s",
1928                                 profile_filename.c_str(),
1929                                 strerror(errno));
1930       return false;
1931     }
1932 
1933     // TODO: Rewrite ProfileCompilationInfo to provide a better interface and
1934     // to store the dex locations in uncompressed section of the file.
1935     auto collect_fn = [&dex_locations](const std::string& dex_location,
1936                                        [[maybe_unused]] uint32_t checksum) {
1937       dex_locations.insert(dex_location);  // Just collect locations.
1938       return false;                        // Do not read the profile data.
1939     };
1940     ProfileCompilationInfo info(/*for_boot_image=*/ true);
1941     if (!info.Load(profile_file->Fd(), /*merge_classes=*/ true, collect_fn)) {
1942       *error_msg = StringPrintf("Failed to scan profile from %s", profile_filename.c_str());
1943       return false;
1944     }
1945   }
1946 
1947   // Match boot class path components to locations from profile.
1948   // Note that the profile records only filenames without paths.
1949   size_t bcp_end = bcp_index;
1950   for (; bcp_end != bcp_component_count; ++bcp_end) {
1951     const std::string& bcp_component = boot_class_path_locations_[bcp_end];
1952     size_t slash_pos = bcp_component.rfind('/');
1953     DCHECK_NE(slash_pos, std::string::npos);
1954     std::string bcp_component_name = bcp_component.substr(slash_pos + 1u);
1955     if (dex_locations.count(bcp_component_name) == 0u) {
1956       break;  // Did not find the current location in dex file.
1957     }
1958   }
1959 
1960   if (bcp_end == bcp_index) {
1961     // No data for the first (requested) component.
1962     *error_msg = StringPrintf("The profile does not contain data for %s",
1963                               boot_class_path_locations_[bcp_index].c_str());
1964     return false;
1965   }
1966 
1967   // Create in-memory files.
1968   std::string art_filename = ExpandLocation(base_filename, bcp_index);
1969   std::string vdex_filename = ImageHeader::GetVdexLocationFromImageLocation(art_filename);
1970   std::string oat_filename = ImageHeader::GetOatLocationFromImageLocation(art_filename);
1971   android::base::unique_fd art_fd(memfd_create_compat(art_filename.c_str(), /*flags=*/ 0));
1972   android::base::unique_fd vdex_fd(memfd_create_compat(vdex_filename.c_str(), /*flags=*/ 0));
1973   android::base::unique_fd oat_fd(memfd_create_compat(oat_filename.c_str(), /*flags=*/ 0));
1974   if (art_fd.get() == -1 || vdex_fd.get() == -1 || oat_fd.get() == -1) {
1975     *error_msg = StringPrintf("Failed to create memfd handles for compiling bootclasspath for %s",
1976                               boot_class_path_locations_[bcp_index].c_str());
1977     return false;
1978   }
1979 
1980   // Construct the dex2oat command line.
1981   std::string dex2oat = runtime->GetCompilerExecutable();
1982   ArrayRef<const std::string> head_bcp =
1983       boot_class_path_.SubArray(/*pos=*/ 0u, /*length=*/ dependency_component_count);
1984   ArrayRef<const std::string> head_bcp_locations =
1985       boot_class_path_locations_.SubArray(/*pos=*/ 0u, /*length=*/ dependency_component_count);
1986   ArrayRef<const std::string> bcp_to_compile =
1987       boot_class_path_.SubArray(/*pos=*/ bcp_index, /*length=*/ bcp_end - bcp_index);
1988   ArrayRef<const std::string> bcp_to_compile_locations =
1989       boot_class_path_locations_.SubArray(/*pos=*/ bcp_index, /*length=*/ bcp_end - bcp_index);
1990   std::string boot_class_path = head_bcp.empty() ?
1991                                     Join(bcp_to_compile, ':') :
1992                                     Join(head_bcp, ':') + ':' + Join(bcp_to_compile, ':');
1993   std::string boot_class_path_locations =
1994       head_bcp_locations.empty() ?
1995           Join(bcp_to_compile_locations, ':') :
1996           Join(head_bcp_locations, ':') + ':' + Join(bcp_to_compile_locations, ':');
1997 
1998   std::vector<std::string> args;
1999   args.push_back(dex2oat);
2000   args.push_back("--runtime-arg");
2001   args.push_back("-Xbootclasspath:" + boot_class_path);
2002   args.push_back("--runtime-arg");
2003   args.push_back("-Xbootclasspath-locations:" + boot_class_path_locations);
2004   if (dependencies.empty()) {
2005     args.push_back(android::base::StringPrintf("--base=0x%08x", ART_BASE_ADDRESS));
2006   } else {
2007     args.push_back("--boot-image=" + Join(dependencies, kComponentSeparator));
2008   }
2009   for (size_t i = bcp_index; i != bcp_end; ++i) {
2010     args.push_back("--dex-file=" + boot_class_path_[i]);
2011     args.push_back("--dex-location=" + boot_class_path_locations_[i]);
2012   }
2013   args.push_back("--image-fd=" + std::to_string(art_fd.get()));
2014   args.push_back("--output-vdex-fd=" + std::to_string(vdex_fd.get()));
2015   args.push_back("--oat-fd=" + std::to_string(oat_fd.get()));
2016   args.push_back("--oat-location=" + ImageHeader::GetOatLocationFromImageLocation(base_filename));
2017   args.push_back("--single-image");
2018   args.push_back("--image-format=uncompressed");
2019 
2020   // We currently cannot guarantee that the boot class path has no verification failures.
2021   // And we do not want to compile anything, compilation should be done by JIT in zygote.
2022   args.push_back("--compiler-filter=verify");
2023 
2024   // Pass the profiles.
2025   for (const std::string& profile_filename : profile_filenames) {
2026     args.push_back("--profile-file=" + profile_filename);
2027   }
2028 
2029   // Do not let the file descriptor numbers change the compilation output.
2030   args.push_back("--avoid-storing-invocation");
2031 
2032   runtime->AddCurrentRuntimeFeaturesAsDex2OatArguments(&args);
2033 
2034   if (!kIsTargetBuild) {
2035     args.push_back("--host");
2036   }
2037 
2038   // Image compiler options go last to allow overriding above args, such as --compiler-filter.
2039   for (const std::string& compiler_option : runtime->GetImageCompilerOptions()) {
2040     args.push_back(compiler_option);
2041   }
2042 
2043   // Compile.
2044   VLOG(image) << "Compiling boot bootclasspath for " << (bcp_end - bcp_index)
2045               << " components, starting from " << boot_class_path_locations_[bcp_index];
2046   if (!Exec(args, error_msg)) {
2047     return false;
2048   }
2049 
2050   // Read and validate the image header.
2051   ImageHeader header;
2052   {
2053     File image_file(art_fd.release(), /*check_usage=*/ false);
2054     if (!ReadSpecificImageHeader(&image_file, "compiled image file", &header, error_msg)) {
2055       return false;
2056     }
2057     art_fd.reset(image_file.Release());
2058   }
2059   const char* file_description = "compiled image file";
2060   if (!ValidateHeader(header, bcp_index, file_description, error_msg)) {
2061     return false;
2062   }
2063 
2064   DCHECK_EQ(chunks_.empty(), dependencies.empty());
2065   ImageChunk chunk;
2066   chunk.base_location = base_location;
2067   chunk.base_filename = base_filename;
2068   chunk.profile_files = profile_filenames;
2069   chunk.start_index = bcp_index;
2070   chunk.component_count = header.GetComponentCount();
2071   chunk.image_space_count = header.GetImageSpaceCount();
2072   chunk.reservation_size = header.GetImageReservationSize();
2073   chunk.checksum = header.GetImageChecksum();
2074   chunk.boot_image_component_count = header.GetBootImageComponentCount();
2075   chunk.boot_image_checksum = header.GetBootImageChecksum();
2076   chunk.boot_image_size = header.GetBootImageSize();
2077   chunk.art_fd.reset(art_fd.release());
2078   chunk.vdex_fd.reset(vdex_fd.release());
2079   chunk.oat_fd.reset(oat_fd.release());
2080   chunks_.push_back(std::move(chunk));
2081   next_bcp_index_ = bcp_index + header.GetComponentCount();
2082   total_component_count_ += header.GetComponentCount();
2083   total_reservation_size_ += header.GetImageReservationSize();
2084   return true;
2085 }
2086 
2087 template <typename FilenameFn>
Load(FilenameFn && filename_fn,bool allow_in_memory_compilation,std::string * error_msg)2088 bool ImageSpace::BootImageLayout::Load(FilenameFn&& filename_fn,
2089                                        bool allow_in_memory_compilation,
2090                                        /*out*/ std::string* error_msg) {
2091   DCHECK(GetChunks().empty());
2092   DCHECK_EQ(GetBaseAddress(), 0u);
2093 
2094   ArrayRef<const std::string> components = image_locations_;
2095   size_t named_components_count = 0u;
2096   if (!VerifyImageLocation(components, &named_components_count, error_msg)) {
2097     return false;
2098   }
2099 
2100   ArrayRef<const std::string> named_components =
2101       ArrayRef<const std::string>(components).SubArray(/*pos=*/ 0u, named_components_count);
2102 
2103   std::vector<NamedComponentLocation> named_component_locations;
2104   if (!MatchNamedComponents(named_components, &named_component_locations, error_msg)) {
2105     return false;
2106   }
2107 
2108   // Load the image headers of named components.
2109   DCHECK_EQ(named_component_locations.size(), named_components.size());
2110   const size_t bcp_component_count = boot_class_path_.size();
2111   size_t bcp_pos = 0u;
2112   for (size_t i = 0, size = named_components.size(); i != size; ++i) {
2113     const std::string& base_location = named_component_locations[i].base_location;
2114     size_t bcp_index = named_component_locations[i].bcp_index;
2115     const std::vector<std::string>& profile_filenames =
2116         named_component_locations[i].profile_filenames;
2117     DCHECK_EQ(i == 0, bcp_index == 0);
2118     if (bcp_index < bcp_pos) {
2119       DCHECK_NE(i, 0u);
2120       LOG(ERROR) << "Named image component already covered by previous image: " << base_location;
2121       continue;
2122     }
2123     std::string local_error_msg;
2124     std::string base_filename;
2125     if (!filename_fn(base_location, &base_filename, &local_error_msg) ||
2126         !ReadHeader(base_location, base_filename, bcp_index, &local_error_msg)) {
2127       LOG(ERROR) << "Error reading named image component header for " << base_location
2128                  << ", error: " << local_error_msg;
2129       // If the primary boot image is invalid, we generate a single full image. This is faster than
2130       // generating the primary boot image and the extension separately.
2131       if (bcp_index == 0) {
2132         if (!allow_in_memory_compilation) {
2133           // The boot image is unusable and we can't continue by generating a boot image in memory.
2134           // All we can do is to return.
2135           *error_msg = std::move(local_error_msg);
2136           return false;
2137         }
2138         // We must at least have profiles for the core libraries.
2139         if (profile_filenames.empty()) {
2140           *error_msg = "Full boot image cannot be compiled because no profile is provided.";
2141           return false;
2142         }
2143         std::vector<std::string> all_profiles;
2144         for (const NamedComponentLocation& named_component_location : named_component_locations) {
2145           const std::vector<std::string>& profiles = named_component_location.profile_filenames;
2146           all_profiles.insert(all_profiles.end(), profiles.begin(), profiles.end());
2147         }
2148         if (!CompileBootclasspathElements(base_location,
2149                                           base_filename,
2150                                           /*bcp_index=*/ 0,
2151                                           all_profiles,
2152                                           /*dependencies=*/ ArrayRef<const std::string>{},
2153                                           &local_error_msg)) {
2154           *error_msg =
2155               StringPrintf("Full boot image cannot be compiled: %s", local_error_msg.c_str());
2156           return false;
2157         }
2158         // No extensions are needed.
2159         return true;
2160       }
2161       bool should_compile_extension = allow_in_memory_compilation && !profile_filenames.empty();
2162       if (!should_compile_extension ||
2163           !CompileBootclasspathElements(base_location,
2164                                         base_filename,
2165                                         bcp_index,
2166                                         profile_filenames,
2167                                         components.SubArray(/*pos=*/ 0, /*length=*/ 1),
2168                                         &local_error_msg)) {
2169         if (should_compile_extension) {
2170           LOG(ERROR) << "Error compiling boot image extension for " << boot_class_path_[bcp_index]
2171                      << ", error: " << local_error_msg;
2172         }
2173         bcp_pos = bcp_index + 1u;  // Skip at least this component.
2174         DCHECK_GT(bcp_pos, GetNextBcpIndex());
2175         continue;
2176       }
2177     }
2178     bcp_pos = GetNextBcpIndex();
2179   }
2180 
2181   // Look for remaining components if there are any wildcard specifications.
2182   ArrayRef<const std::string> search_paths = components.SubArray(/*pos=*/ named_components_count);
2183   if (!search_paths.empty()) {
2184     const std::string& primary_base_location = named_component_locations[0].base_location;
2185     size_t base_slash_pos = primary_base_location.rfind('/');
2186     DCHECK_NE(base_slash_pos, std::string::npos);
2187     std::string base_name = primary_base_location.substr(base_slash_pos + 1u);
2188     DCHECK(!base_name.empty());
2189     while (bcp_pos != bcp_component_count) {
2190       const std::string& bcp_component =  boot_class_path_[bcp_pos];
2191       bool found = false;
2192       for (const std::string& path : search_paths) {
2193         std::string base_location;
2194         if (path.size() == 1u) {
2195           DCHECK_EQ(path, "*");
2196           size_t slash_pos = bcp_component.rfind('/');
2197           DCHECK_NE(slash_pos, std::string::npos);
2198           base_location = bcp_component.substr(0u, slash_pos + 1u) + base_name;
2199         } else {
2200           DCHECK(path.ends_with("/*"));
2201           base_location = path.substr(0u, path.size() - 1u) + base_name;
2202         }
2203         std::string err_msg;  // Ignored.
2204         std::string base_filename;
2205         if (filename_fn(base_location, &base_filename, &err_msg) &&
2206             ReadHeader(base_location, base_filename, bcp_pos, &err_msg)) {
2207           VLOG(image) << "Found image extension for " << ExpandLocation(base_location, bcp_pos);
2208           bcp_pos = GetNextBcpIndex();
2209           found = true;
2210           break;
2211         }
2212       }
2213       if (!found) {
2214         ++bcp_pos;
2215       }
2216     }
2217   }
2218 
2219   return true;
2220 }
2221 
LoadFromSystem(InstructionSet image_isa,bool allow_in_memory_compilation,std::string * error_msg)2222 bool ImageSpace::BootImageLayout::LoadFromSystem(InstructionSet image_isa,
2223                                                  bool allow_in_memory_compilation,
2224                                                  /*out*/ std::string* error_msg) {
2225   auto filename_fn = [image_isa](const std::string& location,
2226                                  /*out*/ std::string* filename,
2227                                  [[maybe_unused]] /*out*/ std::string* err_msg) {
2228     *filename = GetSystemImageFilename(location.c_str(), image_isa);
2229     return true;
2230   };
2231   return Load(filename_fn, allow_in_memory_compilation, error_msg);
2232 }
2233 
2234 class ImageSpace::BootImageLoader {
2235  public:
2236   // Creates an instance.
2237   // `apex_versions` is created from `Runtime::GetApexVersions` and must outlive this instance.
BootImageLoader(const std::vector<std::string> & boot_class_path,const std::vector<std::string> & boot_class_path_locations,ArrayRef<File> boot_class_path_files,ArrayRef<File> boot_class_path_image_files,ArrayRef<File> boot_class_path_vdex_files,ArrayRef<File> boot_class_path_oat_files,const std::vector<std::string> & image_locations,InstructionSet image_isa,bool relocate,bool executable,const std::string * apex_versions)2238   BootImageLoader(const std::vector<std::string>& boot_class_path,
2239                   const std::vector<std::string>& boot_class_path_locations,
2240                   ArrayRef<File> boot_class_path_files,
2241                   ArrayRef<File> boot_class_path_image_files,
2242                   ArrayRef<File> boot_class_path_vdex_files,
2243                   ArrayRef<File> boot_class_path_oat_files,
2244                   const std::vector<std::string>& image_locations,
2245                   InstructionSet image_isa,
2246                   bool relocate,
2247                   bool executable,
2248                   const std::string* apex_versions)
2249       : boot_class_path_(boot_class_path),
2250         boot_class_path_locations_(boot_class_path_locations),
2251         boot_class_path_files_(boot_class_path_files),
2252         boot_class_path_image_files_(boot_class_path_image_files),
2253         boot_class_path_vdex_files_(boot_class_path_vdex_files),
2254         boot_class_path_oat_files_(boot_class_path_oat_files),
2255         image_locations_(image_locations),
2256         image_isa_(image_isa),
2257         relocate_(relocate),
2258         executable_(executable),
2259         has_system_(false),
2260         apex_versions_(apex_versions) {}
2261 
FindImageFiles()2262   void FindImageFiles() {
2263     BootImageLayout layout(image_locations_,
2264                            boot_class_path_,
2265                            boot_class_path_locations_,
2266                            boot_class_path_files_,
2267                            boot_class_path_image_files_,
2268                            boot_class_path_vdex_files_,
2269                            boot_class_path_oat_files_,
2270                            apex_versions_);
2271     std::string image_location = layout.GetPrimaryImageLocation();
2272     std::string system_filename;
2273     bool found_image = FindImageFilenameImpl(image_location.c_str(),
2274                                              image_isa_,
2275                                              &has_system_,
2276                                              &system_filename);
2277     DCHECK_EQ(found_image, has_system_);
2278   }
2279 
HasSystem() const2280   bool HasSystem() const { return has_system_; }
2281 
2282   bool LoadFromSystem(size_t extra_reservation_size,
2283                       bool allow_in_memory_compilation,
2284                       /*out*/std::vector<std::unique_ptr<ImageSpace>>* boot_image_spaces,
2285                       /*out*/MemMap* extra_reservation,
2286                       /*out*/std::string* error_msg) REQUIRES_SHARED(Locks::mutator_lock_);
2287 
2288  private:
LoadImage(const BootImageLayout & layout,bool validate_oat_file,size_t extra_reservation_size,TimingLogger * logger,std::vector<std::unique_ptr<ImageSpace>> * boot_image_spaces,MemMap * extra_reservation,std::string * error_msg)2289   bool LoadImage(
2290       const BootImageLayout& layout,
2291       bool validate_oat_file,
2292       size_t extra_reservation_size,
2293       TimingLogger* logger,
2294       /*out*/std::vector<std::unique_ptr<ImageSpace>>* boot_image_spaces,
2295       /*out*/MemMap* extra_reservation,
2296       /*out*/std::string* error_msg) REQUIRES_SHARED(Locks::mutator_lock_) {
2297     ArrayRef<const BootImageLayout::ImageChunk> chunks = layout.GetChunks();
2298     DCHECK(!chunks.empty());
2299     const uint32_t base_address = layout.GetBaseAddress();
2300     const size_t image_component_count = layout.GetTotalComponentCount();
2301     const size_t image_reservation_size = layout.GetTotalReservationSize();
2302 
2303     DCHECK_LE(image_reservation_size, kMaxTotalImageReservationSize);
2304     static_assert(kMaxTotalImageReservationSize < std::numeric_limits<uint32_t>::max());
2305     if (extra_reservation_size > std::numeric_limits<uint32_t>::max() - image_reservation_size) {
2306       // Since the `image_reservation_size` is limited to kMaxTotalImageReservationSize,
2307       // the `extra_reservation_size` would have to be really excessive to fail this check.
2308       *error_msg = StringPrintf("Excessive extra reservation size: %zu", extra_reservation_size);
2309       return false;
2310     }
2311 
2312     // Reserve address space. If relocating, choose a random address for ALSR.
2313     uint8_t* addr = reinterpret_cast<uint8_t*>(
2314         relocate_ ? ART_BASE_ADDRESS + ChooseRelocationOffsetDelta() : base_address);
2315     MemMap image_reservation =
2316         ReserveBootImageMemory(addr, image_reservation_size + extra_reservation_size, error_msg);
2317     if (!image_reservation.IsValid()) {
2318       return false;
2319     }
2320 
2321     // Load components.
2322     std::vector<std::unique_ptr<ImageSpace>> spaces;
2323     spaces.reserve(image_component_count);
2324     size_t max_image_space_dependencies = 0u;
2325     for (size_t i = 0, num_chunks = chunks.size(); i != num_chunks; ++i) {
2326       const BootImageLayout::ImageChunk& chunk = chunks[i];
2327       std::string extension_error_msg;
2328       uint8_t* old_reservation_begin = image_reservation.Begin();
2329       size_t old_reservation_size = image_reservation.Size();
2330       DCHECK_LE(chunk.reservation_size, old_reservation_size);
2331       if (!LoadComponents(chunk,
2332                           validate_oat_file,
2333                           max_image_space_dependencies,
2334                           logger,
2335                           &spaces,
2336                           &image_reservation,
2337                           (i == 0) ? error_msg : &extension_error_msg)) {
2338         // Failed to load the chunk. If this is the primary boot image, report the error.
2339         if (i == 0) {
2340           return false;
2341         }
2342         // For extension, shrink the reservation (and remap if needed, see below).
2343         size_t new_reservation_size = old_reservation_size - chunk.reservation_size;
2344         if (new_reservation_size == 0u) {
2345           DCHECK_EQ(extra_reservation_size, 0u);
2346           DCHECK_EQ(i + 1u, num_chunks);
2347           image_reservation.Reset();
2348         } else if (old_reservation_begin != image_reservation.Begin()) {
2349           // Part of the image reservation has been used and then unmapped when
2350           // rollling back the partial boot image extension load. Try to remap
2351           // the image reservation. As this should be running single-threaded,
2352           // the address range should still be available to mmap().
2353           image_reservation.Reset();
2354           std::string remap_error_msg;
2355           image_reservation = ReserveBootImageMemory(old_reservation_begin,
2356                                                      new_reservation_size,
2357                                                      &remap_error_msg);
2358           if (!image_reservation.IsValid()) {
2359             *error_msg = StringPrintf("Failed to remap boot image reservation after failing "
2360                                           "to load boot image extension (%s: %s): %s",
2361                                       boot_class_path_locations_[chunk.start_index].c_str(),
2362                                       extension_error_msg.c_str(),
2363                                       remap_error_msg.c_str());
2364             return false;
2365           }
2366         } else {
2367           DCHECK_EQ(old_reservation_size, image_reservation.Size());
2368           image_reservation.SetSize(new_reservation_size);
2369         }
2370         LOG(ERROR) << "Failed to load boot image extension "
2371             << boot_class_path_locations_[chunk.start_index] << ": " << extension_error_msg;
2372       }
2373       // Update `max_image_space_dependencies` if all previous BCP components
2374       // were covered and loading the current chunk succeeded.
2375       size_t total_component_count = 0;
2376       for (const std::unique_ptr<ImageSpace>& space : spaces) {
2377         total_component_count += space->GetComponentCount();
2378       }
2379       if (max_image_space_dependencies == chunk.start_index &&
2380           total_component_count == chunk.start_index + chunk.component_count) {
2381         max_image_space_dependencies = chunk.start_index + chunk.component_count;
2382       }
2383     }
2384 
2385     MemMap local_extra_reservation;
2386     if (!RemapExtraReservation(extra_reservation_size,
2387                                &image_reservation,
2388                                &local_extra_reservation,
2389                                error_msg)) {
2390       return false;
2391     }
2392 
2393     MaybeRelocateSpaces(spaces, logger);
2394     DeduplicateInternedStrings(ArrayRef<const std::unique_ptr<ImageSpace>>(spaces), logger);
2395     boot_image_spaces->swap(spaces);
2396     *extra_reservation = std::move(local_extra_reservation);
2397     return true;
2398   }
2399 
2400  private:
2401   class SimpleRelocateVisitor {
2402    public:
SimpleRelocateVisitor(uint32_t diff,uint32_t begin,uint32_t size)2403     SimpleRelocateVisitor(uint32_t diff, uint32_t begin, uint32_t size)
2404         : diff_(diff), begin_(begin), size_(size) {}
2405 
2406     // Adapter taking the same arguments as SplitRangeRelocateVisitor
2407     // to simplify constructing the various visitors in DoRelocateSpaces().
SimpleRelocateVisitor(uint32_t base_diff,uint32_t current_diff,uint32_t bound,uint32_t begin,uint32_t size)2408     SimpleRelocateVisitor(uint32_t base_diff,
2409                           uint32_t current_diff,
2410                           uint32_t bound,
2411                           uint32_t begin,
2412                           uint32_t size)
2413         : SimpleRelocateVisitor(base_diff, begin, size) {
2414       // Check arguments unused by this class.
2415       DCHECK_EQ(base_diff, current_diff);
2416       DCHECK_EQ(bound, begin);
2417     }
2418 
2419     template <typename T>
operator ()(T * src) const2420     ALWAYS_INLINE T* operator()(T* src) const {
2421       DCHECK(InSource(src));
2422       uint32_t raw_src = reinterpret_cast32<uint32_t>(src);
2423       return reinterpret_cast32<T*>(raw_src + diff_);
2424     }
2425 
2426     template <typename T>
InSource(T * ptr) const2427     ALWAYS_INLINE bool InSource(T* ptr) const {
2428       uint32_t raw_ptr = reinterpret_cast32<uint32_t>(ptr);
2429       return raw_ptr - begin_ < size_;
2430     }
2431 
2432     template <typename T>
InDest(T * ptr) const2433     ALWAYS_INLINE bool InDest(T* ptr) const {
2434       uint32_t raw_ptr = reinterpret_cast32<uint32_t>(ptr);
2435       uint32_t src_ptr = raw_ptr - diff_;
2436       return src_ptr - begin_ < size_;
2437     }
2438 
2439    private:
2440     const uint32_t diff_;
2441     const uint32_t begin_;
2442     const uint32_t size_;
2443   };
2444 
2445   class SplitRangeRelocateVisitor {
2446    public:
SplitRangeRelocateVisitor(uint32_t base_diff,uint32_t current_diff,uint32_t bound,uint32_t begin,uint32_t size)2447     SplitRangeRelocateVisitor(uint32_t base_diff,
2448                               uint32_t current_diff,
2449                               uint32_t bound,
2450                               uint32_t begin,
2451                               uint32_t size)
2452         : base_diff_(base_diff),
2453           current_diff_(current_diff),
2454           bound_(bound),
2455           begin_(begin),
2456           size_(size) {
2457       DCHECK_NE(begin_, bound_);
2458       // The bound separates the boot image range and the extension range.
2459       DCHECK_LT(bound_ - begin_, size_);
2460     }
2461 
2462     template <typename T>
operator ()(T * src) const2463     ALWAYS_INLINE T* operator()(T* src) const {
2464       DCHECK(InSource(src));
2465       uint32_t raw_src = reinterpret_cast32<uint32_t>(src);
2466       uint32_t diff = (raw_src < bound_) ? base_diff_ : current_diff_;
2467       return reinterpret_cast32<T*>(raw_src + diff);
2468     }
2469 
2470     template <typename T>
InSource(T * ptr) const2471     ALWAYS_INLINE bool InSource(T* ptr) const {
2472       uint32_t raw_ptr = reinterpret_cast32<uint32_t>(ptr);
2473       return raw_ptr - begin_ < size_;
2474     }
2475 
2476    private:
2477     const uint32_t base_diff_;
2478     const uint32_t current_diff_;
2479     const uint32_t bound_;
2480     const uint32_t begin_;
2481     const uint32_t size_;
2482   };
2483 
PointerAddress(ArtMethod * method,MemberOffset offset)2484   static void** PointerAddress(ArtMethod* method, MemberOffset offset) {
2485     return reinterpret_cast<void**>(reinterpret_cast<uint8_t*>(method) + offset.Uint32Value());
2486   }
2487 
2488   template <PointerSize kPointerSize>
DoRelocateSpaces(ArrayRef<const std::unique_ptr<ImageSpace>> & spaces,int64_t base_diff64)2489   static void DoRelocateSpaces(ArrayRef<const std::unique_ptr<ImageSpace>>& spaces,
2490                                int64_t base_diff64) REQUIRES_SHARED(Locks::mutator_lock_) {
2491     DCHECK(!spaces.empty());
2492     gc::accounting::ContinuousSpaceBitmap patched_objects(
2493         gc::accounting::ContinuousSpaceBitmap::Create(
2494             "Marked objects",
2495             spaces.front()->Begin(),
2496             spaces.back()->End() - spaces.front()->Begin()));
2497     const ImageHeader& base_header = spaces[0]->GetImageHeader();
2498     size_t base_image_space_count = base_header.GetImageSpaceCount();
2499     DCHECK_LE(base_image_space_count, spaces.size());
2500     DoRelocateSpaces<kPointerSize, /*kExtension=*/ false>(
2501         spaces.SubArray(/*pos=*/ 0u, base_image_space_count),
2502         base_diff64,
2503         &patched_objects);
2504 
2505     for (size_t i = base_image_space_count, size = spaces.size(); i != size; ) {
2506       const ImageHeader& ext_header = spaces[i]->GetImageHeader();
2507       size_t ext_image_space_count = ext_header.GetImageSpaceCount();
2508       DCHECK_LE(ext_image_space_count, size - i);
2509       DoRelocateSpaces<kPointerSize, /*kExtension=*/ true>(
2510           spaces.SubArray(/*pos=*/ i, ext_image_space_count),
2511           base_diff64,
2512           &patched_objects);
2513       i += ext_image_space_count;
2514     }
2515   }
2516 
2517   template <PointerSize kPointerSize, bool kExtension>
DoRelocateSpaces(ArrayRef<const std::unique_ptr<ImageSpace>> spaces,int64_t base_diff64,gc::accounting::ContinuousSpaceBitmap * patched_objects)2518   static void DoRelocateSpaces(ArrayRef<const std::unique_ptr<ImageSpace>> spaces,
2519                                int64_t base_diff64,
2520                                gc::accounting::ContinuousSpaceBitmap* patched_objects)
2521       REQUIRES_SHARED(Locks::mutator_lock_) {
2522     DCHECK(!spaces.empty());
2523     const ImageHeader& first_header = spaces.front()->GetImageHeader();
2524     uint32_t image_begin = reinterpret_cast32<uint32_t>(first_header.GetImageBegin());
2525     uint32_t image_size = first_header.GetImageReservationSize();
2526     DCHECK_NE(image_size, 0u);
2527     uint32_t source_begin = kExtension ? first_header.GetBootImageBegin() : image_begin;
2528     uint32_t source_size = kExtension ? first_header.GetBootImageSize() + image_size : image_size;
2529     if (kExtension) {
2530       DCHECK_EQ(first_header.GetBootImageBegin() + first_header.GetBootImageSize(), image_begin);
2531     }
2532     int64_t current_diff64 = kExtension
2533         ? static_cast<int64_t>(reinterpret_cast32<uint32_t>(spaces.front()->Begin())) -
2534               static_cast<int64_t>(image_begin)
2535         : base_diff64;
2536     if (base_diff64 == 0 && current_diff64 == 0) {
2537       return;
2538     }
2539     uint32_t base_diff = static_cast<uint32_t>(base_diff64);
2540     uint32_t current_diff = static_cast<uint32_t>(current_diff64);
2541 
2542     // For boot image the main visitor is a SimpleRelocateVisitor. For the boot image extension we
2543     // mostly use a SplitRelocationVisitor but some work can still use the SimpleRelocationVisitor.
2544     using MainRelocateVisitor = typename std::conditional<
2545         kExtension, SplitRangeRelocateVisitor, SimpleRelocateVisitor>::type;
2546     SimpleRelocateVisitor simple_relocate_visitor(current_diff, image_begin, image_size);
2547     MainRelocateVisitor main_relocate_visitor(
2548         base_diff, current_diff, /*bound=*/ image_begin, source_begin, source_size);
2549 
2550     using MainPatchRelocateVisitor =
2551         PatchObjectVisitor<kPointerSize, MainRelocateVisitor, MainRelocateVisitor>;
2552     using SimplePatchRelocateVisitor =
2553         PatchObjectVisitor<kPointerSize, SimpleRelocateVisitor, SimpleRelocateVisitor>;
2554     MainPatchRelocateVisitor main_patch_object_visitor(main_relocate_visitor,
2555                                                        main_relocate_visitor);
2556     SimplePatchRelocateVisitor simple_patch_object_visitor(simple_relocate_visitor,
2557                                                            simple_relocate_visitor);
2558 
2559     // Retrieve the Class.class, Method.class and Constructor.class needed in the loops below.
2560     ObjPtr<mirror::ObjectArray<mirror::Class>> class_roots;
2561     ObjPtr<mirror::Class> class_class;
2562     ObjPtr<mirror::Class> method_class;
2563     ObjPtr<mirror::Class> constructor_class;
2564     ObjPtr<mirror::Class> field_var_handle_class;
2565     ObjPtr<mirror::Class> static_field_var_handle_class;
2566     {
2567       ObjPtr<mirror::ObjectArray<mirror::Object>> image_roots =
2568           simple_relocate_visitor(first_header.GetImageRoots<kWithoutReadBarrier>().Ptr());
2569       DCHECK(!patched_objects->Test(image_roots.Ptr()));
2570 
2571       SimpleRelocateVisitor base_relocate_visitor(
2572           base_diff,
2573           source_begin,
2574           kExtension ? source_size - image_size : image_size);
2575       int32_t class_roots_index = enum_cast<int32_t>(ImageHeader::kClassRoots);
2576       DCHECK_LT(class_roots_index, image_roots->GetLength<kVerifyNone>());
2577       class_roots = ObjPtr<mirror::ObjectArray<mirror::Class>>::DownCast(base_relocate_visitor(
2578           image_roots->GetWithoutChecks<kVerifyNone,
2579                                         kWithoutReadBarrier>(class_roots_index).Ptr()));
2580       if (kExtension) {
2581         // Class roots must have been visited if we relocated the primary boot image.
2582         DCHECK(base_diff == 0 || patched_objects->Test(class_roots.Ptr()));
2583         class_class = GetClassRoot<mirror::Class, kWithoutReadBarrier>(class_roots);
2584         method_class = GetClassRoot<mirror::Method, kWithoutReadBarrier>(class_roots);
2585         constructor_class = GetClassRoot<mirror::Constructor, kWithoutReadBarrier>(class_roots);
2586         field_var_handle_class =
2587             GetClassRoot<mirror::FieldVarHandle, kWithoutReadBarrier>(class_roots);
2588         static_field_var_handle_class =
2589             GetClassRoot<mirror::StaticFieldVarHandle, kWithoutReadBarrier>(class_roots);
2590       } else {
2591         DCHECK(!patched_objects->Test(class_roots.Ptr()));
2592         class_class = simple_relocate_visitor(
2593             GetClassRoot<mirror::Class, kWithoutReadBarrier>(class_roots).Ptr());
2594         method_class = simple_relocate_visitor(
2595             GetClassRoot<mirror::Method, kWithoutReadBarrier>(class_roots).Ptr());
2596         constructor_class = simple_relocate_visitor(
2597             GetClassRoot<mirror::Constructor, kWithoutReadBarrier>(class_roots).Ptr());
2598         field_var_handle_class = simple_relocate_visitor(
2599             GetClassRoot<mirror::FieldVarHandle, kWithoutReadBarrier>(class_roots).Ptr());
2600         static_field_var_handle_class = simple_relocate_visitor(
2601             GetClassRoot<mirror::StaticFieldVarHandle, kWithoutReadBarrier>(class_roots).Ptr());
2602       }
2603     }
2604 
2605     for (const std::unique_ptr<ImageSpace>& space : spaces) {
2606       // First patch the image header.
2607       reinterpret_cast<ImageHeader*>(space->Begin())->RelocateImageReferences(current_diff64);
2608       reinterpret_cast<ImageHeader*>(space->Begin())->RelocateBootImageReferences(base_diff64);
2609 
2610       // Patch fields and methods.
2611       const ImageHeader& image_header = space->GetImageHeader();
2612       image_header.VisitPackedArtFields([&](ArtField& field) REQUIRES_SHARED(Locks::mutator_lock_) {
2613         // Fields always reference class in the current image.
2614         simple_patch_object_visitor.template PatchGcRoot</*kMayBeNull=*/ false>(
2615             &field.DeclaringClassRoot());
2616       }, space->Begin());
2617       image_header.VisitPackedArtMethods([&](ArtMethod& method)
2618           REQUIRES_SHARED(Locks::mutator_lock_) {
2619         main_patch_object_visitor.PatchGcRoot(&method.DeclaringClassRoot());
2620         if (!method.HasCodeItem()) {
2621           void** data_address = PointerAddress(&method, ArtMethod::DataOffset(kPointerSize));
2622           main_patch_object_visitor.PatchNativePointer(data_address);
2623         }
2624         void** entrypoint_address =
2625             PointerAddress(&method, ArtMethod::EntryPointFromQuickCompiledCodeOffset(kPointerSize));
2626         main_patch_object_visitor.PatchNativePointer(entrypoint_address);
2627       }, space->Begin(), kPointerSize);
2628       auto method_table_visitor = [&](ArtMethod* method) {
2629         DCHECK(method != nullptr);
2630         return main_relocate_visitor(method);
2631       };
2632       image_header.VisitPackedImTables(method_table_visitor, space->Begin(), kPointerSize);
2633       image_header.VisitPackedImtConflictTables(method_table_visitor, space->Begin(), kPointerSize);
2634       image_header.VisitJniStubMethods</*kUpdate=*/ true>(method_table_visitor,
2635                                                           space->Begin(),
2636                                                           kPointerSize);
2637 
2638       // Patch the intern table.
2639       if (image_header.GetInternedStringsSection().Size() != 0u) {
2640         const uint8_t* data = space->Begin() + image_header.GetInternedStringsSection().Offset();
2641         size_t read_count;
2642         InternTable::UnorderedSet temp_set(data, /*make_copy_of_data=*/ false, &read_count);
2643         for (GcRoot<mirror::String>& slot : temp_set) {
2644           // The intern table contains only strings in the current image.
2645           simple_patch_object_visitor.template PatchGcRoot</*kMayBeNull=*/ false>(&slot);
2646         }
2647       }
2648 
2649       // Patch the class table and classes, so that we can traverse class hierarchy to
2650       // determine the types of other objects when we visit them later.
2651       if (image_header.GetClassTableSection().Size() != 0u) {
2652         uint8_t* data = space->Begin() + image_header.GetClassTableSection().Offset();
2653         size_t read_count;
2654         ClassTable::ClassSet temp_set(data, /*make_copy_of_data=*/ false, &read_count);
2655         DCHECK(!temp_set.empty());
2656         // The class table contains only classes in the current image.
2657         ClassTableVisitor class_table_visitor(simple_relocate_visitor);
2658         for (ClassTable::TableSlot& slot : temp_set) {
2659           slot.VisitRoot(class_table_visitor);
2660           ObjPtr<mirror::Class> klass = slot.Read<kWithoutReadBarrier>();
2661           DCHECK(klass != nullptr);
2662           DCHECK(!patched_objects->Test(klass.Ptr()));
2663           patched_objects->Set(klass.Ptr());
2664           main_patch_object_visitor.VisitClass(klass, class_class);
2665           // Then patch the non-embedded vtable and iftable.
2666           ObjPtr<mirror::PointerArray> vtable =
2667               klass->GetVTable<kVerifyNone, kWithoutReadBarrier>();
2668           if ((kExtension ? simple_relocate_visitor.InDest(vtable.Ptr()) : vtable != nullptr) &&
2669               !patched_objects->Set(vtable.Ptr())) {
2670             main_patch_object_visitor.VisitPointerArray(vtable);
2671           }
2672           ObjPtr<mirror::IfTable> iftable = klass->GetIfTable<kVerifyNone, kWithoutReadBarrier>();
2673           if (kExtension ? simple_relocate_visitor.InDest(iftable.Ptr()) : iftable != nullptr) {
2674             int32_t ifcount = iftable->Count<kVerifyNone>();
2675             for (int32_t i = 0; i != ifcount; ++i) {
2676               ObjPtr<mirror::PointerArray> unpatched_ifarray =
2677                   iftable->GetMethodArrayOrNull<kVerifyNone, kWithoutReadBarrier>(i);
2678               if (kExtension ? simple_relocate_visitor.InSource(unpatched_ifarray.Ptr())
2679                              : unpatched_ifarray != nullptr) {
2680                 // The iftable has not been patched, so we need to explicitly adjust the pointer.
2681                 ObjPtr<mirror::PointerArray> ifarray =
2682                     simple_relocate_visitor(unpatched_ifarray.Ptr());
2683                 if (!patched_objects->Set(ifarray.Ptr())) {
2684                   main_patch_object_visitor.VisitPointerArray(ifarray);
2685                 }
2686               }
2687             }
2688           }
2689         }
2690       }
2691     }
2692 
2693     for (const std::unique_ptr<ImageSpace>& space : spaces) {
2694       const ImageHeader& image_header = space->GetImageHeader();
2695 
2696       static_assert(IsAligned<kObjectAlignment>(sizeof(ImageHeader)), "Header alignment check");
2697       uint32_t objects_end = image_header.GetObjectsSection().Size();
2698       DCHECK_ALIGNED(objects_end, kObjectAlignment);
2699       for (uint32_t pos = sizeof(ImageHeader); pos != objects_end; ) {
2700         mirror::Object* object = reinterpret_cast<mirror::Object*>(space->Begin() + pos);
2701         // Note: use Test() rather than Set() as this is the last time we're checking this object.
2702         if (!patched_objects->Test(object)) {
2703           // This is the last pass over objects, so we do not need to Set().
2704           main_patch_object_visitor.VisitObject(object);
2705           ObjPtr<mirror::Class> klass = object->GetClass<kVerifyNone, kWithoutReadBarrier>();
2706           if (klass == method_class || klass == constructor_class) {
2707             // Patch the ArtMethod* in the mirror::Executable subobject.
2708             ObjPtr<mirror::Executable> as_executable =
2709                 ObjPtr<mirror::Executable>::DownCast(object);
2710             ArtMethod* unpatched_method = as_executable->GetArtMethod<kVerifyNone>();
2711             ArtMethod* patched_method = main_relocate_visitor(unpatched_method);
2712             as_executable->SetArtMethod</*kTransactionActive=*/ false,
2713                                         /*kCheckTransaction=*/ true,
2714                                         kVerifyNone>(patched_method);
2715           } else if (klass == field_var_handle_class || klass == static_field_var_handle_class) {
2716             // Patch the ArtField* in the mirror::FieldVarHandle subobject.
2717             ObjPtr<mirror::FieldVarHandle> as_field_var_handle =
2718                 ObjPtr<mirror::FieldVarHandle>::DownCast(object);
2719             ArtField* unpatched_field = as_field_var_handle->GetArtField<kVerifyNone>();
2720             ArtField* patched_field = main_relocate_visitor(unpatched_field);
2721             as_field_var_handle->SetArtField<kVerifyNone>(patched_field);
2722           }
2723         }
2724         pos += RoundUp(object->SizeOf<kVerifyNone>(), kObjectAlignment);
2725       }
2726     }
2727     if (kIsDebugBuild && !kExtension) {
2728       // We used just Test() instead of Set() above but we need to use Set()
2729       // for class roots to satisfy a DCHECK() for extensions.
2730       DCHECK(!patched_objects->Test(class_roots.Ptr()));
2731       patched_objects->Set(class_roots.Ptr());
2732     }
2733   }
2734 
MaybeRelocateSpaces(const std::vector<std::unique_ptr<ImageSpace>> & spaces,TimingLogger * logger)2735   void MaybeRelocateSpaces(const std::vector<std::unique_ptr<ImageSpace>>& spaces,
2736                            TimingLogger* logger)
2737       REQUIRES_SHARED(Locks::mutator_lock_) {
2738     TimingLogger::ScopedTiming timing("MaybeRelocateSpaces", logger);
2739     ImageSpace* first_space = spaces.front().get();
2740     const ImageHeader& first_space_header = first_space->GetImageHeader();
2741     int64_t base_diff64 =
2742         static_cast<int64_t>(reinterpret_cast32<uint32_t>(first_space->Begin())) -
2743         static_cast<int64_t>(reinterpret_cast32<uint32_t>(first_space_header.GetImageBegin()));
2744     if (!relocate_) {
2745       DCHECK_EQ(base_diff64, 0);
2746     }
2747 
2748     // While `Thread::Current()` is null, the `ScopedDebugDisallowReadBarriers`
2749     // cannot be used but the class `ReadBarrier` shall not allow read barriers anyway.
2750     // For some gtests we actually have an initialized `Thread:Current()`.
2751     std::optional<ScopedDebugDisallowReadBarriers> sddrb(std::nullopt);
2752     if (kCheckDebugDisallowReadBarrierCount && Thread::Current() != nullptr) {
2753       sddrb.emplace(Thread::Current());
2754     }
2755 
2756     ArrayRef<const std::unique_ptr<ImageSpace>> spaces_ref(spaces);
2757     PointerSize pointer_size = first_space_header.GetPointerSize();
2758     if (pointer_size == PointerSize::k64) {
2759       DoRelocateSpaces<PointerSize::k64>(spaces_ref, base_diff64);
2760     } else {
2761       DoRelocateSpaces<PointerSize::k32>(spaces_ref, base_diff64);
2762     }
2763   }
2764 
DeduplicateInternedStrings(ArrayRef<const std::unique_ptr<ImageSpace>> spaces,TimingLogger * logger)2765   void DeduplicateInternedStrings(ArrayRef<const std::unique_ptr<ImageSpace>> spaces,
2766                                   TimingLogger* logger) REQUIRES_SHARED(Locks::mutator_lock_) {
2767     TimingLogger::ScopedTiming timing("DeduplicateInternedStrings", logger);
2768     DCHECK(!spaces.empty());
2769     size_t num_spaces = spaces.size();
2770     const ImageHeader& primary_header = spaces.front()->GetImageHeader();
2771     size_t primary_image_count = primary_header.GetImageSpaceCount();
2772     size_t primary_image_component_count = primary_header.GetComponentCount();
2773     DCHECK_LE(primary_image_count, num_spaces);
2774     // The primary boot image can be generated with `--single-image` on device, when generated
2775     // in-memory or with odrefresh.
2776     DCHECK(primary_image_count == primary_image_component_count || primary_image_count == 1);
2777     size_t component_count = primary_image_component_count;
2778     size_t space_pos = primary_image_count;
2779     while (space_pos != num_spaces) {
2780       const ImageHeader& current_header = spaces[space_pos]->GetImageHeader();
2781       size_t image_space_count = current_header.GetImageSpaceCount();
2782       DCHECK_LE(image_space_count, num_spaces - space_pos);
2783       size_t dependency_component_count = current_header.GetBootImageComponentCount();
2784       DCHECK_LE(dependency_component_count, component_count);
2785       if (dependency_component_count < component_count) {
2786         // There shall be no duplicate strings with the components that this space depends on.
2787         // Find the end of the dependencies, i.e. start of non-dependency images.
2788         size_t start_component_count = primary_image_component_count;
2789         size_t start_pos = primary_image_count;
2790         while (start_component_count != dependency_component_count) {
2791           const ImageHeader& dependency_header = spaces[start_pos]->GetImageHeader();
2792           DCHECK_LE(dependency_header.GetComponentCount(),
2793                     dependency_component_count - start_component_count);
2794           start_component_count += dependency_header.GetComponentCount();
2795           start_pos += dependency_header.GetImageSpaceCount();
2796         }
2797         // Remove duplicates from all intern tables belonging to the chunk.
2798         ArrayRef<const std::unique_ptr<ImageSpace>> old_spaces =
2799             spaces.SubArray(/*pos=*/ start_pos, space_pos - start_pos);
2800         SafeMap<mirror::String*, mirror::String*> intern_remap;
2801         for (size_t i = 0; i != image_space_count; ++i) {
2802           ImageSpace* new_space = spaces[space_pos + i].get();
2803           Loader::RemoveInternTableDuplicates(old_spaces, new_space, &intern_remap);
2804         }
2805         // Remap string for all spaces belonging to the chunk.
2806         if (!intern_remap.empty()) {
2807           for (size_t i = 0; i != image_space_count; ++i) {
2808             ImageSpace* new_space = spaces[space_pos + i].get();
2809             Loader::RemapInternedStringDuplicates(intern_remap, new_space);
2810           }
2811         }
2812       }
2813       component_count += current_header.GetComponentCount();
2814       space_pos += image_space_count;
2815     }
2816   }
2817 
Load(const std::string & image_location,const std::string & image_filename,const std::vector<std::string> & profile_files,android::base::unique_fd art_fd,TimingLogger * logger,MemMap * image_reservation,std::string * error_msg)2818   std::unique_ptr<ImageSpace> Load(const std::string& image_location,
2819                                    const std::string& image_filename,
2820                                    const std::vector<std::string>& profile_files,
2821                                    android::base::unique_fd art_fd,
2822                                    TimingLogger* logger,
2823                                    /*inout*/MemMap* image_reservation,
2824                                    /*out*/std::string* error_msg)
2825       REQUIRES_SHARED(Locks::mutator_lock_) {
2826     if (art_fd.get() != -1) {
2827       VLOG(startup) << "Using image file " << image_filename.c_str() << " for image location "
2828                     << image_location << " for compiled extension";
2829 
2830       File image_file(art_fd.release(), image_filename, /*check_usage=*/ false);
2831       std::unique_ptr<ImageSpace> result = Loader::Init(&image_file,
2832                                                         image_filename.c_str(),
2833                                                         image_location.c_str(),
2834                                                         profile_files,
2835                                                         /*allow_direct_mapping=*/ false,
2836                                                         logger,
2837                                                         image_reservation,
2838                                                         error_msg);
2839       // Note: We're closing the image file descriptor here when we destroy
2840       // the `image_file` as we no longer need it.
2841       return result;
2842     }
2843 
2844     VLOG(startup) << "Using image file " << image_filename.c_str() << " for image location "
2845                   << image_location;
2846 
2847     // If we are in /system we can assume the image is good. We can also
2848     // assume this if we are using a relocated image (i.e. image checksum
2849     // matches) since this is only different by the offset. We need this to
2850     // make sure that host tests continue to work.
2851     // Since we are the boot image, pass null since we load the oat file from the boot image oat
2852     // file name.
2853     return Loader::Init(image_filename.c_str(),
2854                         image_location.c_str(),
2855                         logger,
2856                         image_reservation,
2857                         error_msg);
2858   }
2859 
OpenOatFile(ImageSpace * space,android::base::unique_fd vdex_fd,android::base::unique_fd oat_fd,ArrayRef<const std::string> dex_filenames,ArrayRef<File> dex_files,bool validate_oat_file,ArrayRef<const std::unique_ptr<ImageSpace>> dependencies,TimingLogger * logger,MemMap * image_reservation,std::string * error_msg)2860   bool OpenOatFile(ImageSpace* space,
2861                    android::base::unique_fd vdex_fd,
2862                    android::base::unique_fd oat_fd,
2863                    ArrayRef<const std::string> dex_filenames,
2864                    ArrayRef<File> dex_files,
2865                    bool validate_oat_file,
2866                    ArrayRef<const std::unique_ptr<ImageSpace>> dependencies,
2867                    TimingLogger* logger,
2868                    /*inout*/ MemMap* image_reservation,
2869                    /*out*/ std::string* error_msg) {
2870     // VerifyImageAllocations() will be called later in Runtime::Init()
2871     // as some class roots like ArtMethod::java_lang_reflect_ArtMethod_
2872     // and ArtField::java_lang_reflect_ArtField_, which are used from
2873     // Object::SizeOf() which VerifyImageAllocations() calls, are not
2874     // set yet at this point.
2875     DCHECK(image_reservation != nullptr);
2876     std::unique_ptr<OatFile> oat_file;
2877     {
2878       TimingLogger::ScopedTiming timing("OpenOatFile", logger);
2879       std::string oat_filename =
2880           ImageHeader::GetOatLocationFromImageLocation(space->GetImageFilename());
2881       std::string oat_location =
2882           ImageHeader::GetOatLocationFromImageLocation(space->GetImageLocation());
2883 
2884       DCHECK_EQ(vdex_fd.get() != -1, oat_fd.get() != -1);
2885       if (vdex_fd.get() == -1) {
2886         oat_file.reset(OatFile::Open(/*zip_fd=*/-1,
2887                                      oat_filename,
2888                                      oat_location,
2889                                      executable_,
2890                                      /*low_4gb=*/false,
2891                                      dex_filenames,
2892                                      dex_files,
2893                                      image_reservation,
2894                                      error_msg));
2895       } else {
2896         oat_file.reset(OatFile::Open(/*zip_fd=*/-1,
2897                                      vdex_fd.get(),
2898                                      oat_fd.get(),
2899                                      oat_location,
2900                                      executable_,
2901                                      /*low_4gb=*/false,
2902                                      dex_filenames,
2903                                      dex_files,
2904                                      image_reservation,
2905                                      error_msg));
2906         // We no longer need the file descriptors and they will be closed by
2907         // the unique_fd destructor when we leave this function.
2908       }
2909 
2910       if (oat_file == nullptr) {
2911         *error_msg = StringPrintf("Failed to open oat file '%s' referenced from image %s: %s",
2912                                   oat_filename.c_str(),
2913                                   space->GetName(),
2914                                   error_msg->c_str());
2915         return false;
2916       }
2917       const ImageHeader& image_header = space->GetImageHeader();
2918       uint32_t oat_checksum = oat_file->GetOatHeader().GetChecksum();
2919       uint32_t image_oat_checksum = image_header.GetOatChecksum();
2920       if (oat_checksum != image_oat_checksum) {
2921         *error_msg = StringPrintf("Failed to match oat file checksum 0x%x to expected oat checksum"
2922                                   " 0x%x in image %s",
2923                                   oat_checksum,
2924                                   image_oat_checksum,
2925                                   space->GetName());
2926         return false;
2927       }
2928       const char* oat_boot_class_path =
2929           oat_file->GetOatHeader().GetStoreValueByKey(OatHeader::kBootClassPathKey);
2930       oat_boot_class_path = (oat_boot_class_path != nullptr) ? oat_boot_class_path : "";
2931       const char* oat_boot_class_path_checksums =
2932           oat_file->GetOatHeader().GetStoreValueByKey(OatHeader::kBootClassPathChecksumsKey);
2933       oat_boot_class_path_checksums =
2934           (oat_boot_class_path_checksums != nullptr) ? oat_boot_class_path_checksums : "";
2935       size_t component_count = image_header.GetComponentCount();
2936       if (component_count == 0u) {
2937         if (oat_boot_class_path[0] != 0 || oat_boot_class_path_checksums[0] != 0) {
2938           *error_msg = StringPrintf("Unexpected non-empty boot class path %s and/or checksums %s"
2939                                     " in image %s",
2940                                     oat_boot_class_path,
2941                                     oat_boot_class_path_checksums,
2942                                     space->GetName());
2943           return false;
2944         }
2945       } else if (dependencies.empty()) {
2946         std::string expected_boot_class_path = Join(ArrayRef<const std::string>(
2947               boot_class_path_locations_).SubArray(0u, component_count), ':');
2948         if (expected_boot_class_path != oat_boot_class_path) {
2949           *error_msg = StringPrintf("Failed to match oat boot class path %s to expected "
2950                                     "boot class path %s in image %s",
2951                                     oat_boot_class_path,
2952                                     expected_boot_class_path.c_str(),
2953                                     space->GetName());
2954           return false;
2955         }
2956       } else {
2957         std::string local_error_msg;
2958         if (!VerifyBootClassPathChecksums(
2959                  oat_boot_class_path_checksums,
2960                  oat_boot_class_path,
2961                  dependencies,
2962                  ArrayRef<const std::string>(boot_class_path_locations_),
2963                  ArrayRef<const std::string>(boot_class_path_),
2964                  &local_error_msg)) {
2965           *error_msg = StringPrintf("Failed to verify BCP %s with checksums %s in image %s: %s",
2966                                     oat_boot_class_path,
2967                                     oat_boot_class_path_checksums,
2968                                     space->GetName(),
2969                                     local_error_msg.c_str());
2970           return false;
2971         }
2972       }
2973       ptrdiff_t relocation_diff = space->Begin() - image_header.GetImageBegin();
2974       CHECK(image_header.GetOatDataBegin() != nullptr);
2975       uint8_t* oat_data_begin = image_header.GetOatDataBegin() + relocation_diff;
2976       if (oat_file->Begin() != oat_data_begin) {
2977         *error_msg = StringPrintf("Oat file '%s' referenced from image %s has unexpected begin"
2978                                       " %p v. %p",
2979                                   oat_filename.c_str(),
2980                                   space->GetName(),
2981                                   oat_file->Begin(),
2982                                   oat_data_begin);
2983         return false;
2984       }
2985     }
2986     if (validate_oat_file) {
2987       TimingLogger::ScopedTiming timing("ValidateOatFile", logger);
2988       if (!ImageSpace::ValidateOatFile(*oat_file, error_msg)) {
2989         DCHECK(!error_msg->empty());
2990         return false;
2991       }
2992     }
2993 
2994     // As an optimization, madvise the oat file into memory if it's being used
2995     // for execution with an active runtime. This can significantly improve
2996     // ZygoteInit class preload performance.
2997     if (executable_) {
2998       Runtime* runtime = Runtime::Current();
2999       if (runtime != nullptr) {
3000         Runtime::MadviseFileForRange(runtime->GetMadviseWillNeedSizeOdex(),
3001                                      oat_file->Size(),
3002                                      oat_file->Begin(),
3003                                      oat_file->End(),
3004                                      oat_file->GetLocation());
3005       }
3006     }
3007 
3008     space->oat_file_ = std::move(oat_file);
3009     space->oat_file_non_owned_ = space->oat_file_.get();
3010 
3011     return true;
3012   }
3013 
LoadComponents(const BootImageLayout::ImageChunk & chunk,bool validate_oat_file,size_t max_image_space_dependencies,TimingLogger * logger,std::vector<std::unique_ptr<ImageSpace>> * spaces,MemMap * image_reservation,std::string * error_msg)3014   bool LoadComponents(const BootImageLayout::ImageChunk& chunk,
3015                       bool validate_oat_file,
3016                       size_t max_image_space_dependencies,
3017                       TimingLogger* logger,
3018                       /*inout*/std::vector<std::unique_ptr<ImageSpace>>* spaces,
3019                       /*inout*/MemMap* image_reservation,
3020                       /*out*/std::string* error_msg)
3021       REQUIRES_SHARED(Locks::mutator_lock_) {
3022     // Make sure we destroy the spaces we created if we're returning an error.
3023     // Note that this can unmap part of the original `image_reservation`.
3024     class Guard {
3025      public:
3026       explicit Guard(std::vector<std::unique_ptr<ImageSpace>>* spaces_in)
3027           : spaces_(spaces_in), committed_(spaces_->size()) {}
3028       void Commit() {
3029         DCHECK_LT(committed_, spaces_->size());
3030         committed_ = spaces_->size();
3031       }
3032       ~Guard() {
3033         DCHECK_LE(committed_, spaces_->size());
3034         spaces_->resize(committed_);
3035       }
3036      private:
3037       std::vector<std::unique_ptr<ImageSpace>>* const spaces_;
3038       size_t committed_;
3039     };
3040     Guard guard(spaces);
3041 
3042     bool is_extension = (chunk.start_index != 0u);
3043     DCHECK_NE(spaces->empty(), is_extension);
3044     if (max_image_space_dependencies < chunk.boot_image_component_count) {
3045       DCHECK(is_extension);
3046       *error_msg = StringPrintf("Missing dependencies for extension component %s, %zu < %u",
3047                                 boot_class_path_locations_[chunk.start_index].c_str(),
3048                                 max_image_space_dependencies,
3049                                 chunk.boot_image_component_count);
3050       return false;
3051     }
3052     ArrayRef<const std::string> requested_bcp_locations =
3053         ArrayRef<const std::string>(boot_class_path_locations_).SubArray(
3054             chunk.start_index, chunk.image_space_count);
3055     std::vector<std::string> locations =
3056         ExpandMultiImageLocations(requested_bcp_locations, chunk.base_location, is_extension);
3057     std::vector<std::string> filenames =
3058         ExpandMultiImageLocations(requested_bcp_locations, chunk.base_filename, is_extension);
3059     DCHECK_EQ(locations.size(), filenames.size());
3060     size_t max_dependency_count = spaces->size();
3061     for (size_t i = 0u, size = locations.size(); i != size; ++i) {
3062       android::base::unique_fd image_fd;
3063       if (chunk.art_fd.get() >= 0) {
3064         DCHECK_EQ(locations.size(), 1u);
3065         image_fd = std::move(chunk.art_fd);
3066       } else {
3067         size_t pos = chunk.start_index + i;
3068         int arg_image_fd =
3069             pos < boot_class_path_image_files_.size() ? boot_class_path_image_files_[pos].Fd() : -1;
3070         if (arg_image_fd >= 0) {
3071           image_fd.reset(DupCloexec(arg_image_fd));
3072         }
3073       }
3074       spaces->push_back(Load(locations[i],
3075                              filenames[i],
3076                              chunk.profile_files,
3077                              std::move(image_fd),
3078                              logger,
3079                              image_reservation,
3080                              error_msg));
3081       const ImageSpace* space = spaces->back().get();
3082       if (space == nullptr) {
3083         return false;
3084       }
3085       uint32_t expected_component_count = (i == 0u) ? chunk.component_count : 0u;
3086       uint32_t expected_reservation_size = (i == 0u) ? chunk.reservation_size : 0u;
3087       if (!Loader::CheckImageReservationSize(*space, expected_reservation_size, error_msg) ||
3088           !Loader::CheckImageComponentCount(*space, expected_component_count, error_msg)) {
3089         return false;
3090       }
3091       const ImageHeader& header = space->GetImageHeader();
3092       if (i == 0 && (chunk.checksum != header.GetImageChecksum() ||
3093                      chunk.image_space_count != header.GetImageSpaceCount() ||
3094                      chunk.boot_image_component_count != header.GetBootImageComponentCount() ||
3095                      chunk.boot_image_checksum != header.GetBootImageChecksum() ||
3096                      chunk.boot_image_size != header.GetBootImageSize())) {
3097         *error_msg = StringPrintf("Image header modified since previously read from %s; "
3098                                       "checksum: 0x%08x -> 0x%08x,"
3099                                       "image_space_count: %u -> %u"
3100                                       "boot_image_component_count: %u -> %u, "
3101                                       "boot_image_checksum: 0x%08x -> 0x%08x"
3102                                       "boot_image_size: 0x%08x -> 0x%08x",
3103                                   space->GetImageFilename().c_str(),
3104                                   chunk.checksum,
3105                                   chunk.image_space_count,
3106                                   header.GetImageSpaceCount(),
3107                                   header.GetImageChecksum(),
3108                                   chunk.boot_image_component_count,
3109                                   header.GetBootImageComponentCount(),
3110                                   chunk.boot_image_checksum,
3111                                   header.GetBootImageChecksum(),
3112                                   chunk.boot_image_size,
3113                                   header.GetBootImageSize());
3114         return false;
3115       }
3116     }
3117     DCHECK_GE(max_image_space_dependencies, chunk.boot_image_component_count);
3118     size_t dependency_count = 0;
3119     size_t dependency_component_count = 0;
3120     while (dependency_component_count < chunk.boot_image_component_count &&
3121            dependency_count < max_dependency_count) {
3122       const ImageHeader& current_header = (*spaces)[dependency_count]->GetImageHeader();
3123       dependency_component_count += current_header.GetComponentCount();
3124       dependency_count += current_header.GetImageSpaceCount();
3125     }
3126     if (dependency_component_count != chunk.boot_image_component_count) {
3127       *error_msg = StringPrintf(
3128           "Unable to find dependencies from image spaces; boot_image_component_count: %u",
3129           chunk.boot_image_component_count);
3130       return false;
3131     }
3132     ArrayRef<const std::unique_ptr<ImageSpace>> dependencies =
3133         ArrayRef<const std::unique_ptr<ImageSpace>>(*spaces).SubArray(
3134             /*pos=*/ 0u, dependency_count);
3135     for (size_t i = 0u, size = locations.size(); i != size; ++i) {
3136       ImageSpace* space = (*spaces)[spaces->size() - chunk.image_space_count + i].get();
3137       size_t bcp_chunk_size = (chunk.image_space_count == 1u) ? chunk.component_count : 1u;
3138 
3139       size_t pos = chunk.start_index + i;
3140       ArrayRef<File> boot_class_path_files =
3141           boot_class_path_files_.empty() ?
3142               ArrayRef<File>() :
3143               boot_class_path_files_.SubArray(/*pos=*/pos, bcp_chunk_size);
3144 
3145       // Select vdex and oat FD if any exists.
3146       android::base::unique_fd vdex_fd;
3147       android::base::unique_fd oat_fd;
3148       if (chunk.vdex_fd.get() >= 0) {
3149         DCHECK_EQ(locations.size(), 1u);
3150         vdex_fd = std::move(chunk.vdex_fd);
3151       } else {
3152         int arg_vdex_fd =
3153             pos < boot_class_path_vdex_files_.size() ? boot_class_path_vdex_files_[pos].Fd() : -1;
3154         if (arg_vdex_fd >= 0) {
3155           vdex_fd.reset(DupCloexec(arg_vdex_fd));
3156         }
3157       }
3158       if (chunk.oat_fd.get() >= 0) {
3159         DCHECK_EQ(locations.size(), 1u);
3160         oat_fd = std::move(chunk.oat_fd);
3161       } else {
3162         int arg_oat_fd =
3163             pos < boot_class_path_oat_files_.size() ? boot_class_path_oat_files_[pos].Fd() : -1;
3164         if (arg_oat_fd >= 0) {
3165           oat_fd.reset(DupCloexec(arg_oat_fd));
3166         }
3167       }
3168 
3169       if (!OpenOatFile(space,
3170                        std::move(vdex_fd),
3171                        std::move(oat_fd),
3172                        boot_class_path_.SubArray(/*pos=*/pos, bcp_chunk_size),
3173                        boot_class_path_files,
3174                        validate_oat_file,
3175                        dependencies,
3176                        logger,
3177                        image_reservation,
3178                        error_msg)) {
3179         return false;
3180       }
3181     }
3182 
3183     guard.Commit();
3184     return true;
3185   }
3186 
ReserveBootImageMemory(uint8_t * addr,uint32_t reservation_size,std::string * error_msg)3187   MemMap ReserveBootImageMemory(uint8_t* addr,
3188                                 uint32_t reservation_size,
3189                                 /*out*/std::string* error_msg) {
3190     DCHECK_ALIGNED(reservation_size, kElfSegmentAlignment);
3191     DCHECK_ALIGNED(addr, kElfSegmentAlignment);
3192     return MemMap::MapAnonymous("Boot image reservation",
3193                                 addr,
3194                                 reservation_size,
3195                                 PROT_NONE,
3196                                 /*low_4gb=*/ true,
3197                                 /*reuse=*/ false,
3198                                 /*reservation=*/ nullptr,
3199                                 error_msg);
3200   }
3201 
RemapExtraReservation(size_t extra_reservation_size,MemMap * image_reservation,MemMap * extra_reservation,std::string * error_msg)3202   bool RemapExtraReservation(size_t extra_reservation_size,
3203                              /*inout*/MemMap* image_reservation,
3204                              /*out*/MemMap* extra_reservation,
3205                              /*out*/std::string* error_msg) {
3206     DCHECK_ALIGNED(extra_reservation_size, kElfSegmentAlignment);
3207     DCHECK(!extra_reservation->IsValid());
3208     size_t expected_size = image_reservation->IsValid() ? image_reservation->Size() : 0u;
3209     if (extra_reservation_size != expected_size) {
3210       *error_msg = StringPrintf("Image reservation mismatch after loading boot image: %zu != %zu",
3211                                 extra_reservation_size,
3212                                 expected_size);
3213       return false;
3214     }
3215     if (extra_reservation_size != 0u) {
3216       DCHECK(image_reservation->IsValid());
3217       DCHECK_EQ(extra_reservation_size, image_reservation->Size());
3218       *extra_reservation = image_reservation->RemapAtEnd(image_reservation->Begin(),
3219                                                          "Boot image extra reservation",
3220                                                          PROT_NONE,
3221                                                          error_msg);
3222       if (!extra_reservation->IsValid()) {
3223         return false;
3224       }
3225     }
3226     DCHECK(!image_reservation->IsValid());
3227     return true;
3228   }
3229 
3230   const ArrayRef<const std::string> boot_class_path_;
3231   const ArrayRef<const std::string> boot_class_path_locations_;
3232   ArrayRef<File> boot_class_path_files_;
3233   ArrayRef<File> boot_class_path_image_files_;
3234   ArrayRef<File> boot_class_path_vdex_files_;
3235   ArrayRef<File> boot_class_path_oat_files_;
3236   const ArrayRef<const std::string> image_locations_;
3237   const InstructionSet image_isa_;
3238   const bool relocate_;
3239   const bool executable_;
3240   bool has_system_;
3241   const std::string* apex_versions_;
3242 };
3243 
LoadFromSystem(size_t extra_reservation_size,bool allow_in_memory_compilation,std::vector<std::unique_ptr<ImageSpace>> * boot_image_spaces,MemMap * extra_reservation,std::string * error_msg)3244 bool ImageSpace::BootImageLoader::LoadFromSystem(
3245     size_t extra_reservation_size,
3246     bool allow_in_memory_compilation,
3247     /*out*/std::vector<std::unique_ptr<ImageSpace>>* boot_image_spaces,
3248     /*out*/MemMap* extra_reservation,
3249     /*out*/std::string* error_msg) {
3250   TimingLogger logger(__PRETTY_FUNCTION__, /*precise=*/ true, VLOG_IS_ON(image));
3251 
3252   if (gPageSize != kMinPageSize) {
3253     *error_msg = "Loading boot image is only supported on devices with 4K page size";
3254     return false;
3255   }
3256 
3257   BootImageLayout layout(image_locations_,
3258                          boot_class_path_,
3259                          boot_class_path_locations_,
3260                          boot_class_path_files_,
3261                          boot_class_path_image_files_,
3262                          boot_class_path_vdex_files_,
3263                          boot_class_path_oat_files_,
3264                          apex_versions_);
3265   if (!layout.LoadFromSystem(image_isa_, allow_in_memory_compilation, error_msg)) {
3266     return false;
3267   }
3268 
3269   // Load the image. We don't validate oat files in this stage because they have been validated
3270   // before.
3271   if (!LoadImage(layout,
3272                  /*validate_oat_file=*/ false,
3273                  extra_reservation_size,
3274                  &logger,
3275                  boot_image_spaces,
3276                  extra_reservation,
3277                  error_msg)) {
3278     return false;
3279   }
3280 
3281   if (VLOG_IS_ON(image)) {
3282     LOG(INFO) << "ImageSpace::BootImageLoader::LoadFromSystem exiting "
3283         << *boot_image_spaces->front();
3284     logger.Dump(LOG_STREAM(INFO));
3285   }
3286   return true;
3287 }
3288 
IsBootClassPathOnDisk(InstructionSet image_isa)3289 bool ImageSpace::IsBootClassPathOnDisk(InstructionSet image_isa) {
3290   Runtime* runtime = Runtime::Current();
3291   BootImageLayout layout(ArrayRef<const std::string>(runtime->GetImageLocations()),
3292                          ArrayRef<const std::string>(runtime->GetBootClassPath()),
3293                          ArrayRef<const std::string>(runtime->GetBootClassPathLocations()),
3294                          runtime->GetBootClassPathFiles(),
3295                          runtime->GetBootClassPathImageFiles(),
3296                          runtime->GetBootClassPathVdexFiles(),
3297                          runtime->GetBootClassPathOatFiles(),
3298                          &runtime->GetApexVersions());
3299   const std::string image_location = layout.GetPrimaryImageLocation();
3300   std::unique_ptr<ImageHeader> image_header;
3301   std::string error_msg;
3302 
3303   std::string system_filename;
3304   bool has_system = false;
3305 
3306   if (FindImageFilename(image_location.c_str(),
3307                         image_isa,
3308                         &system_filename,
3309                         &has_system)) {
3310     DCHECK(has_system);
3311     image_header = ReadSpecificImageHeader(system_filename.c_str(), &error_msg);
3312   }
3313 
3314   return image_header != nullptr;
3315 }
3316 
LoadBootImage(const std::vector<std::string> & boot_class_path,const std::vector<std::string> & boot_class_path_locations,ArrayRef<File> boot_class_path_files,ArrayRef<File> boot_class_path_image_files,ArrayRef<File> boot_class_path_vdex_files,ArrayRef<File> boot_class_path_odex_files,const std::vector<std::string> & image_locations,const InstructionSet image_isa,bool relocate,bool executable,size_t extra_reservation_size,bool allow_in_memory_compilation,const std::string & apex_versions,std::vector<std::unique_ptr<ImageSpace>> * boot_image_spaces,MemMap * extra_reservation)3317 bool ImageSpace::LoadBootImage(const std::vector<std::string>& boot_class_path,
3318                                const std::vector<std::string>& boot_class_path_locations,
3319                                ArrayRef<File> boot_class_path_files,
3320                                ArrayRef<File> boot_class_path_image_files,
3321                                ArrayRef<File> boot_class_path_vdex_files,
3322                                ArrayRef<File> boot_class_path_odex_files,
3323                                const std::vector<std::string>& image_locations,
3324                                const InstructionSet image_isa,
3325                                bool relocate,
3326                                bool executable,
3327                                size_t extra_reservation_size,
3328                                bool allow_in_memory_compilation,
3329                                const std::string& apex_versions,
3330                                /*out*/ std::vector<std::unique_ptr<ImageSpace>>* boot_image_spaces,
3331                                /*out*/ MemMap* extra_reservation) {
3332   ScopedTrace trace(__FUNCTION__);
3333 
3334   DCHECK(boot_image_spaces != nullptr);
3335   DCHECK(boot_image_spaces->empty());
3336   DCHECK_ALIGNED(extra_reservation_size, kElfSegmentAlignment);
3337   DCHECK(extra_reservation != nullptr);
3338   DCHECK_NE(image_isa, InstructionSet::kNone);
3339 
3340   if (image_locations.empty()) {
3341     return false;
3342   }
3343 
3344   BootImageLoader loader(boot_class_path,
3345                          boot_class_path_locations,
3346                          boot_class_path_files,
3347                          boot_class_path_image_files,
3348                          boot_class_path_vdex_files,
3349                          boot_class_path_odex_files,
3350                          image_locations,
3351                          image_isa,
3352                          relocate,
3353                          executable,
3354                          &apex_versions);
3355   loader.FindImageFiles();
3356 
3357   std::string error_msg;
3358   if (loader.LoadFromSystem(extra_reservation_size,
3359                             allow_in_memory_compilation,
3360                             boot_image_spaces,
3361                             extra_reservation,
3362                             &error_msg)) {
3363     return true;
3364   }
3365   LOG(ERROR) << "Could not create image space with image file '"
3366              << Join(image_locations, kComponentSeparator)
3367              << "'. Attempting to fall back to imageless running. Error was: "
3368              << error_msg;
3369 
3370   return false;
3371 }
3372 
~ImageSpace()3373 ImageSpace::~ImageSpace() {
3374   // Everything done by member destructors. Classes forward-declared in header are now defined.
3375 }
3376 
CreateFromAppImage(const char * image,const OatFile * oat_file,std::string * error_msg)3377 std::unique_ptr<ImageSpace> ImageSpace::CreateFromAppImage(const char* image,
3378                                                            const OatFile* oat_file,
3379                                                            std::string* error_msg) {
3380   // Note: The oat file has already been validated.
3381   const std::vector<ImageSpace*>& boot_image_spaces =
3382       Runtime::Current()->GetHeap()->GetBootImageSpaces();
3383   return CreateFromAppImage(image,
3384                             oat_file,
3385                             ArrayRef<ImageSpace* const>(boot_image_spaces),
3386                             error_msg);
3387 }
3388 
CreateFromAppImage(const char * image,const OatFile * oat_file,ArrayRef<ImageSpace * const> boot_image_spaces,std::string * error_msg)3389 std::unique_ptr<ImageSpace> ImageSpace::CreateFromAppImage(
3390     const char* image,
3391     const OatFile* oat_file,
3392     ArrayRef<ImageSpace* const> boot_image_spaces,
3393     std::string* error_msg) {
3394   return Loader::InitAppImage(image,
3395                               image,
3396                               oat_file,
3397                               boot_image_spaces,
3398                               error_msg);
3399 }
3400 
GetOatFile() const3401 const OatFile* ImageSpace::GetOatFile() const {
3402   return oat_file_non_owned_;
3403 }
3404 
ReleaseOatFile()3405 std::unique_ptr<const OatFile> ImageSpace::ReleaseOatFile() {
3406   CHECK(oat_file_ != nullptr);
3407   return std::move(oat_file_);
3408 }
3409 
Dump(std::ostream & os) const3410 void ImageSpace::Dump(std::ostream& os) const {
3411   os << GetType()
3412       << " begin=" << reinterpret_cast<void*>(Begin())
3413       << ",end=" << reinterpret_cast<void*>(End())
3414       << ",size=" << PrettySize(Size())
3415       << ",name=\"" << GetName() << "\"]";
3416 }
3417 
ValidateApexVersions(const OatHeader & oat_header,const std::string & apex_versions,const std::string & file_location,std::string * error_msg)3418 bool ImageSpace::ValidateApexVersions(const OatHeader& oat_header,
3419                                       const std::string& apex_versions,
3420                                       const std::string& file_location,
3421                                       std::string* error_msg) {
3422   // For a boot image, the key value store only exists in the first OAT file. Skip other OAT files.
3423   if (oat_header.GetKeyValueStoreSize() == 0) {
3424     return true;
3425   }
3426 
3427   const char* oat_apex_versions = oat_header.GetStoreValueByKey(OatHeader::kApexVersionsKey);
3428   if (oat_apex_versions == nullptr) {
3429     *error_msg = StringPrintf("ValidateApexVersions failed to get APEX versions from oat file '%s'",
3430                               file_location.c_str());
3431     return false;
3432   }
3433   // For a boot image, it can be generated from a subset of the bootclasspath.
3434   // For an app image, some dex files get compiled with a subset of the bootclasspath.
3435   // For such cases, the OAT APEX versions will be a prefix of the runtime APEX versions.
3436   if (!apex_versions.starts_with(oat_apex_versions)) {
3437     *error_msg = StringPrintf(
3438         "ValidateApexVersions found APEX versions mismatch between oat file '%s' and the runtime "
3439         "(Oat file: '%s', Runtime: '%s')",
3440         file_location.c_str(),
3441         oat_apex_versions,
3442         apex_versions.c_str());
3443     return false;
3444   }
3445   return true;
3446 }
3447 
ValidateOatFile(const OatFile & oat_file,std::string * error_msg)3448 bool ImageSpace::ValidateOatFile(const OatFile& oat_file, std::string* error_msg) {
3449   DCHECK(Runtime::Current() != nullptr);
3450   return ValidateOatFile(oat_file, error_msg, {}, {}, Runtime::Current()->GetApexVersions());
3451 }
3452 
ValidateOatFile(const OatFile & oat_file,std::string * error_msg,ArrayRef<const std::string> dex_filenames,ArrayRef<File> dex_files,const std::string & apex_versions)3453 bool ImageSpace::ValidateOatFile(const OatFile& oat_file,
3454                                  std::string* error_msg,
3455                                  ArrayRef<const std::string> dex_filenames,
3456                                  ArrayRef<File> dex_files,
3457                                  const std::string& apex_versions) {
3458   if (!ValidateApexVersions(oat_file.GetOatHeader(),
3459                             apex_versions,
3460                             oat_file.GetLocation(),
3461                             error_msg)) {
3462     return false;
3463   }
3464 
3465   // For a boot image, the key value store only exists in the first OAT file. Skip other OAT files.
3466   if (oat_file.GetOatHeader().GetKeyValueStoreSize() != 0 &&
3467       oat_file.GetOatHeader().IsConcurrentCopying() != gUseReadBarrier) {
3468     *error_msg =
3469         ART_FORMAT("ValidateOatFile found read barrier state mismatch (oat file: {}, runtime: {})",
3470                    oat_file.GetOatHeader().IsConcurrentCopying(),
3471                    gUseReadBarrier);
3472     return false;
3473   }
3474 
3475   size_t dex_file_index = 0;  // Counts only primary dex files.
3476   const std::vector<const OatDexFile*>& oat_dex_files = oat_file.GetOatDexFiles();
3477   for (size_t i = 0; i < oat_dex_files.size();) {
3478     DCHECK(dex_filenames.empty() || dex_file_index < dex_filenames.size());
3479     const std::string& dex_file_location = dex_filenames.empty() ?
3480                                                oat_dex_files[i]->GetDexFileLocation() :
3481                                                dex_filenames[dex_file_index];
3482     File no_file;  // Invalid object.
3483     File& dex_file = dex_file_index < dex_files.size() ? dex_files[dex_file_index] : no_file;
3484     dex_file_index++;
3485 
3486     if (DexFileLoader::IsMultiDexLocation(oat_dex_files[i]->GetDexFileLocation())) {
3487       return false;  // Expected primary dex file.
3488     }
3489     uint32_t oat_checksum = DexFileLoader::GetMultiDexChecksum(oat_dex_files, &i);
3490 
3491     // Original checksum.
3492     std::optional<uint32_t> dex_checksum;
3493     ArtDexFileLoader dex_loader(&dex_file, dex_file_location);
3494     bool ok = dex_loader.GetMultiDexChecksum(&dex_checksum, error_msg);
3495     if (!ok) {
3496       *error_msg = StringPrintf(
3497           "ValidateOatFile failed to get checksum of dex file '%s' "
3498           "referenced by oat file %s: %s",
3499           dex_file_location.c_str(),
3500           oat_file.GetLocation().c_str(),
3501           error_msg->c_str());
3502       return false;
3503     }
3504     CHECK(dex_checksum.has_value());
3505 
3506     if (oat_checksum != dex_checksum) {
3507       *error_msg = StringPrintf(
3508           "ValidateOatFile found checksum mismatch between oat file "
3509           "'%s' and dex file '%s' (0x%x != 0x%x)",
3510           oat_file.GetLocation().c_str(),
3511           dex_file_location.c_str(),
3512           oat_checksum,
3513           dex_checksum.value());
3514       return false;
3515     }
3516   }
3517   return true;
3518 }
3519 
GetBootClassPathChecksums(ArrayRef<ImageSpace * const> image_spaces,ArrayRef<const DexFile * const> boot_class_path)3520 std::string ImageSpace::GetBootClassPathChecksums(
3521     ArrayRef<ImageSpace* const> image_spaces,
3522     ArrayRef<const DexFile* const> boot_class_path) {
3523   DCHECK(!boot_class_path.empty());
3524   size_t bcp_pos = 0u;
3525   std::string boot_image_checksum;
3526 
3527   for (size_t image_pos = 0u, size = image_spaces.size(); image_pos != size; ) {
3528     const ImageSpace* main_space = image_spaces[image_pos];
3529     // Caller must make sure that the image spaces correspond to the head of the BCP.
3530     DCHECK_NE(main_space->oat_file_non_owned_->GetOatDexFiles().size(), 0u);
3531     DCHECK_EQ(main_space->oat_file_non_owned_->GetOatDexFiles()[0]->GetDexFileLocation(),
3532               boot_class_path[bcp_pos]->GetLocation());
3533     const ImageHeader& current_header = main_space->GetImageHeader();
3534     uint32_t image_space_count = current_header.GetImageSpaceCount();
3535     DCHECK_NE(image_space_count, 0u);
3536     DCHECK_LE(image_space_count, image_spaces.size() - image_pos);
3537     if (image_pos != 0u) {
3538       boot_image_checksum += ':';
3539     }
3540     uint32_t component_count = current_header.GetComponentCount();
3541     AppendImageChecksum(component_count, current_header.GetImageChecksum(), &boot_image_checksum);
3542     for (size_t space_index = 0; space_index != image_space_count; ++space_index) {
3543       const ImageSpace* space = image_spaces[image_pos + space_index];
3544       const OatFile* oat_file = space->oat_file_non_owned_;
3545       size_t num_dex_files = oat_file->GetOatDexFiles().size();
3546       if (kIsDebugBuild) {
3547         CHECK_NE(num_dex_files, 0u);
3548         CHECK_LE(oat_file->GetOatDexFiles().size(), boot_class_path.size() - bcp_pos);
3549         for (size_t i = 0; i != num_dex_files; ++i) {
3550           CHECK_EQ(oat_file->GetOatDexFiles()[i]->GetDexFileLocation(),
3551                    boot_class_path[bcp_pos + i]->GetLocation());
3552         }
3553       }
3554       bcp_pos += num_dex_files;
3555     }
3556     image_pos += image_space_count;
3557   }
3558 
3559   ArrayRef<const DexFile* const> boot_class_path_tail =
3560       ArrayRef<const DexFile* const>(boot_class_path).SubArray(bcp_pos);
3561   DCHECK(boot_class_path_tail.empty() ||
3562          !DexFileLoader::IsMultiDexLocation(boot_class_path_tail.front()->GetLocation()));
3563   for (size_t i = 0; i < boot_class_path_tail.size();) {
3564     uint32_t checksum = DexFileLoader::GetMultiDexChecksum(boot_class_path_tail, &i);
3565     if (!boot_image_checksum.empty()) {
3566       boot_image_checksum += ':';
3567     }
3568     boot_image_checksum += kDexFileChecksumPrefix;
3569     StringAppendF(&boot_image_checksum, "/%08x", checksum);
3570   }
3571   return boot_image_checksum;
3572 }
3573 
GetNumberOfComponents(ArrayRef<ImageSpace * const> image_spaces)3574 size_t ImageSpace::GetNumberOfComponents(ArrayRef<ImageSpace* const> image_spaces) {
3575   size_t n = 0;
3576   for (auto&& is : image_spaces) {
3577     n += is->GetComponentCount();
3578   }
3579   return n;
3580 }
3581 
CheckAndCountBCPComponents(std::string_view oat_boot_class_path,ArrayRef<const std::string> boot_class_path,std::string * error_msg)3582 size_t ImageSpace::CheckAndCountBCPComponents(std::string_view oat_boot_class_path,
3583                                          ArrayRef<const std::string> boot_class_path,
3584                                          /*out*/std::string* error_msg) {
3585   // Check that the oat BCP is a prefix of current BCP locations and count components.
3586   size_t component_count = 0u;
3587   std::string_view remaining_bcp(oat_boot_class_path);
3588   bool bcp_ok = false;
3589   for (const std::string& location : boot_class_path) {
3590     if (!remaining_bcp.starts_with(location)) {
3591       break;
3592     }
3593     remaining_bcp.remove_prefix(location.size());
3594     ++component_count;
3595     if (remaining_bcp.empty()) {
3596       bcp_ok = true;
3597       break;
3598     }
3599     if (!remaining_bcp.starts_with(":")) {
3600       break;
3601     }
3602     remaining_bcp.remove_prefix(1u);
3603   }
3604   if (!bcp_ok) {
3605     *error_msg = StringPrintf("Oat boot class path (%s) is not a prefix of"
3606                               " runtime boot class path (%s)",
3607                               std::string(oat_boot_class_path).c_str(),
3608                               Join(boot_class_path, ':').c_str());
3609     return static_cast<size_t>(-1);
3610   }
3611   return component_count;
3612 }
3613 
VerifyBootClassPathChecksums(std::string_view oat_checksums,std::string_view oat_boot_class_path,ArrayRef<const std::unique_ptr<ImageSpace>> image_spaces,ArrayRef<const std::string> boot_class_path_locations,ArrayRef<const std::string> boot_class_path,std::string * error_msg)3614 bool ImageSpace::VerifyBootClassPathChecksums(
3615     std::string_view oat_checksums,
3616     std::string_view oat_boot_class_path,
3617     ArrayRef<const std::unique_ptr<ImageSpace>> image_spaces,
3618     ArrayRef<const std::string> boot_class_path_locations,
3619     ArrayRef<const std::string> boot_class_path,
3620     /*out*/std::string* error_msg) {
3621   DCHECK_EQ(boot_class_path.size(), boot_class_path_locations.size());
3622   DCHECK_GE(boot_class_path_locations.size(), image_spaces.size());
3623   if (oat_checksums.empty() || oat_boot_class_path.empty()) {
3624     *error_msg = oat_checksums.empty() ? "Empty checksums." : "Empty boot class path.";
3625     return false;
3626   }
3627 
3628   size_t oat_bcp_size =
3629       CheckAndCountBCPComponents(oat_boot_class_path, boot_class_path_locations, error_msg);
3630   if (oat_bcp_size == static_cast<size_t>(-1)) {
3631     DCHECK(!error_msg->empty());
3632     return false;
3633   }
3634   const size_t num_image_spaces = image_spaces.size();
3635   size_t dependency_component_count = 0;
3636   for (const std::unique_ptr<ImageSpace>& space : image_spaces) {
3637     dependency_component_count += space->GetComponentCount();
3638   }
3639   if (dependency_component_count != oat_bcp_size) {
3640     *error_msg = StringPrintf("Image header records %s dependencies (%zu) than BCP (%zu)",
3641                               dependency_component_count < oat_bcp_size ? "less" : "more",
3642                               dependency_component_count,
3643                               oat_bcp_size);
3644     return false;
3645   }
3646 
3647   // Verify image checksums.
3648   size_t bcp_pos = 0u;
3649   size_t image_pos = 0u;
3650   while (image_pos != num_image_spaces && oat_checksums.starts_with("i")) {
3651     // Verify the current image checksum.
3652     const ImageHeader& current_header = image_spaces[image_pos]->GetImageHeader();
3653     uint32_t image_space_count = current_header.GetImageSpaceCount();
3654     DCHECK_NE(image_space_count, 0u);
3655     DCHECK_LE(image_space_count, image_spaces.size() - image_pos);
3656     uint32_t component_count = current_header.GetComponentCount();
3657     uint32_t checksum = current_header.GetImageChecksum();
3658     if (!CheckAndRemoveImageChecksum(component_count, checksum, &oat_checksums, error_msg)) {
3659       DCHECK(!error_msg->empty());
3660       return false;
3661     }
3662 
3663     if (kIsDebugBuild) {
3664       for (size_t space_index = 0; space_index != image_space_count; ++space_index) {
3665         const OatFile* oat_file = image_spaces[image_pos + space_index]->oat_file_non_owned_;
3666         size_t num_dex_files = oat_file->GetOatDexFiles().size();
3667         CHECK_NE(num_dex_files, 0u);
3668         const std::string main_location = oat_file->GetOatDexFiles()[0]->GetDexFileLocation();
3669         CHECK_EQ(main_location, boot_class_path_locations[bcp_pos + space_index]);
3670         CHECK(!DexFileLoader::IsMultiDexLocation(main_location));
3671         size_t num_base_locations = 1u;
3672         for (size_t i = 1u; i != num_dex_files; ++i) {
3673           if (!DexFileLoader::IsMultiDexLocation(
3674                   oat_file->GetOatDexFiles()[i]->GetDexFileLocation())) {
3675             CHECK_EQ(image_space_count, 1u);  // We can find base locations only for --single-image.
3676             ++num_base_locations;
3677           }
3678         }
3679         if (image_space_count == 1u) {
3680           CHECK_EQ(num_base_locations, component_count);
3681         }
3682       }
3683     }
3684 
3685     image_pos += image_space_count;
3686     bcp_pos += component_count;
3687 
3688     if (!oat_checksums.starts_with(":")) {
3689       // Check that we've reached the end of checksums and BCP.
3690       if (!oat_checksums.empty()) {
3691          *error_msg = StringPrintf("Expected ':' separator or end of checksums, remaining %s.",
3692                                    std::string(oat_checksums).c_str());
3693          return false;
3694       }
3695       if (bcp_pos != oat_bcp_size) {
3696         *error_msg = StringPrintf("Component count mismatch between checksums (%zu) and BCP (%zu)",
3697                                   bcp_pos,
3698                                   oat_bcp_size);
3699         return false;
3700       }
3701       return true;
3702     }
3703     oat_checksums.remove_prefix(1u);
3704   }
3705 
3706   // We do not allow dependencies of extensions on dex files. That would require
3707   // interleaving the loading of the images with opening the other BCP dex files.
3708   return false;
3709 }
3710 
ExpandMultiImageLocations(ArrayRef<const std::string> dex_locations,const std::string & image_location,bool boot_image_extension)3711 std::vector<std::string> ImageSpace::ExpandMultiImageLocations(
3712     ArrayRef<const std::string> dex_locations,
3713     const std::string& image_location,
3714     bool boot_image_extension) {
3715   DCHECK(!dex_locations.empty());
3716 
3717   // Find the path.
3718   size_t last_slash = image_location.rfind('/');
3719   CHECK_NE(last_slash, std::string::npos);
3720 
3721   // We also need to honor path components that were encoded through '@'. Otherwise the loading
3722   // code won't be able to find the images.
3723   if (image_location.find('@', last_slash) != std::string::npos) {
3724     last_slash = image_location.rfind('@');
3725   }
3726 
3727   // Find the dot separating the primary image name from the extension.
3728   size_t last_dot = image_location.rfind('.');
3729   // Extract the extension and base (the path and primary image name).
3730   std::string extension;
3731   std::string base = image_location;
3732   if (last_dot != std::string::npos && last_dot > last_slash) {
3733     extension = image_location.substr(last_dot);  // Including the dot.
3734     base.resize(last_dot);
3735   }
3736   // For non-empty primary image name, add '-' to the `base`.
3737   if (last_slash + 1u != base.size()) {
3738     base += '-';
3739   }
3740 
3741   std::vector<std::string> locations;
3742   locations.reserve(dex_locations.size());
3743   size_t start_index = 0u;
3744   if (!boot_image_extension) {
3745     start_index = 1u;
3746     locations.push_back(image_location);
3747   }
3748 
3749   // Now create the other names. Use a counted loop to skip the first one if needed.
3750   for (size_t i = start_index; i < dex_locations.size(); ++i) {
3751     // Replace path with `base` (i.e. image path and prefix) and replace the original
3752     // extension (if any) with `extension`.
3753     std::string name = dex_locations[i];
3754     size_t last_dex_slash = name.rfind('/');
3755     if (last_dex_slash != std::string::npos) {
3756       name = name.substr(last_dex_slash + 1);
3757     }
3758     size_t last_dex_dot = name.rfind('.');
3759     if (last_dex_dot != std::string::npos) {
3760       name.resize(last_dex_dot);
3761     }
3762     locations.push_back(ART_FORMAT("{}{}{}", base, name, extension));
3763   }
3764   return locations;
3765 }
3766 
DumpSections(std::ostream & os) const3767 void ImageSpace::DumpSections(std::ostream& os) const {
3768   const uint8_t* base = Begin();
3769   const ImageHeader& header = GetImageHeader();
3770   for (size_t i = 0; i < ImageHeader::kSectionCount; ++i) {
3771     auto section_type = static_cast<ImageHeader::ImageSections>(i);
3772     const ImageSection& section = header.GetImageSection(section_type);
3773     os << section_type << " " << reinterpret_cast<const void*>(base + section.Offset())
3774        << "-" << reinterpret_cast<const void*>(base + section.End()) << "\n";
3775   }
3776 }
3777 
ReleaseMetadata()3778 void ImageSpace::ReleaseMetadata() {
3779   const ImageSection& metadata = GetImageHeader().GetMetadataSection();
3780   VLOG(image) << "Releasing " << metadata.Size() << " image metadata bytes";
3781   // Avoid using ZeroAndReleasePages since the zero fill might not be word atomic.
3782   uint8_t* const page_begin = AlignUp(Begin() + metadata.Offset(), gPageSize);
3783   uint8_t* const page_end = AlignDown(Begin() + metadata.End(), gPageSize);
3784   if (page_begin < page_end) {
3785     CHECK_NE(madvise(page_begin, page_end - page_begin, MADV_DONTNEED), -1) << "madvise failed";
3786   }
3787 }
3788 
3789 }  // namespace space
3790 }  // namespace gc
3791 }  // namespace art
3792