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