image_space.cc revision 2f1e15cc3e169ac61b910c41d695e55671c8d4ca
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 <dirent.h>
20#include <sys/types.h>
21
22#include <random>
23
24#include "base/macros.h"
25#include "base/stl_util.h"
26#include "base/unix_file/fd_file.h"
27#include "base/scoped_flock.h"
28#include "gc/accounting/space_bitmap-inl.h"
29#include "mirror/art_method.h"
30#include "mirror/class-inl.h"
31#include "mirror/object-inl.h"
32#include "oat_file.h"
33#include "os.h"
34#include "space-inl.h"
35#include "utils.h"
36
37namespace art {
38namespace gc {
39namespace space {
40
41Atomic<uint32_t> ImageSpace::bitmap_index_(0);
42
43ImageSpace::ImageSpace(const std::string& image_filename, const char* image_location,
44                       MemMap* mem_map, accounting::ContinuousSpaceBitmap* live_bitmap)
45    : MemMapSpace(image_filename, mem_map, mem_map->Begin(), mem_map->End(), mem_map->End(),
46                  kGcRetentionPolicyNeverCollect),
47      image_location_(image_location) {
48  DCHECK(live_bitmap != nullptr);
49  live_bitmap_.reset(live_bitmap);
50}
51
52static int32_t ChooseRelocationOffsetDelta(int32_t min_delta, int32_t max_delta) {
53  CHECK_ALIGNED(min_delta, kPageSize);
54  CHECK_ALIGNED(max_delta, kPageSize);
55  CHECK_LT(min_delta, max_delta);
56
57  std::default_random_engine generator;
58  generator.seed(NanoTime() * getpid());
59  std::uniform_int_distribution<int32_t> distribution(min_delta, max_delta);
60  int32_t r = distribution(generator);
61  if (r % 2 == 0) {
62    r = RoundUp(r, kPageSize);
63  } else {
64    r = RoundDown(r, kPageSize);
65  }
66  CHECK_LE(min_delta, r);
67  CHECK_GE(max_delta, r);
68  CHECK_ALIGNED(r, kPageSize);
69  return r;
70}
71
72// We are relocating or generating the core image. We should get rid of everything. It is all
73// out-of-date. We also don't really care if this fails since it is just a convienence.
74// Adapted from prune_dex_cache(const char* subdir) in frameworks/native/cmds/installd/commands.c
75// Note this should only be used during first boot.
76static void RealPruneDexCache(const std::string& cache_dir_path);
77static void PruneDexCache(InstructionSet isa) {
78  CHECK_NE(isa, kNone);
79  // Prune the base /data/dalvik-cache
80  RealPruneDexCache(GetDalvikCacheOrDie(".", false));
81  // prune /data/dalvik-cache/<isa>
82  RealPruneDexCache(GetDalvikCacheOrDie(GetInstructionSetString(isa), false));
83}
84static void RealPruneDexCache(const std::string& cache_dir_path) {
85  if (!OS::DirectoryExists(cache_dir_path.c_str())) {
86    return;
87  }
88  DIR* cache_dir = opendir(cache_dir_path.c_str());
89  if (cache_dir == nullptr) {
90    PLOG(WARNING) << "Unable to open " << cache_dir_path << " to delete it's contents";
91    return;
92  }
93
94  for (struct dirent* de = readdir(cache_dir); de != nullptr; de = readdir(cache_dir)) {
95    const char* name = de->d_name;
96    if (strcmp(name, ".") == 0 || strcmp(name, "..") == 0) {
97      continue;
98    }
99    // We only want to delete regular files.
100    if (de->d_type != DT_REG) {
101      if (de->d_type != DT_DIR) {
102        // We do expect some directories (namely the <isa> for pruning the base dalvik-cache).
103        LOG(WARNING) << "Unexpected file type of " << std::hex << de->d_type << " encountered.";
104      }
105      continue;
106    }
107    std::string cache_file(cache_dir_path);
108    cache_file += '/';
109    cache_file += name;
110    if (TEMP_FAILURE_RETRY(unlink(cache_file.c_str())) != 0) {
111      PLOG(ERROR) << "Unable to unlink " << cache_file;
112      continue;
113    }
114  }
115  CHECK_EQ(0, TEMP_FAILURE_RETRY(closedir(cache_dir))) << "Unable to close directory.";
116}
117
118static void RemoveImageFiles(const std::string& image_filename, std::string* error_msg) {
119  if (TEMP_FAILURE_RETRY(unlink(image_filename.c_str())) != 0) {
120    *error_msg = StringPrintf("Failed to remove image file after previous error: %s",
121                              error_msg->c_str());
122  }
123  std::string oat_filename(ImageHeader::GetOatLocationFromImageLocation(image_filename));
124  if (TEMP_FAILURE_RETRY(unlink(oat_filename.c_str())) != 0) {
125    *error_msg = StringPrintf("Failed to remove oat file after previous error: %s",
126                              error_msg->c_str());
127  }
128}
129
130static bool GenerateImage(const std::string& image_filename, InstructionSet image_isa,
131                          std::string* error_msg) {
132  const std::string boot_class_path_string(Runtime::Current()->GetBootClassPathString());
133  std::vector<std::string> boot_class_path;
134  Split(boot_class_path_string, ':', &boot_class_path);
135  if (boot_class_path.empty()) {
136    *error_msg = "Failed to generate image because no boot class path specified";
137    return false;
138  }
139  // We should clean up so we are more likely to have room for the image.
140  if (Runtime::Current()->IsZygote()) {
141    LOG(INFO) << "Pruning dalvik-cache since we are generating an image and will need to recompile";
142    PruneDexCache(image_isa);
143  }
144
145  std::vector<std::string> arg_vector;
146
147  std::string dex2oat(Runtime::Current()->GetCompilerExecutable());
148  arg_vector.push_back(dex2oat);
149
150  std::string image_option_string("--image=");
151  image_option_string += image_filename;
152  arg_vector.push_back(image_option_string);
153
154  for (size_t i = 0; i < boot_class_path.size(); i++) {
155    arg_vector.push_back(std::string("--dex-file=") + boot_class_path[i]);
156  }
157
158  std::string oat_file_option_string("--oat-file=");
159  oat_file_option_string += ImageHeader::GetOatLocationFromImageLocation(image_filename);
160  arg_vector.push_back(oat_file_option_string);
161
162  Runtime::Current()->AddCurrentRuntimeFeaturesAsDex2OatArguments(&arg_vector);
163  CHECK_EQ(image_isa, kRuntimeISA)
164      << "We should always be generating an image for the current isa.";
165
166  int32_t base_offset = ChooseRelocationOffsetDelta(ART_BASE_ADDRESS_MIN_DELTA,
167                                                    ART_BASE_ADDRESS_MAX_DELTA);
168  LOG(INFO) << "Using an offset of 0x" << std::hex << base_offset << " from default "
169            << "art base address of 0x" << std::hex << ART_BASE_ADDRESS;
170  arg_vector.push_back(StringPrintf("--base=0x%x", ART_BASE_ADDRESS + base_offset));
171
172  if (!kIsTargetBuild) {
173    arg_vector.push_back("--host");
174  }
175
176  const std::vector<std::string>& compiler_options = Runtime::Current()->GetImageCompilerOptions();
177  for (size_t i = 0; i < compiler_options.size(); ++i) {
178    arg_vector.push_back(compiler_options[i].c_str());
179  }
180
181  std::string command_line(Join(arg_vector, ' '));
182  LOG(INFO) << "GenerateImage: " << command_line;
183  return Exec(arg_vector, error_msg);
184}
185
186bool ImageSpace::FindImageFilename(const char* image_location,
187                                   const InstructionSet image_isa,
188                                   std::string* system_filename,
189                                   bool* has_system,
190                                   std::string* cache_filename,
191                                   bool* dalvik_cache_exists,
192                                   bool* has_cache,
193                                   bool* is_global_cache) {
194  *has_system = false;
195  *has_cache = false;
196  // image_location = /system/framework/boot.art
197  // system_image_location = /system/framework/<image_isa>/boot.art
198  std::string system_image_filename(GetSystemImageFilename(image_location, image_isa));
199  if (OS::FileExists(system_image_filename.c_str())) {
200    *system_filename = system_image_filename;
201    *has_system = true;
202  }
203
204  bool have_android_data = false;
205  *dalvik_cache_exists = false;
206  std::string dalvik_cache;
207  GetDalvikCache(GetInstructionSetString(image_isa), true, &dalvik_cache,
208                 &have_android_data, dalvik_cache_exists, is_global_cache);
209
210  if (have_android_data && *dalvik_cache_exists) {
211    // Always set output location even if it does not exist,
212    // so that the caller knows where to create the image.
213    //
214    // image_location = /system/framework/boot.art
215    // *image_filename = /data/dalvik-cache/<image_isa>/boot.art
216    std::string error_msg;
217    if (!GetDalvikCacheFilename(image_location, dalvik_cache.c_str(), cache_filename, &error_msg)) {
218      LOG(WARNING) << error_msg;
219      return *has_system;
220    }
221    *has_cache = OS::FileExists(cache_filename->c_str());
222  }
223  return *has_system || *has_cache;
224}
225
226static bool ReadSpecificImageHeader(const char* filename, ImageHeader* image_header) {
227    std::unique_ptr<File> image_file(OS::OpenFileForReading(filename));
228    if (image_file.get() == nullptr) {
229      return false;
230    }
231    const bool success = image_file->ReadFully(image_header, sizeof(ImageHeader));
232    if (!success || !image_header->IsValid()) {
233      return false;
234    }
235    return true;
236}
237
238// Relocate the image at image_location to dest_filename and relocate it by a random amount.
239static bool RelocateImage(const char* image_location, const char* dest_filename,
240                               InstructionSet isa, std::string* error_msg) {
241  // We should clean up so we are more likely to have room for the image.
242  if (Runtime::Current()->IsZygote()) {
243    LOG(INFO) << "Pruning dalvik-cache since we are relocating an image and will need to recompile";
244    PruneDexCache(isa);
245  }
246
247  std::string patchoat(Runtime::Current()->GetPatchoatExecutable());
248
249  std::string input_image_location_arg("--input-image-location=");
250  input_image_location_arg += image_location;
251
252  std::string output_image_filename_arg("--output-image-file=");
253  output_image_filename_arg += dest_filename;
254
255  std::string input_oat_location_arg("--input-oat-location=");
256  input_oat_location_arg += ImageHeader::GetOatLocationFromImageLocation(image_location);
257
258  std::string output_oat_filename_arg("--output-oat-file=");
259  output_oat_filename_arg += ImageHeader::GetOatLocationFromImageLocation(dest_filename);
260
261  std::string instruction_set_arg("--instruction-set=");
262  instruction_set_arg += GetInstructionSetString(isa);
263
264  std::string base_offset_arg("--base-offset-delta=");
265  StringAppendF(&base_offset_arg, "%d", ChooseRelocationOffsetDelta(ART_BASE_ADDRESS_MIN_DELTA,
266                                                                    ART_BASE_ADDRESS_MAX_DELTA));
267
268  std::vector<std::string> argv;
269  argv.push_back(patchoat);
270
271  argv.push_back(input_image_location_arg);
272  argv.push_back(output_image_filename_arg);
273
274  argv.push_back(input_oat_location_arg);
275  argv.push_back(output_oat_filename_arg);
276
277  argv.push_back(instruction_set_arg);
278  argv.push_back(base_offset_arg);
279
280  std::string command_line(Join(argv, ' '));
281  LOG(INFO) << "RelocateImage: " << command_line;
282  return Exec(argv, error_msg);
283}
284
285static ImageHeader* ReadSpecificImageHeader(const char* filename, std::string* error_msg) {
286  std::unique_ptr<ImageHeader> hdr(new ImageHeader);
287  if (!ReadSpecificImageHeader(filename, hdr.get())) {
288    *error_msg = StringPrintf("Unable to read image header for %s", filename);
289    return nullptr;
290  }
291  return hdr.release();
292}
293
294ImageHeader* ImageSpace::ReadImageHeaderOrDie(const char* image_location,
295                                              const InstructionSet image_isa) {
296  std::string error_msg;
297  ImageHeader* image_header = ReadImageHeader(image_location, image_isa, &error_msg);
298  if (image_header == nullptr) {
299    LOG(FATAL) << error_msg;
300  }
301  return image_header;
302}
303
304ImageHeader* ImageSpace::ReadImageHeader(const char* image_location,
305                                         const InstructionSet image_isa,
306                                         std::string* error_msg) {
307  std::string system_filename;
308  bool has_system = false;
309  std::string cache_filename;
310  bool has_cache = false;
311  bool dalvik_cache_exists = false;
312  bool is_global_cache = false;
313  if (FindImageFilename(image_location, image_isa, &system_filename, &has_system,
314                        &cache_filename, &dalvik_cache_exists, &has_cache, &is_global_cache)) {
315    if (Runtime::Current()->ShouldRelocate()) {
316      if (has_system && has_cache) {
317        std::unique_ptr<ImageHeader> sys_hdr(new ImageHeader);
318        std::unique_ptr<ImageHeader> cache_hdr(new ImageHeader);
319        if (!ReadSpecificImageHeader(system_filename.c_str(), sys_hdr.get())) {
320          *error_msg = StringPrintf("Unable to read image header for %s at %s",
321                                    image_location, system_filename.c_str());
322          return nullptr;
323        }
324        if (!ReadSpecificImageHeader(cache_filename.c_str(), cache_hdr.get())) {
325          *error_msg = StringPrintf("Unable to read image header for %s at %s",
326                                    image_location, cache_filename.c_str());
327          return nullptr;
328        }
329        if (sys_hdr->GetOatChecksum() != cache_hdr->GetOatChecksum()) {
330          *error_msg = StringPrintf("Unable to find a relocated version of image file %s",
331                                    image_location);
332          return nullptr;
333        }
334        return cache_hdr.release();
335      } else if (!has_cache) {
336        *error_msg = StringPrintf("Unable to find a relocated version of image file %s",
337                                  image_location);
338        return nullptr;
339      } else if (!has_system && has_cache) {
340        // This can probably just use the cache one.
341        return ReadSpecificImageHeader(cache_filename.c_str(), error_msg);
342      }
343    } else {
344      // We don't want to relocate, Just pick the appropriate one if we have it and return.
345      if (has_system && has_cache) {
346        // We want the cache if the checksum matches, otherwise the system.
347        std::unique_ptr<ImageHeader> system(ReadSpecificImageHeader(system_filename.c_str(),
348                                                                    error_msg));
349        std::unique_ptr<ImageHeader> cache(ReadSpecificImageHeader(cache_filename.c_str(),
350                                                                   error_msg));
351        if (system.get() == nullptr ||
352            (cache.get() != nullptr && cache->GetOatChecksum() == system->GetOatChecksum())) {
353          return cache.release();
354        } else {
355          return system.release();
356        }
357      } else if (has_system) {
358        return ReadSpecificImageHeader(system_filename.c_str(), error_msg);
359      } else if (has_cache) {
360        return ReadSpecificImageHeader(cache_filename.c_str(), error_msg);
361      }
362    }
363  }
364
365  *error_msg = StringPrintf("Unable to find image file for %s", image_location);
366  return nullptr;
367}
368
369static bool ChecksumsMatch(const char* image_a, const char* image_b) {
370  ImageHeader hdr_a;
371  ImageHeader hdr_b;
372  return ReadSpecificImageHeader(image_a, &hdr_a) && ReadSpecificImageHeader(image_b, &hdr_b)
373      && hdr_a.GetOatChecksum() == hdr_b.GetOatChecksum();
374}
375
376static bool ImageCreationAllowed(bool is_global_cache, std::string* error_msg) {
377  // Anyone can write into a "local" cache.
378  if (!is_global_cache) {
379    return true;
380  }
381
382  // Only the zygote is allowed to create the global boot image.
383  if (Runtime::Current()->IsZygote()) {
384    return true;
385  }
386
387  *error_msg = "Only the zygote can create the global boot image.";
388  return false;
389}
390
391ImageSpace* ImageSpace::Create(const char* image_location,
392                               const InstructionSet image_isa,
393                               std::string* error_msg) {
394  std::string system_filename;
395  bool has_system = false;
396  std::string cache_filename;
397  bool has_cache = false;
398  bool dalvik_cache_exists = false;
399  bool is_global_cache = true;
400  const bool found_image = FindImageFilename(image_location, image_isa, &system_filename,
401                                             &has_system, &cache_filename, &dalvik_cache_exists,
402                                             &has_cache, &is_global_cache);
403
404  ImageSpace* space;
405  bool relocate = Runtime::Current()->ShouldRelocate();
406  bool can_compile = Runtime::Current()->IsImageDex2OatEnabled();
407  if (found_image) {
408    const std::string* image_filename;
409    bool is_system = false;
410    bool relocated_version_used = false;
411    if (relocate) {
412      if (!dalvik_cache_exists) {
413        *error_msg = StringPrintf("Requiring relocation for image '%s' at '%s' but we do not have "
414                                  "any dalvik_cache to find/place it in.",
415                                  image_location, system_filename.c_str());
416        return nullptr;
417      }
418      if (has_system) {
419        if (has_cache && ChecksumsMatch(system_filename.c_str(), cache_filename.c_str())) {
420          // We already have a relocated version
421          image_filename = &cache_filename;
422          relocated_version_used = true;
423        } else {
424          // We cannot have a relocated version, Relocate the system one and use it.
425
426          std::string reason;
427          bool success;
428
429          // Check whether we are allowed to relocate.
430          if (!can_compile) {
431            reason = "Image dex2oat disabled by -Xnoimage-dex2oat.";
432            success = false;
433          } else if (!ImageCreationAllowed(is_global_cache, &reason)) {
434            // Whether we can write to the cache.
435            success = false;
436          } else {
437            // Try to relocate.
438            success = RelocateImage(image_location, cache_filename.c_str(), image_isa, &reason);
439          }
440
441          if (success) {
442            relocated_version_used = true;
443            image_filename = &cache_filename;
444          } else {
445            *error_msg = StringPrintf("Unable to relocate image '%s' from '%s' to '%s': %s",
446                                      image_location, system_filename.c_str(),
447                                      cache_filename.c_str(), reason.c_str());
448            RemoveImageFiles(cache_filename, error_msg);
449            return nullptr;
450          }
451        }
452      } else {
453        CHECK(has_cache);
454        // We can just use cache's since it should be fine. This might or might not be relocated.
455        image_filename = &cache_filename;
456      }
457    } else {
458      if (has_system && has_cache) {
459        // Check they have the same cksum. If they do use the cache. Otherwise system.
460        if (ChecksumsMatch(system_filename.c_str(), cache_filename.c_str())) {
461          image_filename = &cache_filename;
462          relocated_version_used = true;
463        } else {
464          image_filename = &system_filename;
465          is_system = true;
466        }
467      } else if (has_system) {
468        image_filename = &system_filename;
469        is_system = true;
470      } else {
471        CHECK(has_cache);
472        image_filename = &cache_filename;
473      }
474    }
475    {
476      // Note that we must not use the file descriptor associated with
477      // ScopedFlock::GetFile to Init the image file. We want the file
478      // descriptor (and the associated exclusive lock) to be released when
479      // we leave Create.
480      ScopedFlock image_lock;
481      image_lock.Init(image_filename->c_str(), error_msg);
482      VLOG(startup) << "Using image file " << image_filename->c_str() << " for image location "
483                    << image_location;
484      // If we are in /system we can assume the image is good. We can also
485      // assume this if we are using a relocated image (i.e. image checksum
486      // matches) since this is only different by the offset. We need this to
487      // make sure that host tests continue to work.
488      space = ImageSpace::Init(image_filename->c_str(), image_location,
489                               !(is_system || relocated_version_used), error_msg);
490    }
491    if (space != nullptr) {
492      return space;
493    }
494
495    // If the /system file exists, it should be up-to-date, don't try to generate it. Same if it is
496    // a relocated copy from something in /system (i.e. checksum's match).
497    // Otherwise, log a warning and fall through to GenerateImage.
498    if (relocated_version_used) {
499      LOG(FATAL) << "Attempted to use relocated version of " << image_location << " "
500                 << "at " << cache_filename << " generated from " << system_filename << " "
501                 << "but image failed to load: " << *error_msg;
502      return nullptr;
503    } else if (is_system) {
504      *error_msg = StringPrintf("Failed to load /system image '%s': %s",
505                                image_filename->c_str(), error_msg->c_str());
506      return nullptr;
507    } else {
508      LOG(WARNING) << *error_msg;
509    }
510  }
511
512  if (!can_compile) {
513    *error_msg = "Not attempting to compile image because -Xnoimage-dex2oat";
514    return nullptr;
515  } else if (!dalvik_cache_exists) {
516    *error_msg = StringPrintf("No place to put generated image.");
517    return nullptr;
518  } else if (!ImageCreationAllowed(is_global_cache, error_msg)) {
519    return nullptr;
520  } else if (!GenerateImage(cache_filename, image_isa, error_msg)) {
521    *error_msg = StringPrintf("Failed to generate image '%s': %s",
522                              cache_filename.c_str(), error_msg->c_str());
523    RemoveImageFiles(cache_filename, error_msg);
524    return nullptr;
525  } else {
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_lock;
531    image_lock.Init(cache_filename.c_str(), error_msg);
532    space = ImageSpace::Init(cache_filename.c_str(), image_location, true, error_msg);
533    if (space == nullptr) {
534      *error_msg = StringPrintf("Failed to load generated image '%s': %s",
535                                cache_filename.c_str(), error_msg->c_str());
536    }
537    return space;
538  }
539}
540
541void ImageSpace::VerifyImageAllocations() {
542  uint8_t* current = Begin() + RoundUp(sizeof(ImageHeader), kObjectAlignment);
543  while (current < End()) {
544    DCHECK_ALIGNED(current, kObjectAlignment);
545    mirror::Object* obj = reinterpret_cast<mirror::Object*>(current);
546    CHECK(live_bitmap_->Test(obj));
547    CHECK(obj->GetClass() != nullptr) << "Image object at address " << obj << " has null class";
548    if (kUseBakerOrBrooksReadBarrier) {
549      obj->AssertReadBarrierPointer();
550    }
551    current += RoundUp(obj->SizeOf(), kObjectAlignment);
552  }
553}
554
555ImageSpace* ImageSpace::Init(const char* image_filename, const char* image_location,
556                             bool validate_oat_file, std::string* error_msg) {
557  CHECK(image_filename != nullptr);
558  CHECK(image_location != nullptr);
559
560  uint64_t start_time = 0;
561  if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
562    start_time = NanoTime();
563    LOG(INFO) << "ImageSpace::Init entering image_filename=" << image_filename;
564  }
565
566  std::unique_ptr<File> file(OS::OpenFileForReading(image_filename));
567  if (file.get() == NULL) {
568    *error_msg = StringPrintf("Failed to open '%s'", image_filename);
569    return nullptr;
570  }
571  ImageHeader image_header;
572  bool success = file->ReadFully(&image_header, sizeof(image_header));
573  if (!success || !image_header.IsValid()) {
574    *error_msg = StringPrintf("Invalid image header in '%s'", image_filename);
575    return nullptr;
576  }
577
578  // Note: The image header is part of the image due to mmap page alignment required of offset.
579  std::unique_ptr<MemMap> map(MemMap::MapFileAtAddress(image_header.GetImageBegin(),
580                                                 image_header.GetImageSize(),
581                                                 PROT_READ | PROT_WRITE,
582                                                 MAP_PRIVATE,
583                                                 file->Fd(),
584                                                 0,
585                                                 false,
586                                                 image_filename,
587                                                 error_msg));
588  if (map.get() == NULL) {
589    DCHECK(!error_msg->empty());
590    return nullptr;
591  }
592  CHECK_EQ(image_header.GetImageBegin(), map->Begin());
593  DCHECK_EQ(0, memcmp(&image_header, map->Begin(), sizeof(ImageHeader)));
594
595  std::unique_ptr<MemMap> image_map(
596      MemMap::MapFileAtAddress(nullptr, image_header.GetImageBitmapSize(),
597                               PROT_READ, MAP_PRIVATE,
598                               file->Fd(), image_header.GetBitmapOffset(),
599                               false,
600                               image_filename,
601                               error_msg));
602  if (image_map.get() == nullptr) {
603    *error_msg = StringPrintf("Failed to map image bitmap: %s", error_msg->c_str());
604    return nullptr;
605  }
606  uint32_t bitmap_index = bitmap_index_.FetchAndAddSequentiallyConsistent(1);
607  std::string bitmap_name(StringPrintf("imagespace %s live-bitmap %u", image_filename,
608                                       bitmap_index));
609  std::unique_ptr<accounting::ContinuousSpaceBitmap> bitmap(
610      accounting::ContinuousSpaceBitmap::CreateFromMemMap(bitmap_name, image_map.release(),
611                                                          reinterpret_cast<uint8_t*>(map->Begin()),
612                                                          map->Size()));
613  if (bitmap.get() == nullptr) {
614    *error_msg = StringPrintf("Could not create bitmap '%s'", bitmap_name.c_str());
615    return nullptr;
616  }
617
618  std::unique_ptr<ImageSpace> space(new ImageSpace(image_filename, image_location,
619                                             map.release(), bitmap.release()));
620
621  // VerifyImageAllocations() will be called later in Runtime::Init()
622  // as some class roots like ArtMethod::java_lang_reflect_ArtMethod_
623  // and ArtField::java_lang_reflect_ArtField_, which are used from
624  // Object::SizeOf() which VerifyImageAllocations() calls, are not
625  // set yet at this point.
626
627  space->oat_file_.reset(space->OpenOatFile(image_filename, error_msg));
628  if (space->oat_file_.get() == nullptr) {
629    DCHECK(!error_msg->empty());
630    return nullptr;
631  }
632
633  if (validate_oat_file && !space->ValidateOatFile(error_msg)) {
634    DCHECK(!error_msg->empty());
635    return nullptr;
636  }
637
638  Runtime* runtime = Runtime::Current();
639  runtime->SetInstructionSet(space->oat_file_->GetOatHeader().GetInstructionSet());
640
641  mirror::Object* resolution_method = image_header.GetImageRoot(ImageHeader::kResolutionMethod);
642  runtime->SetResolutionMethod(down_cast<mirror::ArtMethod*>(resolution_method));
643  mirror::Object* imt_conflict_method = image_header.GetImageRoot(ImageHeader::kImtConflictMethod);
644  runtime->SetImtConflictMethod(down_cast<mirror::ArtMethod*>(imt_conflict_method));
645  mirror::Object* imt_unimplemented_method =
646      image_header.GetImageRoot(ImageHeader::kImtUnimplementedMethod);
647  runtime->SetImtUnimplementedMethod(down_cast<mirror::ArtMethod*>(imt_unimplemented_method));
648  mirror::Object* default_imt = image_header.GetImageRoot(ImageHeader::kDefaultImt);
649  runtime->SetDefaultImt(down_cast<mirror::ObjectArray<mirror::ArtMethod>*>(default_imt));
650
651  mirror::Object* callee_save_method = image_header.GetImageRoot(ImageHeader::kCalleeSaveMethod);
652  runtime->SetCalleeSaveMethod(down_cast<mirror::ArtMethod*>(callee_save_method),
653                               Runtime::kSaveAll);
654  callee_save_method = image_header.GetImageRoot(ImageHeader::kRefsOnlySaveMethod);
655  runtime->SetCalleeSaveMethod(down_cast<mirror::ArtMethod*>(callee_save_method),
656                               Runtime::kRefsOnly);
657  callee_save_method = image_header.GetImageRoot(ImageHeader::kRefsAndArgsSaveMethod);
658  runtime->SetCalleeSaveMethod(down_cast<mirror::ArtMethod*>(callee_save_method),
659                               Runtime::kRefsAndArgs);
660
661  if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
662    LOG(INFO) << "ImageSpace::Init exiting (" << PrettyDuration(NanoTime() - start_time)
663             << ") " << *space.get();
664  }
665  return space.release();
666}
667
668OatFile* ImageSpace::OpenOatFile(const char* image_path, std::string* error_msg) const {
669  const ImageHeader& image_header = GetImageHeader();
670  std::string oat_filename = ImageHeader::GetOatLocationFromImageLocation(image_path);
671
672  OatFile* oat_file = OatFile::Open(oat_filename, oat_filename, image_header.GetOatDataBegin(),
673                                    !Runtime::Current()->IsCompiler(), error_msg);
674  if (oat_file == NULL) {
675    *error_msg = StringPrintf("Failed to open oat file '%s' referenced from image %s: %s",
676                              oat_filename.c_str(), GetName(), error_msg->c_str());
677    return nullptr;
678  }
679  uint32_t oat_checksum = oat_file->GetOatHeader().GetChecksum();
680  uint32_t image_oat_checksum = image_header.GetOatChecksum();
681  if (oat_checksum != image_oat_checksum) {
682    *error_msg = StringPrintf("Failed to match oat file checksum 0x%x to expected oat checksum 0x%x"
683                              " in image %s", oat_checksum, image_oat_checksum, GetName());
684    return nullptr;
685  }
686  int32_t image_patch_delta = image_header.GetPatchDelta();
687  int32_t oat_patch_delta = oat_file->GetOatHeader().GetImagePatchDelta();
688  if (oat_patch_delta != image_patch_delta) {
689    // We should have already relocated by this point. Bail out.
690    *error_msg = StringPrintf("Failed to match oat file patch delta %d to expected patch delta %d "
691                              "in image %s", oat_patch_delta, image_patch_delta, GetName());
692    return nullptr;
693  }
694
695  return oat_file;
696}
697
698bool ImageSpace::ValidateOatFile(std::string* error_msg) const {
699  CHECK(oat_file_.get() != NULL);
700  for (const OatFile::OatDexFile* oat_dex_file : oat_file_->GetOatDexFiles()) {
701    const std::string& dex_file_location = oat_dex_file->GetDexFileLocation();
702    uint32_t dex_file_location_checksum;
703    if (!DexFile::GetChecksum(dex_file_location.c_str(), &dex_file_location_checksum, error_msg)) {
704      *error_msg = StringPrintf("Failed to get checksum of dex file '%s' referenced by image %s: "
705                                "%s", dex_file_location.c_str(), GetName(), error_msg->c_str());
706      return false;
707    }
708    if (dex_file_location_checksum != oat_dex_file->GetDexFileLocationChecksum()) {
709      *error_msg = StringPrintf("ValidateOatFile found checksum mismatch between oat file '%s' and "
710                                "dex file '%s' (0x%x != 0x%x)",
711                                oat_file_->GetLocation().c_str(), dex_file_location.c_str(),
712                                oat_dex_file->GetDexFileLocationChecksum(),
713                                dex_file_location_checksum);
714      return false;
715    }
716  }
717  return true;
718}
719
720const OatFile* ImageSpace::GetOatFile() const {
721  return oat_file_.get();
722}
723
724OatFile* ImageSpace::ReleaseOatFile() {
725  CHECK(oat_file_.get() != NULL);
726  return oat_file_.release();
727}
728
729void ImageSpace::Dump(std::ostream& os) const {
730  os << GetType()
731      << " begin=" << reinterpret_cast<void*>(Begin())
732      << ",end=" << reinterpret_cast<void*>(End())
733      << ",size=" << PrettySize(Size())
734      << ",name=\"" << GetName() << "\"]";
735}
736
737}  // namespace space
738}  // namespace gc
739}  // namespace art
740