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