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 <lz4.h>
20#include <sys/statvfs.h>
21#include <sys/types.h>
22#include <unistd.h>
23
24#include <random>
25
26#include "android-base/stringprintf.h"
27#include "android-base/strings.h"
28
29#include "art_field-inl.h"
30#include "art_method-inl.h"
31#include "base/callee_save_type.h"
32#include "base/enums.h"
33#include "base/file_utils.h"
34#include "base/macros.h"
35#include "base/os.h"
36#include "base/scoped_flock.h"
37#include "base/stl_util.h"
38#include "base/systrace.h"
39#include "base/time_utils.h"
40#include "base/utils.h"
41#include "dex/art_dex_file_loader.h"
42#include "dex/dex_file_loader.h"
43#include "exec_utils.h"
44#include "gc/accounting/space_bitmap-inl.h"
45#include "image-inl.h"
46#include "image_space_fs.h"
47#include "mirror/class-inl.h"
48#include "mirror/object-inl.h"
49#include "mirror/object-refvisitor-inl.h"
50#include "oat_file.h"
51#include "runtime.h"
52#include "space-inl.h"
53
54namespace art {
55namespace gc {
56namespace space {
57
58using android::base::StringAppendF;
59using android::base::StringPrintf;
60
61Atomic<uint32_t> ImageSpace::bitmap_index_(0);
62
63ImageSpace::ImageSpace(const std::string& image_filename,
64                       const char* image_location,
65                       MemMap* mem_map,
66                       accounting::ContinuousSpaceBitmap* live_bitmap,
67                       uint8_t* end)
68    : MemMapSpace(image_filename,
69                  mem_map,
70                  mem_map->Begin(),
71                  end,
72                  end,
73                  kGcRetentionPolicyNeverCollect),
74      oat_file_non_owned_(nullptr),
75      image_location_(image_location) {
76  DCHECK(live_bitmap != nullptr);
77  live_bitmap_.reset(live_bitmap);
78}
79
80static int32_t ChooseRelocationOffsetDelta(int32_t min_delta, int32_t max_delta) {
81  CHECK_ALIGNED(min_delta, kPageSize);
82  CHECK_ALIGNED(max_delta, kPageSize);
83  CHECK_LT(min_delta, max_delta);
84
85  int32_t r = GetRandomNumber<int32_t>(min_delta, max_delta);
86  if (r % 2 == 0) {
87    r = RoundUp(r, kPageSize);
88  } else {
89    r = RoundDown(r, kPageSize);
90  }
91  CHECK_LE(min_delta, r);
92  CHECK_GE(max_delta, r);
93  CHECK_ALIGNED(r, kPageSize);
94  return r;
95}
96
97static int32_t ChooseRelocationOffsetDelta() {
98  return ChooseRelocationOffsetDelta(ART_BASE_ADDRESS_MIN_DELTA, ART_BASE_ADDRESS_MAX_DELTA);
99}
100
101static bool GenerateImage(const std::string& image_filename,
102                          InstructionSet image_isa,
103                          std::string* error_msg) {
104  const std::string boot_class_path_string(Runtime::Current()->GetBootClassPathString());
105  std::vector<std::string> boot_class_path;
106  Split(boot_class_path_string, ':', &boot_class_path);
107  if (boot_class_path.empty()) {
108    *error_msg = "Failed to generate image because no boot class path specified";
109    return false;
110  }
111  // We should clean up so we are more likely to have room for the image.
112  if (Runtime::Current()->IsZygote()) {
113    LOG(INFO) << "Pruning dalvik-cache since we are generating an image and will need to recompile";
114    PruneDalvikCache(image_isa);
115  }
116
117  std::vector<std::string> arg_vector;
118
119  std::string dex2oat(Runtime::Current()->GetCompilerExecutable());
120  arg_vector.push_back(dex2oat);
121
122  std::string image_option_string("--image=");
123  image_option_string += image_filename;
124  arg_vector.push_back(image_option_string);
125
126  for (size_t i = 0; i < boot_class_path.size(); i++) {
127    arg_vector.push_back(std::string("--dex-file=") + boot_class_path[i]);
128  }
129
130  std::string oat_file_option_string("--oat-file=");
131  oat_file_option_string += ImageHeader::GetOatLocationFromImageLocation(image_filename);
132  arg_vector.push_back(oat_file_option_string);
133
134  // Note: we do not generate a fully debuggable boot image so we do not pass the
135  // compiler flag --debuggable here.
136
137  Runtime::Current()->AddCurrentRuntimeFeaturesAsDex2OatArguments(&arg_vector);
138  CHECK_EQ(image_isa, kRuntimeISA)
139      << "We should always be generating an image for the current isa.";
140
141  int32_t base_offset = ChooseRelocationOffsetDelta();
142  LOG(INFO) << "Using an offset of 0x" << std::hex << base_offset << " from default "
143            << "art base address of 0x" << std::hex << ART_BASE_ADDRESS;
144  arg_vector.push_back(StringPrintf("--base=0x%x", ART_BASE_ADDRESS + base_offset));
145
146  if (!kIsTargetBuild) {
147    arg_vector.push_back("--host");
148  }
149
150  const std::vector<std::string>& compiler_options = Runtime::Current()->GetImageCompilerOptions();
151  for (size_t i = 0; i < compiler_options.size(); ++i) {
152    arg_vector.push_back(compiler_options[i].c_str());
153  }
154
155  std::string command_line(android::base::Join(arg_vector, ' '));
156  LOG(INFO) << "GenerateImage: " << command_line;
157  return Exec(arg_vector, error_msg);
158}
159
160static bool FindImageFilenameImpl(const char* image_location,
161                                  const InstructionSet image_isa,
162                                  bool* has_system,
163                                  std::string* system_filename,
164                                  bool* dalvik_cache_exists,
165                                  std::string* dalvik_cache,
166                                  bool* is_global_cache,
167                                  bool* has_cache,
168                                  std::string* cache_filename) {
169  DCHECK(dalvik_cache != nullptr);
170
171  *has_system = false;
172  *has_cache = false;
173  // image_location = /system/framework/boot.art
174  // system_image_location = /system/framework/<image_isa>/boot.art
175  std::string system_image_filename(GetSystemImageFilename(image_location, image_isa));
176  if (OS::FileExists(system_image_filename.c_str())) {
177    *system_filename = system_image_filename;
178    *has_system = true;
179  }
180
181  bool have_android_data = false;
182  *dalvik_cache_exists = false;
183  GetDalvikCache(GetInstructionSetString(image_isa),
184                 true,
185                 dalvik_cache,
186                 &have_android_data,
187                 dalvik_cache_exists,
188                 is_global_cache);
189
190  if (have_android_data && *dalvik_cache_exists) {
191    // Always set output location even if it does not exist,
192    // so that the caller knows where to create the image.
193    //
194    // image_location = /system/framework/boot.art
195    // *image_filename = /data/dalvik-cache/<image_isa>/boot.art
196    std::string error_msg;
197    if (!GetDalvikCacheFilename(image_location,
198                                dalvik_cache->c_str(),
199                                cache_filename,
200                                &error_msg)) {
201      LOG(WARNING) << error_msg;
202      return *has_system;
203    }
204    *has_cache = OS::FileExists(cache_filename->c_str());
205  }
206  return *has_system || *has_cache;
207}
208
209bool ImageSpace::FindImageFilename(const char* image_location,
210                                   const InstructionSet image_isa,
211                                   std::string* system_filename,
212                                   bool* has_system,
213                                   std::string* cache_filename,
214                                   bool* dalvik_cache_exists,
215                                   bool* has_cache,
216                                   bool* is_global_cache) {
217  std::string dalvik_cache_unused;
218  return FindImageFilenameImpl(image_location,
219                               image_isa,
220                               has_system,
221                               system_filename,
222                               dalvik_cache_exists,
223                               &dalvik_cache_unused,
224                               is_global_cache,
225                               has_cache,
226                               cache_filename);
227}
228
229static bool ReadSpecificImageHeader(const char* filename, ImageHeader* image_header) {
230    std::unique_ptr<File> image_file(OS::OpenFileForReading(filename));
231    if (image_file.get() == nullptr) {
232      return false;
233    }
234    const bool success = image_file->ReadFully(image_header, sizeof(ImageHeader));
235    if (!success || !image_header->IsValid()) {
236      return false;
237    }
238    return true;
239}
240
241// Relocate the image at image_location to dest_filename and relocate it by a random amount.
242static bool RelocateImage(const char* image_location,
243                          const char* dest_directory,
244                          InstructionSet isa,
245                          std::string* error_msg) {
246  // We should clean up so we are more likely to have room for the image.
247  if (Runtime::Current()->IsZygote()) {
248    LOG(INFO) << "Pruning dalvik-cache since we are relocating an image and will need to recompile";
249    PruneDalvikCache(isa);
250  }
251
252  std::string patchoat(Runtime::Current()->GetPatchoatExecutable());
253
254  std::string input_image_location_arg("--input-image-location=");
255  input_image_location_arg += image_location;
256
257  std::string output_image_directory_arg("--output-image-directory=");
258  output_image_directory_arg += dest_directory;
259
260  std::string instruction_set_arg("--instruction-set=");
261  instruction_set_arg += GetInstructionSetString(isa);
262
263  std::string base_offset_arg("--base-offset-delta=");
264  StringAppendF(&base_offset_arg, "%d", ChooseRelocationOffsetDelta());
265
266  std::vector<std::string> argv;
267  argv.push_back(patchoat);
268
269  argv.push_back(input_image_location_arg);
270  argv.push_back(output_image_directory_arg);
271
272  argv.push_back(instruction_set_arg);
273  argv.push_back(base_offset_arg);
274
275  std::string command_line(android::base::Join(argv, ' '));
276  LOG(INFO) << "RelocateImage: " << command_line;
277  return Exec(argv, error_msg);
278}
279
280static bool VerifyImage(const char* image_location,
281                        const char* dest_directory,
282                        InstructionSet isa,
283                        std::string* error_msg) {
284  std::string patchoat(Runtime::Current()->GetPatchoatExecutable());
285
286  std::string input_image_location_arg("--input-image-location=");
287  input_image_location_arg += image_location;
288
289  std::string output_image_directory_arg("--output-image-directory=");
290  output_image_directory_arg += dest_directory;
291
292  std::string instruction_set_arg("--instruction-set=");
293  instruction_set_arg += GetInstructionSetString(isa);
294
295  std::vector<std::string> argv;
296  argv.push_back(patchoat);
297
298  argv.push_back(input_image_location_arg);
299  argv.push_back(output_image_directory_arg);
300
301  argv.push_back(instruction_set_arg);
302
303  argv.push_back("--verify");
304
305  std::string command_line(android::base::Join(argv, ' '));
306  LOG(INFO) << "VerifyImage: " << command_line;
307  return Exec(argv, error_msg);
308}
309
310static ImageHeader* ReadSpecificImageHeader(const char* filename, std::string* error_msg) {
311  std::unique_ptr<ImageHeader> hdr(new ImageHeader);
312  if (!ReadSpecificImageHeader(filename, hdr.get())) {
313    *error_msg = StringPrintf("Unable to read image header for %s", filename);
314    return nullptr;
315  }
316  return hdr.release();
317}
318
319ImageHeader* ImageSpace::ReadImageHeader(const char* image_location,
320                                         const InstructionSet image_isa,
321                                         std::string* error_msg) {
322  std::string system_filename;
323  bool has_system = false;
324  std::string cache_filename;
325  bool has_cache = false;
326  bool dalvik_cache_exists = false;
327  bool is_global_cache = false;
328  if (FindImageFilename(image_location, image_isa, &system_filename, &has_system,
329                        &cache_filename, &dalvik_cache_exists, &has_cache, &is_global_cache)) {
330    if (Runtime::Current()->ShouldRelocate()) {
331      if (has_system && has_cache) {
332        std::unique_ptr<ImageHeader> sys_hdr(new ImageHeader);
333        std::unique_ptr<ImageHeader> cache_hdr(new ImageHeader);
334        if (!ReadSpecificImageHeader(system_filename.c_str(), sys_hdr.get())) {
335          *error_msg = StringPrintf("Unable to read image header for %s at %s",
336                                    image_location, system_filename.c_str());
337          return nullptr;
338        }
339        if (!ReadSpecificImageHeader(cache_filename.c_str(), cache_hdr.get())) {
340          *error_msg = StringPrintf("Unable to read image header for %s at %s",
341                                    image_location, cache_filename.c_str());
342          return nullptr;
343        }
344        if (sys_hdr->GetOatChecksum() != cache_hdr->GetOatChecksum()) {
345          *error_msg = StringPrintf("Unable to find a relocated version of image file %s",
346                                    image_location);
347          return nullptr;
348        }
349        return cache_hdr.release();
350      } else if (!has_cache) {
351        *error_msg = StringPrintf("Unable to find a relocated version of image file %s",
352                                  image_location);
353        return nullptr;
354      } else if (!has_system && has_cache) {
355        // This can probably just use the cache one.
356        return ReadSpecificImageHeader(cache_filename.c_str(), error_msg);
357      }
358    } else {
359      // We don't want to relocate, Just pick the appropriate one if we have it and return.
360      if (has_system && has_cache) {
361        // We want the cache if the checksum matches, otherwise the system.
362        std::unique_ptr<ImageHeader> system(ReadSpecificImageHeader(system_filename.c_str(),
363                                                                    error_msg));
364        std::unique_ptr<ImageHeader> cache(ReadSpecificImageHeader(cache_filename.c_str(),
365                                                                   error_msg));
366        if (system.get() == nullptr ||
367            (cache.get() != nullptr && cache->GetOatChecksum() == system->GetOatChecksum())) {
368          return cache.release();
369        } else {
370          return system.release();
371        }
372      } else if (has_system) {
373        return ReadSpecificImageHeader(system_filename.c_str(), error_msg);
374      } else if (has_cache) {
375        return ReadSpecificImageHeader(cache_filename.c_str(), error_msg);
376      }
377    }
378  }
379
380  *error_msg = StringPrintf("Unable to find image file for %s", image_location);
381  return nullptr;
382}
383
384static bool ChecksumsMatch(const char* image_a, const char* image_b, std::string* error_msg) {
385  DCHECK(error_msg != nullptr);
386
387  ImageHeader hdr_a;
388  ImageHeader hdr_b;
389
390  if (!ReadSpecificImageHeader(image_a, &hdr_a)) {
391    *error_msg = StringPrintf("Cannot read header of %s", image_a);
392    return false;
393  }
394  if (!ReadSpecificImageHeader(image_b, &hdr_b)) {
395    *error_msg = StringPrintf("Cannot read header of %s", image_b);
396    return false;
397  }
398
399  if (hdr_a.GetOatChecksum() != hdr_b.GetOatChecksum()) {
400    *error_msg = StringPrintf("Checksum mismatch: %u(%s) vs %u(%s)",
401                              hdr_a.GetOatChecksum(),
402                              image_a,
403                              hdr_b.GetOatChecksum(),
404                              image_b);
405    return false;
406  }
407
408  return true;
409}
410
411static bool CanWriteToDalvikCache(const InstructionSet isa) {
412  const std::string dalvik_cache = GetDalvikCache(GetInstructionSetString(isa));
413  if (access(dalvik_cache.c_str(), O_RDWR) == 0) {
414    return true;
415  } else if (errno != EACCES) {
416    PLOG(WARNING) << "CanWriteToDalvikCache returned error other than EACCES";
417  }
418  return false;
419}
420
421static bool ImageCreationAllowed(bool is_global_cache,
422                                 const InstructionSet isa,
423                                 std::string* error_msg) {
424  // Anyone can write into a "local" cache.
425  if (!is_global_cache) {
426    return true;
427  }
428
429  // Only the zygote running as root is allowed to create the global boot image.
430  // If the zygote is running as non-root (and cannot write to the dalvik-cache),
431  // then image creation is not allowed..
432  if (Runtime::Current()->IsZygote()) {
433    return CanWriteToDalvikCache(isa);
434  }
435
436  *error_msg = "Only the zygote can create the global boot image.";
437  return false;
438}
439
440void ImageSpace::VerifyImageAllocations() {
441  uint8_t* current = Begin() + RoundUp(sizeof(ImageHeader), kObjectAlignment);
442  while (current < End()) {
443    CHECK_ALIGNED(current, kObjectAlignment);
444    auto* obj = reinterpret_cast<mirror::Object*>(current);
445    CHECK(obj->GetClass() != nullptr) << "Image object at address " << obj << " has null class";
446    CHECK(live_bitmap_->Test(obj)) << obj->PrettyTypeOf();
447    if (kUseBakerReadBarrier) {
448      obj->AssertReadBarrierState();
449    }
450    current += RoundUp(obj->SizeOf(), kObjectAlignment);
451  }
452}
453
454// Helper class for relocating from one range of memory to another.
455class RelocationRange {
456 public:
457  RelocationRange() = default;
458  RelocationRange(const RelocationRange&) = default;
459  RelocationRange(uintptr_t source, uintptr_t dest, uintptr_t length)
460      : source_(source),
461        dest_(dest),
462        length_(length) {}
463
464  bool InSource(uintptr_t address) const {
465    return address - source_ < length_;
466  }
467
468  bool InDest(uintptr_t address) const {
469    return address - dest_ < length_;
470  }
471
472  // Translate a source address to the destination space.
473  uintptr_t ToDest(uintptr_t address) const {
474    DCHECK(InSource(address));
475    return address + Delta();
476  }
477
478  // Returns the delta between the dest from the source.
479  uintptr_t Delta() const {
480    return dest_ - source_;
481  }
482
483  uintptr_t Source() const {
484    return source_;
485  }
486
487  uintptr_t Dest() const {
488    return dest_;
489  }
490
491  uintptr_t Length() const {
492    return length_;
493  }
494
495 private:
496  const uintptr_t source_;
497  const uintptr_t dest_;
498  const uintptr_t length_;
499};
500
501std::ostream& operator<<(std::ostream& os, const RelocationRange& reloc) {
502  return os << "(" << reinterpret_cast<const void*>(reloc.Source()) << "-"
503            << reinterpret_cast<const void*>(reloc.Source() + reloc.Length()) << ")->("
504            << reinterpret_cast<const void*>(reloc.Dest()) << "-"
505            << reinterpret_cast<const void*>(reloc.Dest() + reloc.Length()) << ")";
506}
507
508// Helper class encapsulating loading, so we can access private ImageSpace members (this is a
509// friend class), but not declare functions in the header.
510class ImageSpaceLoader {
511 public:
512  static std::unique_ptr<ImageSpace> Load(const char* image_location,
513                                          const std::string& image_filename,
514                                          bool is_zygote,
515                                          bool is_global_cache,
516                                          bool validate_oat_file,
517                                          std::string* error_msg)
518      REQUIRES_SHARED(Locks::mutator_lock_) {
519    // Should this be a RDWR lock? This is only a defensive measure, as at
520    // this point the image should exist.
521    // However, only the zygote can write into the global dalvik-cache, so
522    // restrict to zygote processes, or any process that isn't using
523    // /data/dalvik-cache (which we assume to be allowed to write there).
524    const bool rw_lock = is_zygote || !is_global_cache;
525
526    // Note that we must not use the file descriptor associated with
527    // ScopedFlock::GetFile to Init the image file. We want the file
528    // descriptor (and the associated exclusive lock) to be released when
529    // we leave Create.
530    ScopedFlock image = LockedFile::Open(image_filename.c_str(),
531                                         rw_lock ? (O_CREAT | O_RDWR) : O_RDONLY /* flags */,
532                                         true /* block */,
533                                         error_msg);
534
535    VLOG(startup) << "Using image file " << image_filename.c_str() << " for image location "
536                  << image_location;
537    // If we are in /system we can assume the image is good. We can also
538    // assume this if we are using a relocated image (i.e. image checksum
539    // matches) since this is only different by the offset. We need this to
540    // make sure that host tests continue to work.
541    // Since we are the boot image, pass null since we load the oat file from the boot image oat
542    // file name.
543    return Init(image_filename.c_str(),
544                image_location,
545                validate_oat_file,
546                /* oat_file */nullptr,
547                error_msg);
548  }
549
550  static std::unique_ptr<ImageSpace> Init(const char* image_filename,
551                                          const char* image_location,
552                                          bool validate_oat_file,
553                                          const OatFile* oat_file,
554                                          std::string* error_msg)
555      REQUIRES_SHARED(Locks::mutator_lock_) {
556    CHECK(image_filename != nullptr);
557    CHECK(image_location != nullptr);
558
559    TimingLogger logger(__PRETTY_FUNCTION__, true, VLOG_IS_ON(image));
560    VLOG(image) << "ImageSpace::Init entering image_filename=" << image_filename;
561
562    std::unique_ptr<File> file;
563    {
564      TimingLogger::ScopedTiming timing("OpenImageFile", &logger);
565      file.reset(OS::OpenFileForReading(image_filename));
566      if (file == nullptr) {
567        *error_msg = StringPrintf("Failed to open '%s'", image_filename);
568        return nullptr;
569      }
570    }
571    ImageHeader temp_image_header;
572    ImageHeader* image_header = &temp_image_header;
573    {
574      TimingLogger::ScopedTiming timing("ReadImageHeader", &logger);
575      bool success = file->ReadFully(image_header, sizeof(*image_header));
576      if (!success || !image_header->IsValid()) {
577        *error_msg = StringPrintf("Invalid image header in '%s'", image_filename);
578        return nullptr;
579      }
580    }
581    // Check that the file is larger or equal to the header size + data size.
582    const uint64_t image_file_size = static_cast<uint64_t>(file->GetLength());
583    if (image_file_size < sizeof(ImageHeader) + image_header->GetDataSize()) {
584      *error_msg = StringPrintf("Image file truncated: %" PRIu64 " vs. %" PRIu64 ".",
585                                image_file_size,
586                                sizeof(ImageHeader) + image_header->GetDataSize());
587      return nullptr;
588    }
589
590    if (oat_file != nullptr) {
591      // If we have an oat file, check the oat file checksum. The oat file is only non-null for the
592      // app image case. Otherwise, we open the oat file after the image and check the checksum there.
593      const uint32_t oat_checksum = oat_file->GetOatHeader().GetChecksum();
594      const uint32_t image_oat_checksum = image_header->GetOatChecksum();
595      if (oat_checksum != image_oat_checksum) {
596        *error_msg = StringPrintf("Oat checksum 0x%x does not match the image one 0x%x in image %s",
597                                  oat_checksum,
598                                  image_oat_checksum,
599                                  image_filename);
600        return nullptr;
601      }
602    }
603
604    if (VLOG_IS_ON(startup)) {
605      LOG(INFO) << "Dumping image sections";
606      for (size_t i = 0; i < ImageHeader::kSectionCount; ++i) {
607        const auto section_idx = static_cast<ImageHeader::ImageSections>(i);
608        auto& section = image_header->GetImageSection(section_idx);
609        LOG(INFO) << section_idx << " start="
610            << reinterpret_cast<void*>(image_header->GetImageBegin() + section.Offset()) << " "
611            << section;
612      }
613    }
614
615    const auto& bitmap_section = image_header->GetImageBitmapSection();
616    // The location we want to map from is the first aligned page after the end of the stored
617    // (possibly compressed) data.
618    const size_t image_bitmap_offset = RoundUp(sizeof(ImageHeader) + image_header->GetDataSize(),
619                                               kPageSize);
620    const size_t end_of_bitmap = image_bitmap_offset + bitmap_section.Size();
621    if (end_of_bitmap != image_file_size) {
622      *error_msg = StringPrintf(
623          "Image file size does not equal end of bitmap: size=%" PRIu64 " vs. %zu.", image_file_size,
624          end_of_bitmap);
625      return nullptr;
626    }
627
628    std::unique_ptr<MemMap> map;
629
630    // GetImageBegin is the preferred address to map the image. If we manage to map the
631    // image at the image begin, the amount of fixup work required is minimized.
632    // If it is pic we will retry with error_msg for the failure case. Pass a null error_msg to
633    // avoid reading proc maps for a mapping failure and slowing everything down.
634    map.reset(LoadImageFile(image_filename,
635                            image_location,
636                            *image_header,
637                            image_header->GetImageBegin(),
638                            file->Fd(),
639                            logger,
640                            image_header->IsPic() ? nullptr : error_msg));
641    // If the header specifies PIC mode, we can also map at a random low_4gb address since we can
642    // relocate in-place.
643    if (map == nullptr && image_header->IsPic()) {
644      map.reset(LoadImageFile(image_filename,
645                              image_location,
646                              *image_header,
647                              /* address */ nullptr,
648                              file->Fd(),
649                              logger,
650                              error_msg));
651    }
652    // Were we able to load something and continue?
653    if (map == nullptr) {
654      DCHECK(!error_msg->empty());
655      return nullptr;
656    }
657    DCHECK_EQ(0, memcmp(image_header, map->Begin(), sizeof(ImageHeader)));
658
659    std::unique_ptr<MemMap> image_bitmap_map(MemMap::MapFileAtAddress(nullptr,
660                                                                      bitmap_section.Size(),
661                                                                      PROT_READ, MAP_PRIVATE,
662                                                                      file->Fd(),
663                                                                      image_bitmap_offset,
664                                                                      /*low_4gb*/false,
665                                                                      /*reuse*/false,
666                                                                      image_filename,
667                                                                      error_msg));
668    if (image_bitmap_map == nullptr) {
669      *error_msg = StringPrintf("Failed to map image bitmap: %s", error_msg->c_str());
670      return nullptr;
671    }
672    // Loaded the map, use the image header from the file now in case we patch it with
673    // RelocateInPlace.
674    image_header = reinterpret_cast<ImageHeader*>(map->Begin());
675    const uint32_t bitmap_index = ImageSpace::bitmap_index_.FetchAndAddSequentiallyConsistent(1);
676    std::string bitmap_name(StringPrintf("imagespace %s live-bitmap %u",
677                                         image_filename,
678                                         bitmap_index));
679    // Bitmap only needs to cover until the end of the mirror objects section.
680    const ImageSection& image_objects = image_header->GetObjectsSection();
681    // We only want the mirror object, not the ArtFields and ArtMethods.
682    uint8_t* const image_end = map->Begin() + image_objects.End();
683    std::unique_ptr<accounting::ContinuousSpaceBitmap> bitmap;
684    {
685      TimingLogger::ScopedTiming timing("CreateImageBitmap", &logger);
686      bitmap.reset(
687          accounting::ContinuousSpaceBitmap::CreateFromMemMap(
688              bitmap_name,
689              image_bitmap_map.release(),
690              reinterpret_cast<uint8_t*>(map->Begin()),
691              // Make sure the bitmap is aligned to card size instead of just bitmap word size.
692              RoundUp(image_objects.End(), gc::accounting::CardTable::kCardSize)));
693      if (bitmap == nullptr) {
694        *error_msg = StringPrintf("Could not create bitmap '%s'", bitmap_name.c_str());
695        return nullptr;
696      }
697    }
698    {
699      TimingLogger::ScopedTiming timing("RelocateImage", &logger);
700      if (!RelocateInPlace(*image_header,
701                           map->Begin(),
702                           bitmap.get(),
703                           oat_file,
704                           error_msg)) {
705        return nullptr;
706      }
707    }
708    // We only want the mirror object, not the ArtFields and ArtMethods.
709    std::unique_ptr<ImageSpace> space(new ImageSpace(image_filename,
710                                                     image_location,
711                                                     map.release(),
712                                                     bitmap.release(),
713                                                     image_end));
714
715    // VerifyImageAllocations() will be called later in Runtime::Init()
716    // as some class roots like ArtMethod::java_lang_reflect_ArtMethod_
717    // and ArtField::java_lang_reflect_ArtField_, which are used from
718    // Object::SizeOf() which VerifyImageAllocations() calls, are not
719    // set yet at this point.
720    if (oat_file == nullptr) {
721      TimingLogger::ScopedTiming timing("OpenOatFile", &logger);
722      space->oat_file_ = OpenOatFile(*space, image_filename, error_msg);
723      if (space->oat_file_ == nullptr) {
724        DCHECK(!error_msg->empty());
725        return nullptr;
726      }
727      space->oat_file_non_owned_ = space->oat_file_.get();
728    } else {
729      space->oat_file_non_owned_ = oat_file;
730    }
731
732    if (validate_oat_file) {
733      TimingLogger::ScopedTiming timing("ValidateOatFile", &logger);
734      CHECK(space->oat_file_ != nullptr);
735      if (!ImageSpace::ValidateOatFile(*space->oat_file_, error_msg)) {
736        DCHECK(!error_msg->empty());
737        return nullptr;
738      }
739    }
740
741    Runtime* runtime = Runtime::Current();
742
743    // If oat_file is null, then it is the boot image space. Use oat_file_non_owned_ from the space
744    // to set the runtime methods.
745    CHECK_EQ(oat_file != nullptr, image_header->IsAppImage());
746    if (image_header->IsAppImage()) {
747      CHECK_EQ(runtime->GetResolutionMethod(),
748               image_header->GetImageMethod(ImageHeader::kResolutionMethod));
749      CHECK_EQ(runtime->GetImtConflictMethod(),
750               image_header->GetImageMethod(ImageHeader::kImtConflictMethod));
751      CHECK_EQ(runtime->GetImtUnimplementedMethod(),
752               image_header->GetImageMethod(ImageHeader::kImtUnimplementedMethod));
753      CHECK_EQ(runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveAllCalleeSaves),
754               image_header->GetImageMethod(ImageHeader::kSaveAllCalleeSavesMethod));
755      CHECK_EQ(runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveRefsOnly),
756               image_header->GetImageMethod(ImageHeader::kSaveRefsOnlyMethod));
757      CHECK_EQ(runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveRefsAndArgs),
758               image_header->GetImageMethod(ImageHeader::kSaveRefsAndArgsMethod));
759      CHECK_EQ(runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveEverything),
760               image_header->GetImageMethod(ImageHeader::kSaveEverythingMethod));
761      CHECK_EQ(runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveEverythingForClinit),
762               image_header->GetImageMethod(ImageHeader::kSaveEverythingMethodForClinit));
763      CHECK_EQ(runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveEverythingForSuspendCheck),
764               image_header->GetImageMethod(ImageHeader::kSaveEverythingMethodForSuspendCheck));
765    } else if (!runtime->HasResolutionMethod()) {
766      runtime->SetInstructionSet(space->oat_file_non_owned_->GetOatHeader().GetInstructionSet());
767      runtime->SetResolutionMethod(image_header->GetImageMethod(ImageHeader::kResolutionMethod));
768      runtime->SetImtConflictMethod(image_header->GetImageMethod(ImageHeader::kImtConflictMethod));
769      runtime->SetImtUnimplementedMethod(
770          image_header->GetImageMethod(ImageHeader::kImtUnimplementedMethod));
771      runtime->SetCalleeSaveMethod(
772          image_header->GetImageMethod(ImageHeader::kSaveAllCalleeSavesMethod),
773          CalleeSaveType::kSaveAllCalleeSaves);
774      runtime->SetCalleeSaveMethod(
775          image_header->GetImageMethod(ImageHeader::kSaveRefsOnlyMethod),
776          CalleeSaveType::kSaveRefsOnly);
777      runtime->SetCalleeSaveMethod(
778          image_header->GetImageMethod(ImageHeader::kSaveRefsAndArgsMethod),
779          CalleeSaveType::kSaveRefsAndArgs);
780      runtime->SetCalleeSaveMethod(
781          image_header->GetImageMethod(ImageHeader::kSaveEverythingMethod),
782          CalleeSaveType::kSaveEverything);
783      runtime->SetCalleeSaveMethod(
784          image_header->GetImageMethod(ImageHeader::kSaveEverythingMethodForClinit),
785          CalleeSaveType::kSaveEverythingForClinit);
786      runtime->SetCalleeSaveMethod(
787          image_header->GetImageMethod(ImageHeader::kSaveEverythingMethodForSuspendCheck),
788          CalleeSaveType::kSaveEverythingForSuspendCheck);
789    }
790
791    VLOG(image) << "ImageSpace::Init exiting " << *space.get();
792    if (VLOG_IS_ON(image)) {
793      logger.Dump(LOG_STREAM(INFO));
794    }
795    return space;
796  }
797
798 private:
799  static MemMap* LoadImageFile(const char* image_filename,
800                               const char* image_location,
801                               const ImageHeader& image_header,
802                               uint8_t* address,
803                               int fd,
804                               TimingLogger& logger,
805                               std::string* error_msg) {
806    TimingLogger::ScopedTiming timing("MapImageFile", &logger);
807    const ImageHeader::StorageMode storage_mode = image_header.GetStorageMode();
808    if (storage_mode == ImageHeader::kStorageModeUncompressed) {
809      return MemMap::MapFileAtAddress(address,
810                                      image_header.GetImageSize(),
811                                      PROT_READ | PROT_WRITE,
812                                      MAP_PRIVATE,
813                                      fd,
814                                      0,
815                                      /*low_4gb*/true,
816                                      /*reuse*/false,
817                                      image_filename,
818                                      error_msg);
819    }
820
821    if (storage_mode != ImageHeader::kStorageModeLZ4 &&
822        storage_mode != ImageHeader::kStorageModeLZ4HC) {
823      if (error_msg != nullptr) {
824        *error_msg = StringPrintf("Invalid storage mode in image header %d",
825                                  static_cast<int>(storage_mode));
826      }
827      return nullptr;
828    }
829
830    // Reserve output and decompress into it.
831    std::unique_ptr<MemMap> map(MemMap::MapAnonymous(image_location,
832                                                     address,
833                                                     image_header.GetImageSize(),
834                                                     PROT_READ | PROT_WRITE,
835                                                     /*low_4gb*/true,
836                                                     /*reuse*/false,
837                                                     error_msg));
838    if (map != nullptr) {
839      const size_t stored_size = image_header.GetDataSize();
840      const size_t decompress_offset = sizeof(ImageHeader);  // Skip the header.
841      std::unique_ptr<MemMap> temp_map(MemMap::MapFile(sizeof(ImageHeader) + stored_size,
842                                                       PROT_READ,
843                                                       MAP_PRIVATE,
844                                                       fd,
845                                                       /*offset*/0,
846                                                       /*low_4gb*/false,
847                                                       image_filename,
848                                                       error_msg));
849      if (temp_map == nullptr) {
850        DCHECK(error_msg == nullptr || !error_msg->empty());
851        return nullptr;
852      }
853      memcpy(map->Begin(), &image_header, sizeof(ImageHeader));
854      const uint64_t start = NanoTime();
855      // LZ4HC and LZ4 have same internal format, both use LZ4_decompress.
856      TimingLogger::ScopedTiming timing2("LZ4 decompress image", &logger);
857      const size_t decompressed_size = LZ4_decompress_safe(
858          reinterpret_cast<char*>(temp_map->Begin()) + sizeof(ImageHeader),
859          reinterpret_cast<char*>(map->Begin()) + decompress_offset,
860          stored_size,
861          map->Size() - decompress_offset);
862      const uint64_t time = NanoTime() - start;
863      // Add one 1 ns to prevent possible divide by 0.
864      VLOG(image) << "Decompressing image took " << PrettyDuration(time) << " ("
865                  << PrettySize(static_cast<uint64_t>(map->Size()) * MsToNs(1000) / (time + 1))
866                  << "/s)";
867      if (decompressed_size + sizeof(ImageHeader) != image_header.GetImageSize()) {
868        if (error_msg != nullptr) {
869          *error_msg = StringPrintf(
870              "Decompressed size does not match expected image size %zu vs %zu",
871              decompressed_size + sizeof(ImageHeader),
872              image_header.GetImageSize());
873        }
874        return nullptr;
875      }
876    }
877
878    return map.release();
879  }
880
881  class FixupVisitor : public ValueObject {
882   public:
883    FixupVisitor(const RelocationRange& boot_image,
884                 const RelocationRange& boot_oat,
885                 const RelocationRange& app_image,
886                 const RelocationRange& app_oat)
887        : boot_image_(boot_image),
888          boot_oat_(boot_oat),
889          app_image_(app_image),
890          app_oat_(app_oat) {}
891
892    // Return the relocated address of a heap object.
893    template <typename T>
894    ALWAYS_INLINE T* ForwardObject(T* src) const {
895      const uintptr_t uint_src = reinterpret_cast<uintptr_t>(src);
896      if (boot_image_.InSource(uint_src)) {
897        return reinterpret_cast<T*>(boot_image_.ToDest(uint_src));
898      }
899      if (app_image_.InSource(uint_src)) {
900        return reinterpret_cast<T*>(app_image_.ToDest(uint_src));
901      }
902      // Since we are fixing up the app image, there should only be pointers to the app image and
903      // boot image.
904      DCHECK(src == nullptr) << reinterpret_cast<const void*>(src);
905      return src;
906    }
907
908    // Return the relocated address of a code pointer (contained by an oat file).
909    ALWAYS_INLINE const void* ForwardCode(const void* src) const {
910      const uintptr_t uint_src = reinterpret_cast<uintptr_t>(src);
911      if (boot_oat_.InSource(uint_src)) {
912        return reinterpret_cast<const void*>(boot_oat_.ToDest(uint_src));
913      }
914      if (app_oat_.InSource(uint_src)) {
915        return reinterpret_cast<const void*>(app_oat_.ToDest(uint_src));
916      }
917      DCHECK(src == nullptr) << src;
918      return src;
919    }
920
921    // Must be called on pointers that already have been relocated to the destination relocation.
922    ALWAYS_INLINE bool IsInAppImage(mirror::Object* object) const {
923      return app_image_.InDest(reinterpret_cast<uintptr_t>(object));
924    }
925
926   protected:
927    // Source section.
928    const RelocationRange boot_image_;
929    const RelocationRange boot_oat_;
930    const RelocationRange app_image_;
931    const RelocationRange app_oat_;
932  };
933
934  // Adapt for mirror::Class::FixupNativePointers.
935  class FixupObjectAdapter : public FixupVisitor {
936   public:
937    template<typename... Args>
938    explicit FixupObjectAdapter(Args... args) : FixupVisitor(args...) {}
939
940    template <typename T>
941    T* operator()(T* obj, void** dest_addr ATTRIBUTE_UNUSED = nullptr) const {
942      return ForwardObject(obj);
943    }
944  };
945
946  class FixupRootVisitor : public FixupVisitor {
947   public:
948    template<typename... Args>
949    explicit FixupRootVisitor(Args... args) : FixupVisitor(args...) {}
950
951    ALWAYS_INLINE void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
952        REQUIRES_SHARED(Locks::mutator_lock_) {
953      if (!root->IsNull()) {
954        VisitRoot(root);
955      }
956    }
957
958    ALWAYS_INLINE void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
959        REQUIRES_SHARED(Locks::mutator_lock_) {
960      mirror::Object* ref = root->AsMirrorPtr();
961      mirror::Object* new_ref = ForwardObject(ref);
962      if (ref != new_ref) {
963        root->Assign(new_ref);
964      }
965    }
966  };
967
968  class FixupObjectVisitor : public FixupVisitor {
969   public:
970    template<typename... Args>
971    explicit FixupObjectVisitor(gc::accounting::ContinuousSpaceBitmap* visited,
972                                const PointerSize pointer_size,
973                                Args... args)
974        : FixupVisitor(args...),
975          pointer_size_(pointer_size),
976          visited_(visited) {}
977
978    // Fix up separately since we also need to fix up method entrypoints.
979    ALWAYS_INLINE void VisitRootIfNonNull(
980        mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const {}
981
982    ALWAYS_INLINE void VisitRoot(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED)
983        const {}
984
985    ALWAYS_INLINE void operator()(ObjPtr<mirror::Object> obj,
986                                  MemberOffset offset,
987                                  bool is_static ATTRIBUTE_UNUSED) const
988        NO_THREAD_SAFETY_ANALYSIS {
989      // There could be overlap between ranges, we must avoid visiting the same reference twice.
990      // Avoid the class field since we already fixed it up in FixupClassVisitor.
991      if (offset.Uint32Value() != mirror::Object::ClassOffset().Uint32Value()) {
992        // Space is not yet added to the heap, don't do a read barrier.
993        mirror::Object* ref = obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(
994            offset);
995        // Use SetFieldObjectWithoutWriteBarrier to avoid card marking since we are writing to the
996        // image.
997        obj->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(offset, ForwardObject(ref));
998      }
999    }
1000
1001    // Visit a pointer array and forward corresponding native data. Ignores pointer arrays in the
1002    // boot image. Uses the bitmap to ensure the same array is not visited multiple times.
1003    template <typename Visitor>
1004    void UpdatePointerArrayContents(mirror::PointerArray* array, const Visitor& visitor) const
1005        NO_THREAD_SAFETY_ANALYSIS {
1006      DCHECK(array != nullptr);
1007      DCHECK(visitor.IsInAppImage(array));
1008      // The bit for the array contents is different than the bit for the array. Since we may have
1009      // already visited the array as a long / int array from walking the bitmap without knowing it
1010      // was a pointer array.
1011      static_assert(kObjectAlignment == 8u, "array bit may be in another object");
1012      mirror::Object* const contents_bit = reinterpret_cast<mirror::Object*>(
1013          reinterpret_cast<uintptr_t>(array) + kObjectAlignment);
1014      // If the bit is not set then the contents have not yet been updated.
1015      if (!visited_->Test(contents_bit)) {
1016        array->Fixup<kVerifyNone, kWithoutReadBarrier>(array, pointer_size_, visitor);
1017        visited_->Set(contents_bit);
1018      }
1019    }
1020
1021    // java.lang.ref.Reference visitor.
1022    void operator()(ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
1023                    ObjPtr<mirror::Reference> ref) const
1024        REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
1025      mirror::Object* obj = ref->GetReferent<kWithoutReadBarrier>();
1026      ref->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
1027          mirror::Reference::ReferentOffset(),
1028          ForwardObject(obj));
1029    }
1030
1031    void operator()(mirror::Object* obj) const
1032        NO_THREAD_SAFETY_ANALYSIS {
1033      if (visited_->Test(obj)) {
1034        // Already visited.
1035        return;
1036      }
1037      visited_->Set(obj);
1038
1039      // Handle class specially first since we need it to be updated to properly visit the rest of
1040      // the instance fields.
1041      {
1042        mirror::Class* klass = obj->GetClass<kVerifyNone, kWithoutReadBarrier>();
1043        DCHECK(klass != nullptr) << "Null class in image";
1044        // No AsClass since our fields aren't quite fixed up yet.
1045        mirror::Class* new_klass = down_cast<mirror::Class*>(ForwardObject(klass));
1046        if (klass != new_klass) {
1047          obj->SetClass<kVerifyNone>(new_klass);
1048        }
1049        if (new_klass != klass && IsInAppImage(new_klass)) {
1050          // Make sure the klass contents are fixed up since we depend on it to walk the fields.
1051          operator()(new_klass);
1052        }
1053      }
1054
1055      if (obj->IsClass()) {
1056        mirror::Class* klass = obj->AsClass<kVerifyNone, kWithoutReadBarrier>();
1057        // Fixup super class before visiting instance fields which require
1058        // information from their super class to calculate offsets.
1059        mirror::Class* super_class = klass->GetSuperClass<kVerifyNone, kWithoutReadBarrier>();
1060        if (super_class != nullptr) {
1061          mirror::Class* new_super_class = down_cast<mirror::Class*>(ForwardObject(super_class));
1062          if (new_super_class != super_class && IsInAppImage(new_super_class)) {
1063            // Recursively fix all dependencies.
1064            operator()(new_super_class);
1065          }
1066        }
1067      }
1068
1069      obj->VisitReferences</*visit native roots*/false, kVerifyNone, kWithoutReadBarrier>(
1070          *this,
1071          *this);
1072      // Note that this code relies on no circular dependencies.
1073      // We want to use our own class loader and not the one in the image.
1074      if (obj->IsClass<kVerifyNone, kWithoutReadBarrier>()) {
1075        mirror::Class* as_klass = obj->AsClass<kVerifyNone, kWithoutReadBarrier>();
1076        FixupObjectAdapter visitor(boot_image_, boot_oat_, app_image_, app_oat_);
1077        as_klass->FixupNativePointers<kVerifyNone, kWithoutReadBarrier>(as_klass,
1078                                                                        pointer_size_,
1079                                                                        visitor);
1080        // Deal with the pointer arrays. Use the helper function since multiple classes can reference
1081        // the same arrays.
1082        mirror::PointerArray* const vtable = as_klass->GetVTable<kVerifyNone, kWithoutReadBarrier>();
1083        if (vtable != nullptr && IsInAppImage(vtable)) {
1084          operator()(vtable);
1085          UpdatePointerArrayContents(vtable, visitor);
1086        }
1087        mirror::IfTable* iftable = as_klass->GetIfTable<kVerifyNone, kWithoutReadBarrier>();
1088        // Ensure iftable arrays are fixed up since we need GetMethodArray to return the valid
1089        // contents.
1090        if (IsInAppImage(iftable)) {
1091          operator()(iftable);
1092          for (int32_t i = 0, count = iftable->Count(); i < count; ++i) {
1093            if (iftable->GetMethodArrayCount<kVerifyNone, kWithoutReadBarrier>(i) > 0) {
1094              mirror::PointerArray* methods =
1095                  iftable->GetMethodArray<kVerifyNone, kWithoutReadBarrier>(i);
1096              if (visitor.IsInAppImage(methods)) {
1097                operator()(methods);
1098                DCHECK(methods != nullptr);
1099                UpdatePointerArrayContents(methods, visitor);
1100              }
1101            }
1102          }
1103        }
1104      }
1105    }
1106
1107   private:
1108    const PointerSize pointer_size_;
1109    gc::accounting::ContinuousSpaceBitmap* const visited_;
1110  };
1111
1112  class ForwardObjectAdapter {
1113   public:
1114    ALWAYS_INLINE explicit ForwardObjectAdapter(const FixupVisitor* visitor) : visitor_(visitor) {}
1115
1116    template <typename T>
1117    ALWAYS_INLINE T* operator()(T* src) const {
1118      return visitor_->ForwardObject(src);
1119    }
1120
1121   private:
1122    const FixupVisitor* const visitor_;
1123  };
1124
1125  class ForwardCodeAdapter {
1126   public:
1127    ALWAYS_INLINE explicit ForwardCodeAdapter(const FixupVisitor* visitor)
1128        : visitor_(visitor) {}
1129
1130    template <typename T>
1131    ALWAYS_INLINE T* operator()(T* src) const {
1132      return visitor_->ForwardCode(src);
1133    }
1134
1135   private:
1136    const FixupVisitor* const visitor_;
1137  };
1138
1139  class FixupArtMethodVisitor : public FixupVisitor, public ArtMethodVisitor {
1140   public:
1141    template<typename... Args>
1142    explicit FixupArtMethodVisitor(bool fixup_heap_objects, PointerSize pointer_size, Args... args)
1143        : FixupVisitor(args...),
1144          fixup_heap_objects_(fixup_heap_objects),
1145          pointer_size_(pointer_size) {}
1146
1147    virtual void Visit(ArtMethod* method) NO_THREAD_SAFETY_ANALYSIS {
1148      // TODO: Separate visitor for runtime vs normal methods.
1149      if (UNLIKELY(method->IsRuntimeMethod())) {
1150        ImtConflictTable* table = method->GetImtConflictTable(pointer_size_);
1151        if (table != nullptr) {
1152          ImtConflictTable* new_table = ForwardObject(table);
1153          if (table != new_table) {
1154            method->SetImtConflictTable(new_table, pointer_size_);
1155          }
1156        }
1157        const void* old_code = method->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size_);
1158        const void* new_code = ForwardCode(old_code);
1159        if (old_code != new_code) {
1160          method->SetEntryPointFromQuickCompiledCodePtrSize(new_code, pointer_size_);
1161        }
1162      } else {
1163        if (fixup_heap_objects_) {
1164          method->UpdateObjectsForImageRelocation(ForwardObjectAdapter(this));
1165        }
1166        method->UpdateEntrypoints<kWithoutReadBarrier>(ForwardCodeAdapter(this), pointer_size_);
1167      }
1168    }
1169
1170   private:
1171    const bool fixup_heap_objects_;
1172    const PointerSize pointer_size_;
1173  };
1174
1175  class FixupArtFieldVisitor : public FixupVisitor, public ArtFieldVisitor {
1176   public:
1177    template<typename... Args>
1178    explicit FixupArtFieldVisitor(Args... args) : FixupVisitor(args...) {}
1179
1180    virtual void Visit(ArtField* field) NO_THREAD_SAFETY_ANALYSIS {
1181      field->UpdateObjects(ForwardObjectAdapter(this));
1182    }
1183  };
1184
1185  // Relocate an image space mapped at target_base which possibly used to be at a different base
1186  // address. Only needs a single image space, not one for both source and destination.
1187  // In place means modifying a single ImageSpace in place rather than relocating from one ImageSpace
1188  // to another.
1189  static bool RelocateInPlace(ImageHeader& image_header,
1190                              uint8_t* target_base,
1191                              accounting::ContinuousSpaceBitmap* bitmap,
1192                              const OatFile* app_oat_file,
1193                              std::string* error_msg) {
1194    DCHECK(error_msg != nullptr);
1195    if (!image_header.IsPic()) {
1196      if (image_header.GetImageBegin() == target_base) {
1197        return true;
1198      }
1199      *error_msg = StringPrintf("Cannot relocate non-pic image for oat file %s",
1200                                (app_oat_file != nullptr) ? app_oat_file->GetLocation().c_str() : "");
1201      return false;
1202    }
1203    // Set up sections.
1204    uint32_t boot_image_begin = 0;
1205    uint32_t boot_image_end = 0;
1206    uint32_t boot_oat_begin = 0;
1207    uint32_t boot_oat_end = 0;
1208    const PointerSize pointer_size = image_header.GetPointerSize();
1209    gc::Heap* const heap = Runtime::Current()->GetHeap();
1210    heap->GetBootImagesSize(&boot_image_begin, &boot_image_end, &boot_oat_begin, &boot_oat_end);
1211    if (boot_image_begin == boot_image_end) {
1212      *error_msg = "Can not relocate app image without boot image space";
1213      return false;
1214    }
1215    if (boot_oat_begin == boot_oat_end) {
1216      *error_msg = "Can not relocate app image without boot oat file";
1217      return false;
1218    }
1219    const uint32_t boot_image_size = boot_image_end - boot_image_begin;
1220    const uint32_t boot_oat_size = boot_oat_end - boot_oat_begin;
1221    const uint32_t image_header_boot_image_size = image_header.GetBootImageSize();
1222    const uint32_t image_header_boot_oat_size = image_header.GetBootOatSize();
1223    if (boot_image_size != image_header_boot_image_size) {
1224      *error_msg = StringPrintf("Boot image size %" PRIu64 " does not match expected size %"
1225                                    PRIu64,
1226                                static_cast<uint64_t>(boot_image_size),
1227                                static_cast<uint64_t>(image_header_boot_image_size));
1228      return false;
1229    }
1230    if (boot_oat_size != image_header_boot_oat_size) {
1231      *error_msg = StringPrintf("Boot oat size %" PRIu64 " does not match expected size %"
1232                                    PRIu64,
1233                                static_cast<uint64_t>(boot_oat_size),
1234                                static_cast<uint64_t>(image_header_boot_oat_size));
1235      return false;
1236    }
1237    TimingLogger logger(__FUNCTION__, true, false);
1238    RelocationRange boot_image(image_header.GetBootImageBegin(),
1239                               boot_image_begin,
1240                               boot_image_size);
1241    RelocationRange boot_oat(image_header.GetBootOatBegin(),
1242                             boot_oat_begin,
1243                             boot_oat_size);
1244    RelocationRange app_image(reinterpret_cast<uintptr_t>(image_header.GetImageBegin()),
1245                              reinterpret_cast<uintptr_t>(target_base),
1246                              image_header.GetImageSize());
1247    // Use the oat data section since this is where the OatFile::Begin is.
1248    RelocationRange app_oat(reinterpret_cast<uintptr_t>(image_header.GetOatDataBegin()),
1249                            // Not necessarily in low 4GB.
1250                            reinterpret_cast<uintptr_t>(app_oat_file->Begin()),
1251                            image_header.GetOatDataEnd() - image_header.GetOatDataBegin());
1252    VLOG(image) << "App image " << app_image;
1253    VLOG(image) << "App oat " << app_oat;
1254    VLOG(image) << "Boot image " << boot_image;
1255    VLOG(image) << "Boot oat " << boot_oat;
1256    // True if we need to fixup any heap pointers, otherwise only code pointers.
1257    const bool fixup_image = boot_image.Delta() != 0 || app_image.Delta() != 0;
1258    const bool fixup_code = boot_oat.Delta() != 0 || app_oat.Delta() != 0;
1259    if (!fixup_image && !fixup_code) {
1260      // Nothing to fix up.
1261      return true;
1262    }
1263    ScopedDebugDisallowReadBarriers sddrb(Thread::Current());
1264    // Need to update the image to be at the target base.
1265    const ImageSection& objects_section = image_header.GetObjectsSection();
1266    uintptr_t objects_begin = reinterpret_cast<uintptr_t>(target_base + objects_section.Offset());
1267    uintptr_t objects_end = reinterpret_cast<uintptr_t>(target_base + objects_section.End());
1268    FixupObjectAdapter fixup_adapter(boot_image, boot_oat, app_image, app_oat);
1269    if (fixup_image) {
1270      // Two pass approach, fix up all classes first, then fix up non class-objects.
1271      // The visited bitmap is used to ensure that pointer arrays are not forwarded twice.
1272      std::unique_ptr<gc::accounting::ContinuousSpaceBitmap> visited_bitmap(
1273          gc::accounting::ContinuousSpaceBitmap::Create("Relocate bitmap",
1274                                                        target_base,
1275                                                        image_header.GetImageSize()));
1276      FixupObjectVisitor fixup_object_visitor(visited_bitmap.get(),
1277                                              pointer_size,
1278                                              boot_image,
1279                                              boot_oat,
1280                                              app_image,
1281                                              app_oat);
1282      TimingLogger::ScopedTiming timing("Fixup classes", &logger);
1283      // Fixup objects may read fields in the boot image, use the mutator lock here for sanity. Though
1284      // its probably not required.
1285      ScopedObjectAccess soa(Thread::Current());
1286      timing.NewTiming("Fixup objects");
1287      bitmap->VisitMarkedRange(objects_begin, objects_end, fixup_object_visitor);
1288      // Fixup image roots.
1289      CHECK(app_image.InSource(reinterpret_cast<uintptr_t>(
1290          image_header.GetImageRoots<kWithoutReadBarrier>())));
1291      image_header.RelocateImageObjects(app_image.Delta());
1292      CHECK_EQ(image_header.GetImageBegin(), target_base);
1293      // Fix up dex cache DexFile pointers.
1294      auto* dex_caches = image_header.GetImageRoot<kWithoutReadBarrier>(ImageHeader::kDexCaches)->
1295          AsObjectArray<mirror::DexCache, kVerifyNone, kWithoutReadBarrier>();
1296      for (int32_t i = 0, count = dex_caches->GetLength(); i < count; ++i) {
1297        mirror::DexCache* dex_cache = dex_caches->Get<kVerifyNone, kWithoutReadBarrier>(i);
1298        // Fix up dex cache pointers.
1299        mirror::StringDexCacheType* strings = dex_cache->GetStrings();
1300        if (strings != nullptr) {
1301          mirror::StringDexCacheType* new_strings = fixup_adapter.ForwardObject(strings);
1302          if (strings != new_strings) {
1303            dex_cache->SetStrings(new_strings);
1304          }
1305          dex_cache->FixupStrings<kWithoutReadBarrier>(new_strings, fixup_adapter);
1306        }
1307        mirror::TypeDexCacheType* types = dex_cache->GetResolvedTypes();
1308        if (types != nullptr) {
1309          mirror::TypeDexCacheType* new_types = fixup_adapter.ForwardObject(types);
1310          if (types != new_types) {
1311            dex_cache->SetResolvedTypes(new_types);
1312          }
1313          dex_cache->FixupResolvedTypes<kWithoutReadBarrier>(new_types, fixup_adapter);
1314        }
1315        mirror::MethodDexCacheType* methods = dex_cache->GetResolvedMethods();
1316        if (methods != nullptr) {
1317          mirror::MethodDexCacheType* new_methods = fixup_adapter.ForwardObject(methods);
1318          if (methods != new_methods) {
1319            dex_cache->SetResolvedMethods(new_methods);
1320          }
1321          for (size_t j = 0, num = dex_cache->NumResolvedMethods(); j != num; ++j) {
1322            auto pair = mirror::DexCache::GetNativePairPtrSize(new_methods, j, pointer_size);
1323            ArtMethod* orig = pair.object;
1324            ArtMethod* copy = fixup_adapter.ForwardObject(orig);
1325            if (orig != copy) {
1326              pair.object = copy;
1327              mirror::DexCache::SetNativePairPtrSize(new_methods, j, pair, pointer_size);
1328            }
1329          }
1330        }
1331        mirror::FieldDexCacheType* fields = dex_cache->GetResolvedFields();
1332        if (fields != nullptr) {
1333          mirror::FieldDexCacheType* new_fields = fixup_adapter.ForwardObject(fields);
1334          if (fields != new_fields) {
1335            dex_cache->SetResolvedFields(new_fields);
1336          }
1337          for (size_t j = 0, num = dex_cache->NumResolvedFields(); j != num; ++j) {
1338            mirror::FieldDexCachePair orig =
1339                mirror::DexCache::GetNativePairPtrSize(new_fields, j, pointer_size);
1340            mirror::FieldDexCachePair copy(fixup_adapter.ForwardObject(orig.object), orig.index);
1341            if (orig.object != copy.object) {
1342              mirror::DexCache::SetNativePairPtrSize(new_fields, j, copy, pointer_size);
1343            }
1344          }
1345        }
1346
1347        mirror::MethodTypeDexCacheType* method_types = dex_cache->GetResolvedMethodTypes();
1348        if (method_types != nullptr) {
1349          mirror::MethodTypeDexCacheType* new_method_types =
1350              fixup_adapter.ForwardObject(method_types);
1351          if (method_types != new_method_types) {
1352            dex_cache->SetResolvedMethodTypes(new_method_types);
1353          }
1354          dex_cache->FixupResolvedMethodTypes<kWithoutReadBarrier>(new_method_types, fixup_adapter);
1355        }
1356        GcRoot<mirror::CallSite>* call_sites = dex_cache->GetResolvedCallSites();
1357        if (call_sites != nullptr) {
1358          GcRoot<mirror::CallSite>* new_call_sites = fixup_adapter.ForwardObject(call_sites);
1359          if (call_sites != new_call_sites) {
1360            dex_cache->SetResolvedCallSites(new_call_sites);
1361          }
1362          dex_cache->FixupResolvedCallSites<kWithoutReadBarrier>(new_call_sites, fixup_adapter);
1363        }
1364      }
1365    }
1366    {
1367      // Only touches objects in the app image, no need for mutator lock.
1368      TimingLogger::ScopedTiming timing("Fixup methods", &logger);
1369      FixupArtMethodVisitor method_visitor(fixup_image,
1370                                           pointer_size,
1371                                           boot_image,
1372                                           boot_oat,
1373                                           app_image,
1374                                           app_oat);
1375      image_header.VisitPackedArtMethods(&method_visitor, target_base, pointer_size);
1376    }
1377    if (fixup_image) {
1378      {
1379        // Only touches objects in the app image, no need for mutator lock.
1380        TimingLogger::ScopedTiming timing("Fixup fields", &logger);
1381        FixupArtFieldVisitor field_visitor(boot_image, boot_oat, app_image, app_oat);
1382        image_header.VisitPackedArtFields(&field_visitor, target_base);
1383      }
1384      {
1385        TimingLogger::ScopedTiming timing("Fixup imt", &logger);
1386        image_header.VisitPackedImTables(fixup_adapter, target_base, pointer_size);
1387      }
1388      {
1389        TimingLogger::ScopedTiming timing("Fixup conflict tables", &logger);
1390        image_header.VisitPackedImtConflictTables(fixup_adapter, target_base, pointer_size);
1391      }
1392      // In the app image case, the image methods are actually in the boot image.
1393      image_header.RelocateImageMethods(boot_image.Delta());
1394      const auto& class_table_section = image_header.GetClassTableSection();
1395      if (class_table_section.Size() > 0u) {
1396        // Note that we require that ReadFromMemory does not make an internal copy of the elements.
1397        // This also relies on visit roots not doing any verification which could fail after we update
1398        // the roots to be the image addresses.
1399        ScopedObjectAccess soa(Thread::Current());
1400        WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
1401        ClassTable temp_table;
1402        temp_table.ReadFromMemory(target_base + class_table_section.Offset());
1403        FixupRootVisitor root_visitor(boot_image, boot_oat, app_image, app_oat);
1404        temp_table.VisitRoots(root_visitor);
1405      }
1406    }
1407    if (VLOG_IS_ON(image)) {
1408      logger.Dump(LOG_STREAM(INFO));
1409    }
1410    return true;
1411  }
1412
1413  static std::unique_ptr<OatFile> OpenOatFile(const ImageSpace& image,
1414                                              const char* image_path,
1415                                              std::string* error_msg) {
1416    const ImageHeader& image_header = image.GetImageHeader();
1417    std::string oat_filename = ImageHeader::GetOatLocationFromImageLocation(image_path);
1418
1419    CHECK(image_header.GetOatDataBegin() != nullptr);
1420
1421    std::unique_ptr<OatFile> oat_file(OatFile::Open(/* zip_fd */ -1,
1422                                                    oat_filename,
1423                                                    oat_filename,
1424                                                    image_header.GetOatDataBegin(),
1425                                                    image_header.GetOatFileBegin(),
1426                                                    !Runtime::Current()->IsAotCompiler(),
1427                                                    /*low_4gb*/false,
1428                                                    nullptr,
1429                                                    error_msg));
1430    if (oat_file == nullptr) {
1431      *error_msg = StringPrintf("Failed to open oat file '%s' referenced from image %s: %s",
1432                                oat_filename.c_str(),
1433                                image.GetName(),
1434                                error_msg->c_str());
1435      return nullptr;
1436    }
1437    uint32_t oat_checksum = oat_file->GetOatHeader().GetChecksum();
1438    uint32_t image_oat_checksum = image_header.GetOatChecksum();
1439    if (oat_checksum != image_oat_checksum) {
1440      *error_msg = StringPrintf("Failed to match oat file checksum 0x%x to expected oat checksum 0x%x"
1441                                " in image %s",
1442                                oat_checksum,
1443                                image_oat_checksum,
1444                                image.GetName());
1445      return nullptr;
1446    }
1447    int32_t image_patch_delta = image_header.GetPatchDelta();
1448    int32_t oat_patch_delta = oat_file->GetOatHeader().GetImagePatchDelta();
1449    if (oat_patch_delta != image_patch_delta && !image_header.CompilePic()) {
1450      // We should have already relocated by this point. Bail out.
1451      *error_msg = StringPrintf("Failed to match oat file patch delta %d to expected patch delta %d "
1452                                "in image %s",
1453                                oat_patch_delta,
1454                                image_patch_delta,
1455                                image.GetName());
1456      return nullptr;
1457    }
1458
1459    return oat_file;
1460  }
1461};
1462
1463static constexpr uint64_t kLowSpaceValue = 50 * MB;
1464static constexpr uint64_t kTmpFsSentinelValue = 384 * MB;
1465
1466// Read the free space of the cache partition and make a decision whether to keep the generated
1467// image. This is to try to mitigate situations where the system might run out of space later.
1468static bool CheckSpace(const std::string& cache_filename, std::string* error_msg) {
1469  // Using statvfs vs statvfs64 because of b/18207376, and it is enough for all practical purposes.
1470  struct statvfs buf;
1471
1472  int res = TEMP_FAILURE_RETRY(statvfs(cache_filename.c_str(), &buf));
1473  if (res != 0) {
1474    // Could not stat. Conservatively tell the system to delete the image.
1475    *error_msg = "Could not stat the filesystem, assuming low-memory situation.";
1476    return false;
1477  }
1478
1479  uint64_t fs_overall_size = buf.f_bsize * static_cast<uint64_t>(buf.f_blocks);
1480  // Zygote is privileged, but other things are not. Use bavail.
1481  uint64_t fs_free_size = buf.f_bsize * static_cast<uint64_t>(buf.f_bavail);
1482
1483  // Take the overall size as an indicator for a tmpfs, which is being used for the decryption
1484  // environment. We do not want to fail quickening the boot image there, as it is beneficial
1485  // for time-to-UI.
1486  if (fs_overall_size > kTmpFsSentinelValue) {
1487    if (fs_free_size < kLowSpaceValue) {
1488      *error_msg = StringPrintf("Low-memory situation: only %4.2f megabytes available, need at "
1489                                "least %" PRIu64 ".",
1490                                static_cast<double>(fs_free_size) / MB,
1491                                kLowSpaceValue / MB);
1492      return false;
1493    }
1494  }
1495  return true;
1496}
1497
1498std::unique_ptr<ImageSpace> ImageSpace::CreateBootImage(const char* image_location,
1499                                                        const InstructionSet image_isa,
1500                                                        bool secondary_image,
1501                                                        std::string* error_msg) {
1502  ScopedTrace trace(__FUNCTION__);
1503
1504  // Step 0: Extra zygote work.
1505
1506  // Step 0.a: If we're the zygote, mark boot.
1507  const bool is_zygote = Runtime::Current()->IsZygote();
1508  if (is_zygote && !secondary_image && CanWriteToDalvikCache(image_isa)) {
1509    MarkZygoteStart(image_isa, Runtime::Current()->GetZygoteMaxFailedBoots());
1510  }
1511
1512  // Step 0.b: If we're the zygote, check for free space, and prune the cache preemptively,
1513  //           if necessary. While the runtime may be fine (it is pretty tolerant to
1514  //           out-of-disk-space situations), other parts of the platform are not.
1515  //
1516  //           The advantage of doing this proactively is that the later steps are simplified,
1517  //           i.e., we do not need to code retries.
1518  std::string system_filename;
1519  bool has_system = false;
1520  std::string cache_filename;
1521  bool has_cache = false;
1522  bool dalvik_cache_exists = false;
1523  bool is_global_cache = true;
1524  std::string dalvik_cache;
1525  bool found_image = FindImageFilenameImpl(image_location,
1526                                           image_isa,
1527                                           &has_system,
1528                                           &system_filename,
1529                                           &dalvik_cache_exists,
1530                                           &dalvik_cache,
1531                                           &is_global_cache,
1532                                           &has_cache,
1533                                           &cache_filename);
1534
1535  bool dex2oat_enabled = Runtime::Current()->IsImageDex2OatEnabled();
1536
1537  if (is_zygote && dalvik_cache_exists && !secondary_image) {
1538    // Extra checks for the zygote. These only apply when loading the first image, explained below.
1539    DCHECK(!dalvik_cache.empty());
1540    std::string local_error_msg;
1541    // All secondary images are verified when the primary image is verified.
1542    bool verified = VerifyImage(image_location, dalvik_cache.c_str(), image_isa, &local_error_msg);
1543    // If we prune for space at a secondary image, we may end up in a crash loop with the _exit
1544    // path.
1545    bool check_space = CheckSpace(dalvik_cache, &local_error_msg);
1546    if (!verified || !check_space) {
1547      // Note: it is important to only prune for space on the primary image, or we will hit the
1548      //       restart path.
1549      LOG(WARNING) << local_error_msg << " Preemptively pruning the dalvik cache.";
1550      PruneDalvikCache(image_isa);
1551
1552      // Re-evaluate the image.
1553      found_image = FindImageFilenameImpl(image_location,
1554                                          image_isa,
1555                                          &has_system,
1556                                          &system_filename,
1557                                          &dalvik_cache_exists,
1558                                          &dalvik_cache,
1559                                          &is_global_cache,
1560                                          &has_cache,
1561                                          &cache_filename);
1562    }
1563    if (!check_space) {
1564      // Disable compilation/patching - we do not want to fill up the space again.
1565      dex2oat_enabled = false;
1566    }
1567  }
1568
1569  // Collect all the errors.
1570  std::vector<std::string> error_msgs;
1571
1572  // Step 1: Check if we have an existing and relocated image.
1573
1574  // Step 1.a: Have files in system and cache. Then they need to match.
1575  if (found_image && has_system && has_cache) {
1576    std::string local_error_msg;
1577    // Check that the files are matching.
1578    if (ChecksumsMatch(system_filename.c_str(), cache_filename.c_str(), &local_error_msg)) {
1579      std::unique_ptr<ImageSpace> relocated_space =
1580          ImageSpaceLoader::Load(image_location,
1581                                 cache_filename,
1582                                 is_zygote,
1583                                 is_global_cache,
1584                                 /* validate_oat_file */ false,
1585                                 &local_error_msg);
1586      if (relocated_space != nullptr) {
1587        return relocated_space;
1588      }
1589    }
1590    error_msgs.push_back(local_error_msg);
1591  }
1592
1593  // Step 1.b: Only have a cache file.
1594  if (found_image && !has_system && has_cache) {
1595    std::string local_error_msg;
1596    std::unique_ptr<ImageSpace> cache_space =
1597        ImageSpaceLoader::Load(image_location,
1598                               cache_filename,
1599                               is_zygote,
1600                               is_global_cache,
1601                               /* validate_oat_file */ true,
1602                               &local_error_msg);
1603    if (cache_space != nullptr) {
1604      return cache_space;
1605    }
1606    error_msgs.push_back(local_error_msg);
1607  }
1608
1609  // Step 2: We have an existing image in /system.
1610
1611  // Step 2.a: We are not required to relocate it. Then we can use it directly.
1612  bool relocate = Runtime::Current()->ShouldRelocate();
1613
1614  if (found_image && has_system && !relocate) {
1615    std::string local_error_msg;
1616    std::unique_ptr<ImageSpace> system_space =
1617        ImageSpaceLoader::Load(image_location,
1618                               system_filename,
1619                               is_zygote,
1620                               is_global_cache,
1621                               /* validate_oat_file */ false,
1622                               &local_error_msg);
1623    if (system_space != nullptr) {
1624      return system_space;
1625    }
1626    error_msgs.push_back(local_error_msg);
1627  }
1628
1629  // Step 2.b: We require a relocated image. Then we must patch it. This step fails if this is a
1630  //           secondary image.
1631  if (found_image && has_system && relocate) {
1632    std::string local_error_msg;
1633    if (!dex2oat_enabled) {
1634      local_error_msg = "Patching disabled.";
1635    } else if (secondary_image) {
1636      // We really want a working image. Prune and restart.
1637      PruneDalvikCache(image_isa);
1638      _exit(1);
1639    } else if (ImageCreationAllowed(is_global_cache, image_isa, &local_error_msg)) {
1640      bool patch_success =
1641          RelocateImage(image_location, dalvik_cache.c_str(), image_isa, &local_error_msg);
1642      if (patch_success) {
1643        std::unique_ptr<ImageSpace> patched_space =
1644            ImageSpaceLoader::Load(image_location,
1645                                   cache_filename,
1646                                   is_zygote,
1647                                   is_global_cache,
1648                                   /* validate_oat_file */ false,
1649                                   &local_error_msg);
1650        if (patched_space != nullptr) {
1651          return patched_space;
1652        }
1653      }
1654    }
1655    error_msgs.push_back(StringPrintf("Cannot relocate image %s to %s: %s",
1656                                      image_location,
1657                                      cache_filename.c_str(),
1658                                      local_error_msg.c_str()));
1659  }
1660
1661  // Step 3: We do not have an existing image in /system, so generate an image into the dalvik
1662  //         cache. This step fails if this is a secondary image.
1663  if (!has_system) {
1664    std::string local_error_msg;
1665    if (!dex2oat_enabled) {
1666      local_error_msg = "Image compilation disabled.";
1667    } else if (secondary_image) {
1668      local_error_msg = "Cannot compile a secondary image.";
1669    } else if (ImageCreationAllowed(is_global_cache, image_isa, &local_error_msg)) {
1670      bool compilation_success = GenerateImage(cache_filename, image_isa, &local_error_msg);
1671      if (compilation_success) {
1672        std::unique_ptr<ImageSpace> compiled_space =
1673            ImageSpaceLoader::Load(image_location,
1674                                   cache_filename,
1675                                   is_zygote,
1676                                   is_global_cache,
1677                                   /* validate_oat_file */ false,
1678                                   &local_error_msg);
1679        if (compiled_space != nullptr) {
1680          return compiled_space;
1681        }
1682      }
1683    }
1684    error_msgs.push_back(StringPrintf("Cannot compile image to %s: %s",
1685                                      cache_filename.c_str(),
1686                                      local_error_msg.c_str()));
1687  }
1688
1689  // We failed. Prune the cache the free up space, create a compound error message and return no
1690  // image.
1691  PruneDalvikCache(image_isa);
1692
1693  std::ostringstream oss;
1694  bool first = true;
1695  for (const auto& msg : error_msgs) {
1696    if (!first) {
1697      oss << "\n    ";
1698    }
1699    oss << msg;
1700  }
1701  *error_msg = oss.str();
1702
1703  return nullptr;
1704}
1705
1706bool ImageSpace::LoadBootImage(const std::string& image_file_name,
1707                               const InstructionSet image_instruction_set,
1708                               std::vector<space::ImageSpace*>* boot_image_spaces,
1709                               uint8_t** oat_file_end) {
1710  DCHECK(boot_image_spaces != nullptr);
1711  DCHECK(boot_image_spaces->empty());
1712  DCHECK(oat_file_end != nullptr);
1713  DCHECK_NE(image_instruction_set, InstructionSet::kNone);
1714
1715  if (image_file_name.empty()) {
1716    return false;
1717  }
1718
1719  // For code reuse, handle this like a work queue.
1720  std::vector<std::string> image_file_names;
1721  image_file_names.push_back(image_file_name);
1722
1723  bool error = false;
1724  uint8_t* oat_file_end_tmp = *oat_file_end;
1725
1726  for (size_t index = 0; index < image_file_names.size(); ++index) {
1727    std::string& image_name = image_file_names[index];
1728    std::string error_msg;
1729    std::unique_ptr<space::ImageSpace> boot_image_space_uptr = CreateBootImage(
1730        image_name.c_str(),
1731        image_instruction_set,
1732        index > 0,
1733        &error_msg);
1734    if (boot_image_space_uptr != nullptr) {
1735      space::ImageSpace* boot_image_space = boot_image_space_uptr.release();
1736      boot_image_spaces->push_back(boot_image_space);
1737      // Oat files referenced by image files immediately follow them in memory, ensure alloc space
1738      // isn't going to get in the middle
1739      uint8_t* oat_file_end_addr = boot_image_space->GetImageHeader().GetOatFileEnd();
1740      CHECK_GT(oat_file_end_addr, boot_image_space->End());
1741      oat_file_end_tmp = AlignUp(oat_file_end_addr, kPageSize);
1742
1743      if (index == 0) {
1744        // If this was the first space, check whether there are more images to load.
1745        const OatFile* boot_oat_file = boot_image_space->GetOatFile();
1746        if (boot_oat_file == nullptr) {
1747          continue;
1748        }
1749
1750        const OatHeader& boot_oat_header = boot_oat_file->GetOatHeader();
1751        const char* boot_classpath =
1752            boot_oat_header.GetStoreValueByKey(OatHeader::kBootClassPathKey);
1753        if (boot_classpath == nullptr) {
1754          continue;
1755        }
1756
1757        ExtractMultiImageLocations(image_file_name, boot_classpath, &image_file_names);
1758      }
1759    } else {
1760      error = true;
1761      LOG(ERROR) << "Could not create image space with image file '" << image_file_name << "'. "
1762          << "Attempting to fall back to imageless running. Error was: " << error_msg
1763          << "\nAttempted image: " << image_name;
1764      break;
1765    }
1766  }
1767
1768  if (error) {
1769    // Remove already loaded spaces.
1770    for (space::Space* loaded_space : *boot_image_spaces) {
1771      delete loaded_space;
1772    }
1773    boot_image_spaces->clear();
1774    return false;
1775  }
1776
1777  *oat_file_end = oat_file_end_tmp;
1778  return true;
1779}
1780
1781ImageSpace::~ImageSpace() {
1782  Runtime* runtime = Runtime::Current();
1783  if (runtime == nullptr) {
1784    return;
1785  }
1786
1787  if (GetImageHeader().IsAppImage()) {
1788    // This image space did not modify resolution method then in Init.
1789    return;
1790  }
1791
1792  if (!runtime->HasResolutionMethod()) {
1793    // Another image space has already unloaded the below methods.
1794    return;
1795  }
1796
1797  runtime->ClearInstructionSet();
1798  runtime->ClearResolutionMethod();
1799  runtime->ClearImtConflictMethod();
1800  runtime->ClearImtUnimplementedMethod();
1801  runtime->ClearCalleeSaveMethods();
1802}
1803
1804std::unique_ptr<ImageSpace> ImageSpace::CreateFromAppImage(const char* image,
1805                                                           const OatFile* oat_file,
1806                                                           std::string* error_msg) {
1807  return ImageSpaceLoader::Init(image,
1808                                image,
1809                                /*validate_oat_file*/false,
1810                                oat_file,
1811                                /*out*/error_msg);
1812}
1813
1814const OatFile* ImageSpace::GetOatFile() const {
1815  return oat_file_non_owned_;
1816}
1817
1818std::unique_ptr<const OatFile> ImageSpace::ReleaseOatFile() {
1819  CHECK(oat_file_ != nullptr);
1820  return std::move(oat_file_);
1821}
1822
1823void ImageSpace::Dump(std::ostream& os) const {
1824  os << GetType()
1825      << " begin=" << reinterpret_cast<void*>(Begin())
1826      << ",end=" << reinterpret_cast<void*>(End())
1827      << ",size=" << PrettySize(Size())
1828      << ",name=\"" << GetName() << "\"]";
1829}
1830
1831std::string ImageSpace::GetMultiImageBootClassPath(
1832    const std::vector<const char*>& dex_locations,
1833    const std::vector<const char*>& oat_filenames,
1834    const std::vector<const char*>& image_filenames) {
1835  DCHECK_GT(oat_filenames.size(), 1u);
1836  // If the image filename was adapted (e.g., for our tests), we need to change this here,
1837  // too, but need to strip all path components (they will be re-established when loading).
1838  std::ostringstream bootcp_oss;
1839  bool first_bootcp = true;
1840  for (size_t i = 0; i < dex_locations.size(); ++i) {
1841    if (!first_bootcp) {
1842      bootcp_oss << ":";
1843    }
1844
1845    std::string dex_loc = dex_locations[i];
1846    std::string image_filename = image_filenames[i];
1847
1848    // Use the dex_loc path, but the image_filename name (without path elements).
1849    size_t dex_last_slash = dex_loc.rfind('/');
1850
1851    // npos is max(size_t). That makes this a bit ugly.
1852    size_t image_last_slash = image_filename.rfind('/');
1853    size_t image_last_at = image_filename.rfind('@');
1854    size_t image_last_sep = (image_last_slash == std::string::npos)
1855                                ? image_last_at
1856                                : (image_last_at == std::string::npos)
1857                                      ? std::string::npos
1858                                      : std::max(image_last_slash, image_last_at);
1859    // Note: whenever image_last_sep == npos, +1 overflow means using the full string.
1860
1861    if (dex_last_slash == std::string::npos) {
1862      dex_loc = image_filename.substr(image_last_sep + 1);
1863    } else {
1864      dex_loc = dex_loc.substr(0, dex_last_slash + 1) +
1865          image_filename.substr(image_last_sep + 1);
1866    }
1867
1868    // Image filenames already end with .art, no need to replace.
1869
1870    bootcp_oss << dex_loc;
1871    first_bootcp = false;
1872  }
1873  return bootcp_oss.str();
1874}
1875
1876bool ImageSpace::ValidateOatFile(const OatFile& oat_file, std::string* error_msg) {
1877  const ArtDexFileLoader dex_file_loader;
1878  for (const OatFile::OatDexFile* oat_dex_file : oat_file.GetOatDexFiles()) {
1879    const std::string& dex_file_location = oat_dex_file->GetDexFileLocation();
1880
1881    // Skip multidex locations - These will be checked when we visit their
1882    // corresponding primary non-multidex location.
1883    if (DexFileLoader::IsMultiDexLocation(dex_file_location.c_str())) {
1884      continue;
1885    }
1886
1887    std::vector<uint32_t> checksums;
1888    if (!dex_file_loader.GetMultiDexChecksums(dex_file_location.c_str(), &checksums, error_msg)) {
1889      *error_msg = StringPrintf("ValidateOatFile failed to get checksums of dex file '%s' "
1890                                "referenced by oat file %s: %s",
1891                                dex_file_location.c_str(),
1892                                oat_file.GetLocation().c_str(),
1893                                error_msg->c_str());
1894      return false;
1895    }
1896    CHECK(!checksums.empty());
1897    if (checksums[0] != oat_dex_file->GetDexFileLocationChecksum()) {
1898      *error_msg = StringPrintf("ValidateOatFile found checksum mismatch between oat file "
1899                                "'%s' and dex file '%s' (0x%x != 0x%x)",
1900                                oat_file.GetLocation().c_str(),
1901                                dex_file_location.c_str(),
1902                                oat_dex_file->GetDexFileLocationChecksum(),
1903                                checksums[0]);
1904      return false;
1905    }
1906
1907    // Verify checksums for any related multidex entries.
1908    for (size_t i = 1; i < checksums.size(); i++) {
1909      std::string multi_dex_location = DexFileLoader::GetMultiDexLocation(
1910          i,
1911          dex_file_location.c_str());
1912      const OatFile::OatDexFile* multi_dex = oat_file.GetOatDexFile(multi_dex_location.c_str(),
1913                                                                    nullptr,
1914                                                                    error_msg);
1915      if (multi_dex == nullptr) {
1916        *error_msg = StringPrintf("ValidateOatFile oat file '%s' is missing entry '%s'",
1917                                  oat_file.GetLocation().c_str(),
1918                                  multi_dex_location.c_str());
1919        return false;
1920      }
1921
1922      if (checksums[i] != multi_dex->GetDexFileLocationChecksum()) {
1923        *error_msg = StringPrintf("ValidateOatFile found checksum mismatch between oat file "
1924                                  "'%s' and dex file '%s' (0x%x != 0x%x)",
1925                                  oat_file.GetLocation().c_str(),
1926                                  multi_dex_location.c_str(),
1927                                  multi_dex->GetDexFileLocationChecksum(),
1928                                  checksums[i]);
1929        return false;
1930      }
1931    }
1932  }
1933  return true;
1934}
1935
1936void ImageSpace::ExtractMultiImageLocations(const std::string& input_image_file_name,
1937                                            const std::string& boot_classpath,
1938                                            std::vector<std::string>* image_file_names) {
1939  DCHECK(image_file_names != nullptr);
1940
1941  std::vector<std::string> images;
1942  Split(boot_classpath, ':', &images);
1943
1944  // Add the rest into the list. We have to adjust locations, possibly:
1945  //
1946  // For example, image_file_name is /a/b/c/d/e.art
1947  //              images[0] is          f/c/d/e.art
1948  // ----------------------------------------------
1949  //              images[1] is          g/h/i/j.art  -> /a/b/h/i/j.art
1950  const std::string& first_image = images[0];
1951  // Length of common suffix.
1952  size_t common = 0;
1953  while (common < input_image_file_name.size() &&
1954         common < first_image.size() &&
1955         *(input_image_file_name.end() - common - 1) == *(first_image.end() - common - 1)) {
1956    ++common;
1957  }
1958  // We want to replace the prefix of the input image with the prefix of the boot class path.
1959  // This handles the case where the image file contains @ separators.
1960  // Example image_file_name is oats/system@framework@boot.art
1961  // images[0] is .../arm/boot.art
1962  // means that the image name prefix will be oats/system@framework@
1963  // so that the other images are openable.
1964  const size_t old_prefix_length = first_image.size() - common;
1965  const std::string new_prefix = input_image_file_name.substr(
1966      0,
1967      input_image_file_name.size() - common);
1968
1969  // Apply pattern to images[1] .. images[n].
1970  for (size_t i = 1; i < images.size(); ++i) {
1971    const std::string& image = images[i];
1972    CHECK_GT(image.length(), old_prefix_length);
1973    std::string suffix = image.substr(old_prefix_length);
1974    image_file_names->push_back(new_prefix + suffix);
1975  }
1976}
1977
1978void ImageSpace::DumpSections(std::ostream& os) const {
1979  const uint8_t* base = Begin();
1980  const ImageHeader& header = GetImageHeader();
1981  for (size_t i = 0; i < ImageHeader::kSectionCount; ++i) {
1982    auto section_type = static_cast<ImageHeader::ImageSections>(i);
1983    const ImageSection& section = header.GetImageSection(section_type);
1984    os << section_type << " " << reinterpret_cast<const void*>(base + section.Offset())
1985       << "-" << reinterpret_cast<const void*>(base + section.End()) << "\n";
1986  }
1987}
1988
1989}  // namespace space
1990}  // namespace gc
1991}  // namespace art
1992