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