image_space.cc revision c7cb1901b776129044a4ad3886fd6450e83df681
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 "base/stl_util.h"
20#include "base/unix_file/fd_file.h"
21#include "gc/accounting/space_bitmap-inl.h"
22#include "mirror/art_method.h"
23#include "mirror/class-inl.h"
24#include "mirror/object-inl.h"
25#include "oat_file.h"
26#include "os.h"
27#include "runtime.h"
28#include "space-inl.h"
29#include "utils.h"
30
31namespace art {
32namespace gc {
33namespace space {
34
35Atomic<uint32_t> ImageSpace::bitmap_index_(0);
36
37ImageSpace::ImageSpace(const std::string& name, MemMap* mem_map,
38                       accounting::SpaceBitmap* live_bitmap)
39    : MemMapSpace(name, mem_map, mem_map->Begin(), mem_map->End(), mem_map->End(),
40                  kGcRetentionPolicyNeverCollect) {
41  DCHECK(live_bitmap != nullptr);
42  live_bitmap_.reset(live_bitmap);
43}
44
45static bool GenerateImage(const std::string& image_file_name, std::string* error_msg) {
46  const std::string boot_class_path_string(Runtime::Current()->GetBootClassPathString());
47  std::vector<std::string> boot_class_path;
48  Split(boot_class_path_string, ':', boot_class_path);
49  if (boot_class_path.empty()) {
50    *error_msg = "Failed to generate image because no boot class path specified";
51    return false;
52  }
53
54  std::vector<std::string> arg_vector;
55
56  std::string dex2oat(GetAndroidRoot());
57  dex2oat += (kIsDebugBuild ? "/bin/dex2oatd" : "/bin/dex2oat");
58  arg_vector.push_back(dex2oat);
59
60  std::string image_option_string("--image=");
61  image_option_string += image_file_name;
62  arg_vector.push_back(image_option_string);
63
64  arg_vector.push_back("--runtime-arg");
65  arg_vector.push_back("-Xms64m");
66
67  arg_vector.push_back("--runtime-arg");
68  arg_vector.push_back("-Xmx64m");
69
70  for (size_t i = 0; i < boot_class_path.size(); i++) {
71    arg_vector.push_back(std::string("--dex-file=") + boot_class_path[i]);
72  }
73
74  std::string oat_file_option_string("--oat-file=");
75  oat_file_option_string += image_file_name;
76  oat_file_option_string.erase(oat_file_option_string.size() - 3);
77  oat_file_option_string += "oat";
78  arg_vector.push_back(oat_file_option_string);
79
80  arg_vector.push_back(StringPrintf("--base=0x%x", ART_BASE_ADDRESS));
81
82  if (kIsTargetBuild) {
83    arg_vector.push_back("--image-classes-zip=/system/framework/framework.jar");
84    arg_vector.push_back("--image-classes=preloaded-classes");
85  } else {
86    arg_vector.push_back("--host");
87  }
88
89  const std::vector<std::string>& compiler_options = Runtime::Current()->GetImageCompilerOptions();
90  for (size_t i = 0; i < compiler_options.size(); ++i) {
91    arg_vector.push_back(compiler_options[i].c_str());
92  }
93
94  std::string command_line(Join(arg_vector, ' '));
95  LOG(INFO) << "GenerateImage: " << command_line;
96  return Exec(arg_vector, error_msg);
97}
98
99ImageSpace* ImageSpace::Create(const char* original_image_file_name) {
100  if (OS::FileExists(original_image_file_name)) {
101    // If the /system file exists, it should be up-to-date, don't try to generate
102    std::string error_msg;
103    ImageSpace* space = ImageSpace::Init(original_image_file_name, false, &error_msg);
104    if (space == nullptr) {
105      LOG(FATAL) << "Failed to load image '" << original_image_file_name << "': " << error_msg;
106    }
107    return space;
108  }
109  // If the /system file didn't exist, we need to use one from the dalvik-cache.
110  // If the cache file exists, try to open, but if it fails, regenerate.
111  // If it does not exist, generate.
112  std::string image_file_name(GetDalvikCacheFilenameOrDie(original_image_file_name));
113  std::string error_msg;
114  if (OS::FileExists(image_file_name.c_str())) {
115    space::ImageSpace* image_space = ImageSpace::Init(image_file_name.c_str(), true, &error_msg);
116    if (image_space != nullptr) {
117      return image_space;
118    } else {
119      LOG(WARNING) << error_msg;
120    }
121  }
122  CHECK(GenerateImage(image_file_name, &error_msg))
123      << "Failed to generate image '" << image_file_name << "': " << error_msg;
124  ImageSpace* space = ImageSpace::Init(image_file_name.c_str(), true, &error_msg);
125  if (space == nullptr) {
126    LOG(FATAL) << "Failed to load image '" << original_image_file_name << "': " << error_msg;
127  }
128  return space;
129}
130
131void ImageSpace::VerifyImageAllocations() {
132  byte* current = Begin() + RoundUp(sizeof(ImageHeader), kObjectAlignment);
133  while (current < End()) {
134    DCHECK_ALIGNED(current, kObjectAlignment);
135    mirror::Object* obj = reinterpret_cast<mirror::Object*>(current);
136    CHECK(live_bitmap_->Test(obj));
137    CHECK(obj->GetClass() != nullptr) << "Image object at address " << obj << " has null class";
138    if (kUseBrooksPointer) {
139      CHECK(obj->GetBrooksPointer() == obj)
140          << "Bad Brooks pointer: obj=" << reinterpret_cast<void*>(obj)
141          << " brooks_ptr=" << reinterpret_cast<void*>(obj->GetBrooksPointer());
142    }
143    current += RoundUp(obj->SizeOf(), kObjectAlignment);
144  }
145}
146
147ImageSpace* ImageSpace::Init(const char* image_file_name, bool validate_oat_file,
148                             std::string* error_msg) {
149  CHECK(image_file_name != nullptr);
150
151  uint64_t start_time = 0;
152  if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
153    start_time = NanoTime();
154    LOG(INFO) << "ImageSpace::Init entering image_file_name=" << image_file_name;
155  }
156
157  UniquePtr<File> file(OS::OpenFileForReading(image_file_name));
158  if (file.get() == NULL) {
159    *error_msg = StringPrintf("Failed to open '%s'", image_file_name);
160    return nullptr;
161  }
162  ImageHeader image_header;
163  bool success = file->ReadFully(&image_header, sizeof(image_header));
164  if (!success || !image_header.IsValid()) {
165    *error_msg = StringPrintf("Invalid image header in '%s'", image_file_name);
166    return nullptr;
167  }
168
169  // Note: The image header is part of the image due to mmap page alignment required of offset.
170  UniquePtr<MemMap> map(MemMap::MapFileAtAddress(image_header.GetImageBegin(),
171                                                 image_header.GetImageSize(),
172                                                 PROT_READ | PROT_WRITE,
173                                                 MAP_PRIVATE | MAP_FIXED,
174                                                 file->Fd(),
175                                                 0,
176                                                 false,
177                                                 image_file_name,
178                                                 error_msg));
179  if (map.get() == NULL) {
180    DCHECK(!error_msg->empty());
181    return nullptr;
182  }
183  CHECK_EQ(image_header.GetImageBegin(), map->Begin());
184  DCHECK_EQ(0, memcmp(&image_header, map->Begin(), sizeof(ImageHeader)));
185
186  UniquePtr<MemMap> image_map(MemMap::MapFileAtAddress(nullptr, image_header.GetImageBitmapSize(),
187                                                       PROT_READ, MAP_PRIVATE,
188                                                       file->Fd(), image_header.GetBitmapOffset(),
189                                                       false,
190                                                       image_file_name,
191                                                       error_msg));
192  if (image_map.get() == nullptr) {
193    *error_msg = StringPrintf("Failed to map image bitmap: %s", error_msg->c_str());
194    return nullptr;
195  }
196  uint32_t bitmap_index = bitmap_index_.FetchAndAdd(1);
197  std::string bitmap_name(StringPrintf("imagespace %s live-bitmap %u", image_file_name,
198                                       bitmap_index));
199  UniquePtr<accounting::SpaceBitmap> bitmap(
200      accounting::SpaceBitmap::CreateFromMemMap(bitmap_name, image_map.release(),
201                                                reinterpret_cast<byte*>(map->Begin()),
202                                                map->Size()));
203  if (bitmap.get() == nullptr) {
204    *error_msg = StringPrintf("Could not create bitmap '%s'", bitmap_name.c_str());
205    return nullptr;
206  }
207
208  Runtime* runtime = Runtime::Current();
209  mirror::Object* resolution_method = image_header.GetImageRoot(ImageHeader::kResolutionMethod);
210  runtime->SetResolutionMethod(down_cast<mirror::ArtMethod*>(resolution_method));
211  mirror::Object* imt_conflict_method = image_header.GetImageRoot(ImageHeader::kImtConflictMethod);
212  runtime->SetImtConflictMethod(down_cast<mirror::ArtMethod*>(imt_conflict_method));
213  mirror::Object* default_imt = image_header.GetImageRoot(ImageHeader::kDefaultImt);
214  runtime->SetDefaultImt(down_cast<mirror::ObjectArray<mirror::ArtMethod>*>(default_imt));
215
216  mirror::Object* callee_save_method = image_header.GetImageRoot(ImageHeader::kCalleeSaveMethod);
217  runtime->SetCalleeSaveMethod(down_cast<mirror::ArtMethod*>(callee_save_method), Runtime::kSaveAll);
218  callee_save_method = image_header.GetImageRoot(ImageHeader::kRefsOnlySaveMethod);
219  runtime->SetCalleeSaveMethod(down_cast<mirror::ArtMethod*>(callee_save_method), Runtime::kRefsOnly);
220  callee_save_method = image_header.GetImageRoot(ImageHeader::kRefsAndArgsSaveMethod);
221  runtime->SetCalleeSaveMethod(down_cast<mirror::ArtMethod*>(callee_save_method), Runtime::kRefsAndArgs);
222
223  UniquePtr<ImageSpace> space(new ImageSpace(image_file_name, map.release(), bitmap.release()));
224  if (kIsDebugBuild) {
225    space->VerifyImageAllocations();
226  }
227
228  space->oat_file_.reset(space->OpenOatFile(image_file_name, error_msg));
229  if (space->oat_file_.get() == nullptr) {
230    DCHECK(!error_msg->empty());
231    return nullptr;
232  }
233
234  if (validate_oat_file && !space->ValidateOatFile(error_msg)) {
235    DCHECK(!error_msg->empty());
236    return nullptr;
237  }
238
239  if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
240    LOG(INFO) << "ImageSpace::Init exiting (" << PrettyDuration(NanoTime() - start_time)
241             << ") " << *space.get();
242  }
243  return space.release();
244}
245
246OatFile* ImageSpace::OpenOatFile(const char* image_path, std::string* error_msg) const {
247  const ImageHeader& image_header = GetImageHeader();
248  std::string oat_filename = ImageHeader::GetOatLocationFromImageLocation(image_path);
249
250  OatFile* oat_file = OatFile::Open(oat_filename, oat_filename, image_header.GetOatDataBegin(),
251                                    !Runtime::Current()->IsCompiler(), error_msg);
252  if (oat_file == NULL) {
253    *error_msg = StringPrintf("Failed to open oat file '%s' referenced from image %s: %s",
254                              oat_filename.c_str(), GetName(), error_msg->c_str());
255    return nullptr;
256  }
257  uint32_t oat_checksum = oat_file->GetOatHeader().GetChecksum();
258  uint32_t image_oat_checksum = image_header.GetOatChecksum();
259  if (oat_checksum != image_oat_checksum) {
260    *error_msg = StringPrintf("Failed to match oat file checksum 0x%x to expected oat checksum 0x%x"
261                              " in image %s", oat_checksum, image_oat_checksum, GetName());
262    return nullptr;
263  }
264  return oat_file;
265}
266
267bool ImageSpace::ValidateOatFile(std::string* error_msg) const {
268  CHECK(oat_file_.get() != NULL);
269  for (const OatFile::OatDexFile* oat_dex_file : oat_file_->GetOatDexFiles()) {
270    const std::string& dex_file_location = oat_dex_file->GetDexFileLocation();
271    uint32_t dex_file_location_checksum;
272    if (!DexFile::GetChecksum(dex_file_location.c_str(), &dex_file_location_checksum, error_msg)) {
273      *error_msg = StringPrintf("Failed to get checksum of dex file '%s' referenced by image %s: "
274                                "%s", dex_file_location.c_str(), GetName(), error_msg->c_str());
275      return false;
276    }
277    if (dex_file_location_checksum != oat_dex_file->GetDexFileLocationChecksum()) {
278      *error_msg = StringPrintf("ValidateOatFile found checksum mismatch between oat file '%s' and "
279                                "dex file '%s' (0x%x != 0x%x)",
280                                oat_file_->GetLocation().c_str(), dex_file_location.c_str(),
281                                oat_dex_file->GetDexFileLocationChecksum(),
282                                dex_file_location_checksum);
283      return false;
284    }
285  }
286  return true;
287}
288
289OatFile* ImageSpace::ReleaseOatFile() {
290  CHECK(oat_file_.get() != NULL);
291  return oat_file_.release();
292}
293
294void ImageSpace::Dump(std::ostream& os) const {
295  os << GetType()
296      << " begin=" << reinterpret_cast<void*>(Begin())
297      << ",end=" << reinterpret_cast<void*>(End())
298      << ",size=" << PrettySize(Size())
299      << ",name=\"" << GetName() << "\"]";
300}
301
302}  // namespace space
303}  // namespace gc
304}  // namespace art
305