blob: 452af9075012503de1340872926beb4ea1a53b2c [file] [log] [blame]
Ian Rogers1d54e732013-05-02 21:10:01 -07001/*
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
Alex Light25396132014-08-27 15:37:23 -070019#include <dirent.h>
20#include <sys/types.h>
21
Alex Lighta59dd802014-07-02 16:28:08 -070022#include <random>
23
Brian Carlstrom56d947f2013-07-15 13:14:23 -070024#include "base/stl_util.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070025#include "base/unix_file/fd_file.h"
Narayan Kamathd1c606f2014-06-09 16:50:19 +010026#include "base/scoped_flock.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070027#include "gc/accounting/space_bitmap-inl.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070028#include "mirror/art_method.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070029#include "mirror/class-inl.h"
30#include "mirror/object-inl.h"
Brian Carlstrom56d947f2013-07-15 13:14:23 -070031#include "oat_file.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070032#include "os.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070033#include "space-inl.h"
34#include "utils.h"
35
36namespace art {
37namespace gc {
38namespace space {
39
Ian Rogersef7d42f2014-01-06 12:55:46 -080040Atomic<uint32_t> ImageSpace::bitmap_index_(0);
Ian Rogers1d54e732013-05-02 21:10:01 -070041
Narayan Kamath52f84882014-05-02 10:10:39 +010042ImageSpace::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) {
Mathieu Chartier590fee92013-09-13 13:46:47 -070047 DCHECK(live_bitmap != nullptr);
Mathieu Chartier31e89252013-08-28 11:29:12 -070048 live_bitmap_.reset(live_bitmap);
Ian Rogers1d54e732013-05-02 21:10:01 -070049}
50
Alex Lightcf4bf382014-07-24 11:29:14 -070051static 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
Alex Light25396132014-08-27 15:37:23 -070071// 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 }
Alex Light25396132014-08-27 15:37:23 -070092
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 }
Brian Carlstromdebdda02014-08-28 22:17:13 -0700106 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;
Alex Light25396132014-08-27 15:37:23 -0700111 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) {
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700119 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()) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700123 *error_msg = "Failed to generate image because no boot class path specified";
124 return false;
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700125 }
Alex Light25396132014-08-27 15:37:23 -0700126 // We should clean up so we are more likely to have room for the image.
127 if (Runtime::Current()->IsZygote()) {
Andreas Gampe3c13a792014-09-18 20:56:04 -0700128 LOG(INFO) << "Pruning dalvik-cache since we are generating an image and will need to recompile";
Alex Light25396132014-08-27 15:37:23 -0700129 PruneDexCache(image_isa);
130 }
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700131
Mathieu Chartier8bbc8c02013-07-31 16:27:01 -0700132 std::vector<std::string> arg_vector;
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700133
Tsu Chiang Chuang12e6d742014-05-22 10:22:25 -0700134 std::string dex2oat(Runtime::Current()->GetCompilerExecutable());
Mathieu Chartier08d7d442013-07-31 18:08:51 -0700135 arg_vector.push_back(dex2oat);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700136
137 std::string image_option_string("--image=");
Narayan Kamath52f84882014-05-02 10:10:39 +0100138 image_option_string += image_filename;
Mathieu Chartier8bbc8c02013-07-31 16:27:01 -0700139 arg_vector.push_back(image_option_string);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700140
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700141 for (size_t i = 0; i < boot_class_path.size(); i++) {
Mathieu Chartier8bbc8c02013-07-31 16:27:01 -0700142 arg_vector.push_back(std::string("--dex-file=") + boot_class_path[i]);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700143 }
144
145 std::string oat_file_option_string("--oat-file=");
Narayan Kamath52f84882014-05-02 10:10:39 +0100146 oat_file_option_string += image_filename;
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700147 oat_file_option_string.erase(oat_file_option_string.size() - 3);
148 oat_file_option_string += "oat";
Mathieu Chartier8bbc8c02013-07-31 16:27:01 -0700149 arg_vector.push_back(oat_file_option_string);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700150
Ian Rogers8afeb852014-04-02 14:55:49 -0700151 Runtime::Current()->AddCurrentRuntimeFeaturesAsDex2OatArguments(&arg_vector);
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700152 CHECK_EQ(image_isa, kRuntimeISA)
153 << "We should always be generating an image for the current isa.";
Ian Rogers8afeb852014-04-02 14:55:49 -0700154
Alex Lightcf4bf382014-07-24 11:29:14 -0700155 int32_t base_offset = ChooseRelocationOffsetDelta(ART_BASE_ADDRESS_MIN_DELTA,
156 ART_BASE_ADDRESS_MAX_DELTA);
157 LOG(INFO) << "Using an offset of 0x" << std::hex << base_offset << " from default "
158 << "art base address of 0x" << std::hex << ART_BASE_ADDRESS;
159 arg_vector.push_back(StringPrintf("--base=0x%x", ART_BASE_ADDRESS + base_offset));
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700160
Brian Carlstrom57309db2014-07-30 15:13:25 -0700161 if (!kIsTargetBuild) {
Mathieu Chartier8bbc8c02013-07-31 16:27:01 -0700162 arg_vector.push_back("--host");
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700163 }
164
Brian Carlstrom6449c622014-02-10 23:48:36 -0800165 const std::vector<std::string>& compiler_options = Runtime::Current()->GetImageCompilerOptions();
Brian Carlstrom2ec65202014-03-03 15:16:37 -0800166 for (size_t i = 0; i < compiler_options.size(); ++i) {
Brian Carlstrom6449c622014-02-10 23:48:36 -0800167 arg_vector.push_back(compiler_options[i].c_str());
168 }
169
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700170 std::string command_line(Join(arg_vector, ' '));
171 LOG(INFO) << "GenerateImage: " << command_line;
Brian Carlstrom6449c622014-02-10 23:48:36 -0800172 return Exec(arg_vector, error_msg);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700173}
174
Narayan Kamath52f84882014-05-02 10:10:39 +0100175bool ImageSpace::FindImageFilename(const char* image_location,
176 const InstructionSet image_isa,
Alex Lighta59dd802014-07-02 16:28:08 -0700177 std::string* system_filename,
178 bool* has_system,
179 std::string* cache_filename,
180 bool* dalvik_cache_exists,
Andreas Gampe3c13a792014-09-18 20:56:04 -0700181 bool* has_cache,
182 bool* is_global_cache) {
Alex Lighta59dd802014-07-02 16:28:08 -0700183 *has_system = false;
184 *has_cache = false;
Brian Carlstrom0e12bdc2014-05-14 17:44:28 -0700185 // image_location = /system/framework/boot.art
186 // system_image_location = /system/framework/<image_isa>/boot.art
187 std::string system_image_filename(GetSystemImageFilename(image_location, image_isa));
188 if (OS::FileExists(system_image_filename.c_str())) {
Alex Lighta59dd802014-07-02 16:28:08 -0700189 *system_filename = system_image_filename;
190 *has_system = true;
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700191 }
Narayan Kamath52f84882014-05-02 10:10:39 +0100192
Alex Lighta59dd802014-07-02 16:28:08 -0700193 bool have_android_data = false;
194 *dalvik_cache_exists = false;
195 std::string dalvik_cache;
196 GetDalvikCache(GetInstructionSetString(image_isa), true, &dalvik_cache,
Andreas Gampe3c13a792014-09-18 20:56:04 -0700197 &have_android_data, dalvik_cache_exists, is_global_cache);
Narayan Kamath52f84882014-05-02 10:10:39 +0100198
Alex Lighta59dd802014-07-02 16:28:08 -0700199 if (have_android_data && *dalvik_cache_exists) {
200 // Always set output location even if it does not exist,
201 // so that the caller knows where to create the image.
202 //
203 // image_location = /system/framework/boot.art
204 // *image_filename = /data/dalvik-cache/<image_isa>/boot.art
205 std::string error_msg;
206 if (!GetDalvikCacheFilename(image_location, dalvik_cache.c_str(), cache_filename, &error_msg)) {
207 LOG(WARNING) << error_msg;
208 return *has_system;
209 }
210 *has_cache = OS::FileExists(cache_filename->c_str());
211 }
212 return *has_system || *has_cache;
213}
214
215static bool ReadSpecificImageHeader(const char* filename, ImageHeader* image_header) {
216 std::unique_ptr<File> image_file(OS::OpenFileForReading(filename));
217 if (image_file.get() == nullptr) {
218 return false;
219 }
220 const bool success = image_file->ReadFully(image_header, sizeof(ImageHeader));
221 if (!success || !image_header->IsValid()) {
222 return false;
223 }
224 return true;
225}
226
Alex Light6e183f22014-07-18 14:57:04 -0700227// Relocate the image at image_location to dest_filename and relocate it by a random amount.
228static bool RelocateImage(const char* image_location, const char* dest_filename,
Alex Lighta59dd802014-07-02 16:28:08 -0700229 InstructionSet isa, std::string* error_msg) {
Alex Light25396132014-08-27 15:37:23 -0700230 // We should clean up so we are more likely to have room for the image.
231 if (Runtime::Current()->IsZygote()) {
232 LOG(INFO) << "Pruning dalvik-cache since we are relocating an image and will need to recompile";
233 PruneDexCache(isa);
234 }
235
Alex Lighta59dd802014-07-02 16:28:08 -0700236 std::string patchoat(Runtime::Current()->GetPatchoatExecutable());
237
238 std::string input_image_location_arg("--input-image-location=");
239 input_image_location_arg += image_location;
240
241 std::string output_image_filename_arg("--output-image-file=");
242 output_image_filename_arg += dest_filename;
243
244 std::string input_oat_location_arg("--input-oat-location=");
245 input_oat_location_arg += ImageHeader::GetOatLocationFromImageLocation(image_location);
246
247 std::string output_oat_filename_arg("--output-oat-file=");
248 output_oat_filename_arg += ImageHeader::GetOatLocationFromImageLocation(dest_filename);
249
250 std::string instruction_set_arg("--instruction-set=");
251 instruction_set_arg += GetInstructionSetString(isa);
252
253 std::string base_offset_arg("--base-offset-delta=");
254 StringAppendF(&base_offset_arg, "%d", ChooseRelocationOffsetDelta(ART_BASE_ADDRESS_MIN_DELTA,
255 ART_BASE_ADDRESS_MAX_DELTA));
256
257 std::vector<std::string> argv;
258 argv.push_back(patchoat);
259
260 argv.push_back(input_image_location_arg);
261 argv.push_back(output_image_filename_arg);
262
263 argv.push_back(input_oat_location_arg);
264 argv.push_back(output_oat_filename_arg);
265
266 argv.push_back(instruction_set_arg);
267 argv.push_back(base_offset_arg);
268
269 std::string command_line(Join(argv, ' '));
270 LOG(INFO) << "RelocateImage: " << command_line;
271 return Exec(argv, error_msg);
272}
273
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700274static ImageHeader* ReadSpecificImageHeader(const char* filename, std::string* error_msg) {
Alex Lighta59dd802014-07-02 16:28:08 -0700275 std::unique_ptr<ImageHeader> hdr(new ImageHeader);
276 if (!ReadSpecificImageHeader(filename, hdr.get())) {
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700277 *error_msg = StringPrintf("Unable to read image header for %s", filename);
Alex Lighta59dd802014-07-02 16:28:08 -0700278 return nullptr;
279 }
280 return hdr.release();
Narayan Kamath52f84882014-05-02 10:10:39 +0100281}
282
283ImageHeader* ImageSpace::ReadImageHeaderOrDie(const char* image_location,
284 const InstructionSet image_isa) {
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700285 std::string error_msg;
286 ImageHeader* image_header = ReadImageHeader(image_location, image_isa, &error_msg);
287 if (image_header == nullptr) {
288 LOG(FATAL) << error_msg;
289 }
290 return image_header;
291}
292
293ImageHeader* ImageSpace::ReadImageHeader(const char* image_location,
294 const InstructionSet image_isa,
295 std::string* error_msg) {
Alex Lighta59dd802014-07-02 16:28:08 -0700296 std::string system_filename;
297 bool has_system = false;
298 std::string cache_filename;
299 bool has_cache = false;
300 bool dalvik_cache_exists = false;
Andreas Gampe3c13a792014-09-18 20:56:04 -0700301 bool is_global_cache = false;
Alex Lighta59dd802014-07-02 16:28:08 -0700302 if (FindImageFilename(image_location, image_isa, &system_filename, &has_system,
Andreas Gampe3c13a792014-09-18 20:56:04 -0700303 &cache_filename, &dalvik_cache_exists, &has_cache, &is_global_cache)) {
Alex Lighta59dd802014-07-02 16:28:08 -0700304 if (Runtime::Current()->ShouldRelocate()) {
305 if (has_system && has_cache) {
306 std::unique_ptr<ImageHeader> sys_hdr(new ImageHeader);
307 std::unique_ptr<ImageHeader> cache_hdr(new ImageHeader);
308 if (!ReadSpecificImageHeader(system_filename.c_str(), sys_hdr.get())) {
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700309 *error_msg = StringPrintf("Unable to read image header for %s at %s",
310 image_location, system_filename.c_str());
Alex Lighta59dd802014-07-02 16:28:08 -0700311 return nullptr;
312 }
313 if (!ReadSpecificImageHeader(cache_filename.c_str(), cache_hdr.get())) {
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700314 *error_msg = StringPrintf("Unable to read image header for %s at %s",
315 image_location, cache_filename.c_str());
Alex Lighta59dd802014-07-02 16:28:08 -0700316 return nullptr;
317 }
318 if (sys_hdr->GetOatChecksum() != cache_hdr->GetOatChecksum()) {
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700319 *error_msg = StringPrintf("Unable to find a relocated version of image file %s",
320 image_location);
Alex Lighta59dd802014-07-02 16:28:08 -0700321 return nullptr;
322 }
323 return cache_hdr.release();
324 } else if (!has_cache) {
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700325 *error_msg = StringPrintf("Unable to find a relocated version of image file %s",
326 image_location);
Alex Lighta59dd802014-07-02 16:28:08 -0700327 return nullptr;
328 } else if (!has_system && has_cache) {
329 // This can probably just use the cache one.
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700330 return ReadSpecificImageHeader(cache_filename.c_str(), error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -0700331 }
332 } else {
333 // We don't want to relocate, Just pick the appropriate one if we have it and return.
334 if (has_system && has_cache) {
335 // We want the cache if the checksum matches, otherwise the system.
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700336 std::unique_ptr<ImageHeader> system(ReadSpecificImageHeader(system_filename.c_str(),
337 error_msg));
338 std::unique_ptr<ImageHeader> cache(ReadSpecificImageHeader(cache_filename.c_str(),
339 error_msg));
Alex Lighta59dd802014-07-02 16:28:08 -0700340 if (system.get() == nullptr ||
341 (cache.get() != nullptr && cache->GetOatChecksum() == system->GetOatChecksum())) {
342 return cache.release();
343 } else {
344 return system.release();
345 }
346 } else if (has_system) {
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700347 return ReadSpecificImageHeader(system_filename.c_str(), error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -0700348 } else if (has_cache) {
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700349 return ReadSpecificImageHeader(cache_filename.c_str(), error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -0700350 }
Narayan Kamath52f84882014-05-02 10:10:39 +0100351 }
Narayan Kamath52f84882014-05-02 10:10:39 +0100352 }
353
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700354 *error_msg = StringPrintf("Unable to find image file for %s", image_location);
Narayan Kamath52f84882014-05-02 10:10:39 +0100355 return nullptr;
356}
357
Alex Lighta59dd802014-07-02 16:28:08 -0700358static bool ChecksumsMatch(const char* image_a, const char* image_b) {
359 ImageHeader hdr_a;
360 ImageHeader hdr_b;
361 return ReadSpecificImageHeader(image_a, &hdr_a) && ReadSpecificImageHeader(image_b, &hdr_b)
362 && hdr_a.GetOatChecksum() == hdr_b.GetOatChecksum();
363}
364
Andreas Gampe3c13a792014-09-18 20:56:04 -0700365static bool ImageCreationAllowed(bool is_global_cache, std::string* error_msg) {
366 // Anyone can write into a "local" cache.
367 if (!is_global_cache) {
368 return true;
369 }
370
371 // Only the zygote is allowed to create the global boot image.
372 if (Runtime::Current()->IsZygote()) {
373 return true;
374 }
375
376 *error_msg = "Only the zygote can create the global boot image.";
377 return false;
378}
379
Narayan Kamath52f84882014-05-02 10:10:39 +0100380ImageSpace* ImageSpace::Create(const char* image_location,
Alex Light64ad14d2014-08-19 14:23:13 -0700381 const InstructionSet image_isa,
382 std::string* error_msg) {
Alex Lighta59dd802014-07-02 16:28:08 -0700383 std::string system_filename;
384 bool has_system = false;
385 std::string cache_filename;
386 bool has_cache = false;
387 bool dalvik_cache_exists = false;
Andreas Gampe3c13a792014-09-18 20:56:04 -0700388 bool is_global_cache = true;
Alex Lighta59dd802014-07-02 16:28:08 -0700389 const bool found_image = FindImageFilename(image_location, image_isa, &system_filename,
390 &has_system, &cache_filename, &dalvik_cache_exists,
Andreas Gampe3c13a792014-09-18 20:56:04 -0700391 &has_cache, &is_global_cache);
Narayan Kamathd1c606f2014-06-09 16:50:19 +0100392
Alex Lighta59dd802014-07-02 16:28:08 -0700393 ImageSpace* space;
394 bool relocate = Runtime::Current()->ShouldRelocate();
Alex Light64ad14d2014-08-19 14:23:13 -0700395 bool can_compile = Runtime::Current()->IsImageDex2OatEnabled();
Narayan Kamathd1c606f2014-06-09 16:50:19 +0100396 if (found_image) {
Alex Lighta59dd802014-07-02 16:28:08 -0700397 const std::string* image_filename;
398 bool is_system = false;
399 bool relocated_version_used = false;
400 if (relocate) {
Alex Light64ad14d2014-08-19 14:23:13 -0700401 if (!dalvik_cache_exists) {
402 *error_msg = StringPrintf("Requiring relocation for image '%s' at '%s' but we do not have "
403 "any dalvik_cache to find/place it in.",
404 image_location, system_filename.c_str());
405 return nullptr;
406 }
Alex Lighta59dd802014-07-02 16:28:08 -0700407 if (has_system) {
408 if (has_cache && ChecksumsMatch(system_filename.c_str(), cache_filename.c_str())) {
409 // We already have a relocated version
410 image_filename = &cache_filename;
411 relocated_version_used = true;
412 } else {
413 // We cannot have a relocated version, Relocate the system one and use it.
Andreas Gampe3c13a792014-09-18 20:56:04 -0700414
415 std::string reason;
416 bool success;
417
418 // Check whether we are allowed to relocate.
419 if (!can_compile) {
420 reason = "Image dex2oat disabled by -Xnoimage-dex2oat.";
421 success = false;
422 } else if (!ImageCreationAllowed(is_global_cache, &reason)) {
423 // Whether we can write to the cache.
424 success = false;
425 } else {
426 // Try to relocate.
427 success = RelocateImage(image_location, cache_filename.c_str(), image_isa, &reason);
428 }
429
430 if (success) {
Alex Lighta59dd802014-07-02 16:28:08 -0700431 relocated_version_used = true;
432 image_filename = &cache_filename;
433 } else {
Andreas Gampe3c13a792014-09-18 20:56:04 -0700434 *error_msg = StringPrintf("Unable to relocate image '%s' from '%s' to '%s': %s",
Alex Light64ad14d2014-08-19 14:23:13 -0700435 image_location, system_filename.c_str(),
436 cache_filename.c_str(), reason.c_str());
Alex Lighta59dd802014-07-02 16:28:08 -0700437 return nullptr;
438 }
439 }
440 } else {
441 CHECK(has_cache);
442 // We can just use cache's since it should be fine. This might or might not be relocated.
443 image_filename = &cache_filename;
444 }
445 } else {
446 if (has_system && has_cache) {
447 // Check they have the same cksum. If they do use the cache. Otherwise system.
448 if (ChecksumsMatch(system_filename.c_str(), cache_filename.c_str())) {
449 image_filename = &cache_filename;
450 relocated_version_used = true;
451 } else {
452 image_filename = &system_filename;
Alex Light1a762132014-07-31 09:32:13 -0700453 is_system = true;
Alex Lighta59dd802014-07-02 16:28:08 -0700454 }
455 } else if (has_system) {
456 image_filename = &system_filename;
Alex Light1a762132014-07-31 09:32:13 -0700457 is_system = true;
Alex Lighta59dd802014-07-02 16:28:08 -0700458 } else {
459 CHECK(has_cache);
460 image_filename = &cache_filename;
461 }
462 }
463 {
464 // Note that we must not use the file descriptor associated with
465 // ScopedFlock::GetFile to Init the image file. We want the file
466 // descriptor (and the associated exclusive lock) to be released when
467 // we leave Create.
468 ScopedFlock image_lock;
Alex Light64ad14d2014-08-19 14:23:13 -0700469 image_lock.Init(image_filename->c_str(), error_msg);
Alex Lightb6cabc12014-08-21 09:45:00 -0700470 VLOG(startup) << "Using image file " << image_filename->c_str() << " for image location "
471 << image_location;
Alex Lightb93637a2014-07-31 10:48:46 -0700472 // If we are in /system we can assume the image is good. We can also
473 // assume this if we are using a relocated image (i.e. image checksum
474 // matches) since this is only different by the offset. We need this to
475 // make sure that host tests continue to work.
Alex Lighta59dd802014-07-02 16:28:08 -0700476 space = ImageSpace::Init(image_filename->c_str(), image_location,
Alex Light64ad14d2014-08-19 14:23:13 -0700477 !(is_system || relocated_version_used), error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -0700478 }
Narayan Kamath52f84882014-05-02 10:10:39 +0100479 if (space != nullptr) {
480 return space;
481 }
482
Alex Lighta59dd802014-07-02 16:28:08 -0700483 // If the /system file exists, it should be up-to-date, don't try to generate it. Same if it is
484 // a relocated copy from something in /system (i.e. checksum's match).
485 // Otherwise, log a warning and fall through to GenerateImage.
486 if (relocated_version_used) {
487 LOG(FATAL) << "Attempted to use relocated version of " << image_location << " "
488 << "at " << cache_filename << " generated from " << system_filename << " "
489 << "but image failed to load: " << error_msg;
490 return nullptr;
491 } else if (is_system) {
Alex Light64ad14d2014-08-19 14:23:13 -0700492 *error_msg = StringPrintf("Failed to load /system image '%s': %s",
493 image_filename->c_str(), error_msg->c_str());
Narayan Kamath52f84882014-05-02 10:10:39 +0100494 return nullptr;
Mathieu Chartierc7cb1902014-03-05 14:41:03 -0800495 } else {
Alex Light64ad14d2014-08-19 14:23:13 -0700496 LOG(WARNING) << *error_msg;
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700497 }
498 }
Narayan Kamath52f84882014-05-02 10:10:39 +0100499
Alex Light64ad14d2014-08-19 14:23:13 -0700500 if (!can_compile) {
501 *error_msg = "Not attempting to compile image because -Xnoimage-dex2oat";
502 return nullptr;
503 } else if (!dalvik_cache_exists) {
504 *error_msg = StringPrintf("No place to put generated image.");
505 return nullptr;
Andreas Gampe3c13a792014-09-18 20:56:04 -0700506 } else if (!ImageCreationAllowed(is_global_cache, error_msg)) {
507 return nullptr;
Alex Light25396132014-08-27 15:37:23 -0700508 } else if (!GenerateImage(cache_filename, image_isa, error_msg)) {
Alex Light64ad14d2014-08-19 14:23:13 -0700509 *error_msg = StringPrintf("Failed to generate image '%s': %s",
510 cache_filename.c_str(), error_msg->c_str());
511 return nullptr;
512 } else {
Alex Lighta59dd802014-07-02 16:28:08 -0700513 // Note that we must not use the file descriptor associated with
514 // ScopedFlock::GetFile to Init the image file. We want the file
515 // descriptor (and the associated exclusive lock) to be released when
516 // we leave Create.
517 ScopedFlock image_lock;
Alex Light64ad14d2014-08-19 14:23:13 -0700518 image_lock.Init(cache_filename.c_str(), error_msg);
519 space = ImageSpace::Init(cache_filename.c_str(), image_location, true, error_msg);
520 if (space == nullptr) {
521 *error_msg = StringPrintf("Failed to load generated image '%s': %s",
522 cache_filename.c_str(), error_msg->c_str());
523 }
524 return space;
Alex Lighta59dd802014-07-02 16:28:08 -0700525 }
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700526}
527
Mathieu Chartier31e89252013-08-28 11:29:12 -0700528void ImageSpace::VerifyImageAllocations() {
Ian Rogers13735952014-10-08 12:43:28 -0700529 uint8_t* current = Begin() + RoundUp(sizeof(ImageHeader), kObjectAlignment);
Mathieu Chartier31e89252013-08-28 11:29:12 -0700530 while (current < End()) {
531 DCHECK_ALIGNED(current, kObjectAlignment);
Ian Rogersef7d42f2014-01-06 12:55:46 -0800532 mirror::Object* obj = reinterpret_cast<mirror::Object*>(current);
Mathieu Chartier31e89252013-08-28 11:29:12 -0700533 CHECK(live_bitmap_->Test(obj));
534 CHECK(obj->GetClass() != nullptr) << "Image object at address " << obj << " has null class";
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -0700535 if (kUseBakerOrBrooksReadBarrier) {
536 obj->AssertReadBarrierPointer();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800537 }
Mathieu Chartier31e89252013-08-28 11:29:12 -0700538 current += RoundUp(obj->SizeOf(), kObjectAlignment);
539 }
540}
541
Narayan Kamath52f84882014-05-02 10:10:39 +0100542ImageSpace* ImageSpace::Init(const char* image_filename, const char* image_location,
543 bool validate_oat_file, std::string* error_msg) {
544 CHECK(image_filename != nullptr);
545 CHECK(image_location != nullptr);
Ian Rogers1d54e732013-05-02 21:10:01 -0700546
547 uint64_t start_time = 0;
548 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
549 start_time = NanoTime();
Narayan Kamath52f84882014-05-02 10:10:39 +0100550 LOG(INFO) << "ImageSpace::Init entering image_filename=" << image_filename;
Ian Rogers1d54e732013-05-02 21:10:01 -0700551 }
552
Ian Rogers700a4022014-05-19 16:49:03 -0700553 std::unique_ptr<File> file(OS::OpenFileForReading(image_filename));
Ian Rogers1d54e732013-05-02 21:10:01 -0700554 if (file.get() == NULL) {
Narayan Kamath52f84882014-05-02 10:10:39 +0100555 *error_msg = StringPrintf("Failed to open '%s'", image_filename);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700556 return nullptr;
Ian Rogers1d54e732013-05-02 21:10:01 -0700557 }
558 ImageHeader image_header;
559 bool success = file->ReadFully(&image_header, sizeof(image_header));
560 if (!success || !image_header.IsValid()) {
Narayan Kamath52f84882014-05-02 10:10:39 +0100561 *error_msg = StringPrintf("Invalid image header in '%s'", image_filename);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700562 return nullptr;
Ian Rogers1d54e732013-05-02 21:10:01 -0700563 }
Mathieu Chartier31e89252013-08-28 11:29:12 -0700564
565 // Note: The image header is part of the image due to mmap page alignment required of offset.
Ian Rogers700a4022014-05-19 16:49:03 -0700566 std::unique_ptr<MemMap> map(MemMap::MapFileAtAddress(image_header.GetImageBegin(),
Mathieu Chartier31e89252013-08-28 11:29:12 -0700567 image_header.GetImageSize(),
Ian Rogers1d54e732013-05-02 21:10:01 -0700568 PROT_READ | PROT_WRITE,
Hiroshi Yamauchi4fb5df82014-03-13 15:10:27 -0700569 MAP_PRIVATE,
Ian Rogers1d54e732013-05-02 21:10:01 -0700570 file->Fd(),
571 0,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700572 false,
Narayan Kamath52f84882014-05-02 10:10:39 +0100573 image_filename,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700574 error_msg));
Ian Rogers1d54e732013-05-02 21:10:01 -0700575 if (map.get() == NULL) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700576 DCHECK(!error_msg->empty());
577 return nullptr;
Ian Rogers1d54e732013-05-02 21:10:01 -0700578 }
579 CHECK_EQ(image_header.GetImageBegin(), map->Begin());
580 DCHECK_EQ(0, memcmp(&image_header, map->Begin(), sizeof(ImageHeader)));
581
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700582 std::unique_ptr<MemMap> image_map(
583 MemMap::MapFileAtAddress(nullptr, image_header.GetImageBitmapSize(),
584 PROT_READ, MAP_PRIVATE,
585 file->Fd(), image_header.GetBitmapOffset(),
586 false,
587 image_filename,
588 error_msg));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700589 if (image_map.get() == nullptr) {
590 *error_msg = StringPrintf("Failed to map image bitmap: %s", error_msg->c_str());
591 return nullptr;
592 }
Ian Rogers3e5cf302014-05-20 16:40:37 -0700593 uint32_t bitmap_index = bitmap_index_.FetchAndAddSequentiallyConsistent(1);
Narayan Kamath52f84882014-05-02 10:10:39 +0100594 std::string bitmap_name(StringPrintf("imagespace %s live-bitmap %u", image_filename,
Mathieu Chartier31e89252013-08-28 11:29:12 -0700595 bitmap_index));
Ian Rogers700a4022014-05-19 16:49:03 -0700596 std::unique_ptr<accounting::ContinuousSpaceBitmap> bitmap(
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -0700597 accounting::ContinuousSpaceBitmap::CreateFromMemMap(bitmap_name, image_map.release(),
Ian Rogers13735952014-10-08 12:43:28 -0700598 reinterpret_cast<uint8_t*>(map->Begin()),
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -0700599 map->Size()));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700600 if (bitmap.get() == nullptr) {
601 *error_msg = StringPrintf("Could not create bitmap '%s'", bitmap_name.c_str());
602 return nullptr;
603 }
Mathieu Chartier31e89252013-08-28 11:29:12 -0700604
Ian Rogers700a4022014-05-19 16:49:03 -0700605 std::unique_ptr<ImageSpace> space(new ImageSpace(image_filename, image_location,
Narayan Kamath52f84882014-05-02 10:10:39 +0100606 map.release(), bitmap.release()));
Hiroshi Yamauchibd0fb612014-05-20 13:46:00 -0700607
608 // VerifyImageAllocations() will be called later in Runtime::Init()
609 // as some class roots like ArtMethod::java_lang_reflect_ArtMethod_
610 // and ArtField::java_lang_reflect_ArtField_, which are used from
611 // Object::SizeOf() which VerifyImageAllocations() calls, are not
612 // set yet at this point.
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700613
Narayan Kamath52f84882014-05-02 10:10:39 +0100614 space->oat_file_.reset(space->OpenOatFile(image_filename, error_msg));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700615 if (space->oat_file_.get() == nullptr) {
616 DCHECK(!error_msg->empty());
617 return nullptr;
Ian Rogers1d54e732013-05-02 21:10:01 -0700618 }
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700619
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700620 if (validate_oat_file && !space->ValidateOatFile(error_msg)) {
621 DCHECK(!error_msg->empty());
622 return nullptr;
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700623 }
624
Vladimir Marko7624d252014-05-02 14:40:15 +0100625 Runtime* runtime = Runtime::Current();
626 runtime->SetInstructionSet(space->oat_file_->GetOatHeader().GetInstructionSet());
627
628 mirror::Object* resolution_method = image_header.GetImageRoot(ImageHeader::kResolutionMethod);
629 runtime->SetResolutionMethod(down_cast<mirror::ArtMethod*>(resolution_method));
630 mirror::Object* imt_conflict_method = image_header.GetImageRoot(ImageHeader::kImtConflictMethod);
631 runtime->SetImtConflictMethod(down_cast<mirror::ArtMethod*>(imt_conflict_method));
632 mirror::Object* default_imt = image_header.GetImageRoot(ImageHeader::kDefaultImt);
633 runtime->SetDefaultImt(down_cast<mirror::ObjectArray<mirror::ArtMethod>*>(default_imt));
634
635 mirror::Object* callee_save_method = image_header.GetImageRoot(ImageHeader::kCalleeSaveMethod);
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700636 runtime->SetCalleeSaveMethod(down_cast<mirror::ArtMethod*>(callee_save_method),
637 Runtime::kSaveAll);
Vladimir Marko7624d252014-05-02 14:40:15 +0100638 callee_save_method = image_header.GetImageRoot(ImageHeader::kRefsOnlySaveMethod);
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700639 runtime->SetCalleeSaveMethod(down_cast<mirror::ArtMethod*>(callee_save_method),
640 Runtime::kRefsOnly);
Vladimir Marko7624d252014-05-02 14:40:15 +0100641 callee_save_method = image_header.GetImageRoot(ImageHeader::kRefsAndArgsSaveMethod);
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700642 runtime->SetCalleeSaveMethod(down_cast<mirror::ArtMethod*>(callee_save_method),
643 Runtime::kRefsAndArgs);
Vladimir Marko7624d252014-05-02 14:40:15 +0100644
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700645 if (VLOG_IS_ON(heap) || VLOG_IS_ON(startup)) {
646 LOG(INFO) << "ImageSpace::Init exiting (" << PrettyDuration(NanoTime() - start_time)
647 << ") " << *space.get();
648 }
649 return space.release();
650}
651
Nicolas Geoffray9583fbc2014-02-28 15:21:07 +0000652OatFile* ImageSpace::OpenOatFile(const char* image_path, std::string* error_msg) const {
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700653 const ImageHeader& image_header = GetImageHeader();
Nicolas Geoffray9583fbc2014-02-28 15:21:07 +0000654 std::string oat_filename = ImageHeader::GetOatLocationFromImageLocation(image_path);
655
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700656 OatFile* oat_file = OatFile::Open(oat_filename, oat_filename, image_header.GetOatDataBegin(),
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700657 !Runtime::Current()->IsCompiler(), error_msg);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700658 if (oat_file == NULL) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700659 *error_msg = StringPrintf("Failed to open oat file '%s' referenced from image %s: %s",
660 oat_filename.c_str(), GetName(), error_msg->c_str());
661 return nullptr;
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700662 }
663 uint32_t oat_checksum = oat_file->GetOatHeader().GetChecksum();
664 uint32_t image_oat_checksum = image_header.GetOatChecksum();
665 if (oat_checksum != image_oat_checksum) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700666 *error_msg = StringPrintf("Failed to match oat file checksum 0x%x to expected oat checksum 0x%x"
667 " in image %s", oat_checksum, image_oat_checksum, GetName());
668 return nullptr;
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700669 }
Alex Lighta59dd802014-07-02 16:28:08 -0700670 int32_t image_patch_delta = image_header.GetPatchDelta();
671 int32_t oat_patch_delta = oat_file->GetOatHeader().GetImagePatchDelta();
672 if (oat_patch_delta != image_patch_delta) {
673 // We should have already relocated by this point. Bail out.
674 *error_msg = StringPrintf("Failed to match oat file patch delta %d to expected patch delta %d "
675 "in image %s", oat_patch_delta, image_patch_delta, GetName());
676 return nullptr;
677 }
678
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700679 return oat_file;
680}
681
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700682bool ImageSpace::ValidateOatFile(std::string* error_msg) const {
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700683 CHECK(oat_file_.get() != NULL);
Mathieu Chartier31e89252013-08-28 11:29:12 -0700684 for (const OatFile::OatDexFile* oat_dex_file : oat_file_->GetOatDexFiles()) {
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700685 const std::string& dex_file_location = oat_dex_file->GetDexFileLocation();
686 uint32_t dex_file_location_checksum;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700687 if (!DexFile::GetChecksum(dex_file_location.c_str(), &dex_file_location_checksum, error_msg)) {
688 *error_msg = StringPrintf("Failed to get checksum of dex file '%s' referenced by image %s: "
689 "%s", dex_file_location.c_str(), GetName(), error_msg->c_str());
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700690 return false;
691 }
692 if (dex_file_location_checksum != oat_dex_file->GetDexFileLocationChecksum()) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700693 *error_msg = StringPrintf("ValidateOatFile found checksum mismatch between oat file '%s' and "
694 "dex file '%s' (0x%x != 0x%x)",
695 oat_file_->GetLocation().c_str(), dex_file_location.c_str(),
696 oat_dex_file->GetDexFileLocationChecksum(),
697 dex_file_location_checksum);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700698 return false;
699 }
700 }
701 return true;
702}
703
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700704const OatFile* ImageSpace::GetOatFile() const {
705 return oat_file_.get();
706}
707
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700708OatFile* ImageSpace::ReleaseOatFile() {
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700709 CHECK(oat_file_.get() != NULL);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700710 return oat_file_.release();
Ian Rogers1d54e732013-05-02 21:10:01 -0700711}
712
Ian Rogers1d54e732013-05-02 21:10:01 -0700713void ImageSpace::Dump(std::ostream& os) const {
714 os << GetType()
Mathieu Chartier590fee92013-09-13 13:46:47 -0700715 << " begin=" << reinterpret_cast<void*>(Begin())
Ian Rogers1d54e732013-05-02 21:10:01 -0700716 << ",end=" << reinterpret_cast<void*>(End())
717 << ",size=" << PrettySize(Size())
718 << ",name=\"" << GetName() << "\"]";
719}
720
721} // namespace space
722} // namespace gc
723} // namespace art