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