blob: 0c06c386b5e63f35a1961e402924b0dcc0775ca4 [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>
Mathieu Chartierceb07b32015-12-10 09:33:21 -080020#include <lz4.h>
21#include <random>
Andreas Gampe70be1fb2014-10-31 16:45:19 -070022#include <sys/statvfs.h>
Alex Light25396132014-08-27 15:37:23 -070023#include <sys/types.h>
Narayan Kamath5a2be3f2015-02-16 13:51:51 +000024#include <unistd.h>
Alex Light25396132014-08-27 15:37:23 -070025
Mathieu Chartiere401d142015-04-22 13:56:20 -070026#include "art_method.h"
Ian Rogersc7dd2952014-10-21 23:31:19 -070027#include "base/macros.h"
Brian Carlstrom56d947f2013-07-15 13:14:23 -070028#include "base/stl_util.h"
Narayan Kamathd1c606f2014-06-09 16:50:19 +010029#include "base/scoped_flock.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010030#include "base/time_utils.h"
31#include "base/unix_file/fd_file.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070032#include "gc/accounting/space_bitmap-inl.h"
Mathieu Chartier4a26f172016-01-26 14:26:18 -080033#include "image-inl.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070034#include "mirror/class-inl.h"
35#include "mirror/object-inl.h"
Brian Carlstrom56d947f2013-07-15 13:14:23 -070036#include "oat_file.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070037#include "os.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070038#include "space-inl.h"
39#include "utils.h"
40
41namespace art {
42namespace gc {
43namespace space {
44
Ian Rogersef7d42f2014-01-06 12:55:46 -080045Atomic<uint32_t> ImageSpace::bitmap_index_(0);
Ian Rogers1d54e732013-05-02 21:10:01 -070046
Jeff Haodcdc85b2015-12-04 14:06:18 -080047ImageSpace::ImageSpace(const std::string& image_filename,
48 const char* image_location,
49 MemMap* mem_map,
50 accounting::ContinuousSpaceBitmap* live_bitmap,
Mathieu Chartier2d124ec2016-01-05 18:03:15 -080051 uint8_t* end)
52 : MemMapSpace(image_filename,
53 mem_map,
54 mem_map->Begin(),
55 end,
56 end,
Narayan Kamath52f84882014-05-02 10:10:39 +010057 kGcRetentionPolicyNeverCollect),
Jeff Haodcdc85b2015-12-04 14:06:18 -080058 oat_file_non_owned_(nullptr),
Mathieu Chartier2d124ec2016-01-05 18:03:15 -080059 image_location_(image_location) {
Mathieu Chartier590fee92013-09-13 13:46:47 -070060 DCHECK(live_bitmap != nullptr);
Mathieu Chartier31e89252013-08-28 11:29:12 -070061 live_bitmap_.reset(live_bitmap);
Ian Rogers1d54e732013-05-02 21:10:01 -070062}
63
Alex Lightcf4bf382014-07-24 11:29:14 -070064static int32_t ChooseRelocationOffsetDelta(int32_t min_delta, int32_t max_delta) {
65 CHECK_ALIGNED(min_delta, kPageSize);
66 CHECK_ALIGNED(max_delta, kPageSize);
67 CHECK_LT(min_delta, max_delta);
68
Alex Light15324762015-11-19 11:03:10 -080069 int32_t r = GetRandomNumber<int32_t>(min_delta, max_delta);
Alex Lightcf4bf382014-07-24 11:29:14 -070070 if (r % 2 == 0) {
71 r = RoundUp(r, kPageSize);
72 } else {
73 r = RoundDown(r, kPageSize);
74 }
75 CHECK_LE(min_delta, r);
76 CHECK_GE(max_delta, r);
77 CHECK_ALIGNED(r, kPageSize);
78 return r;
79}
80
Alex Light25396132014-08-27 15:37:23 -070081// We are relocating or generating the core image. We should get rid of everything. It is all
Andreas Gampe8db9dcd2014-11-09 18:14:30 -080082// out-of-date. We also don't really care if this fails since it is just a convenience.
Alex Light25396132014-08-27 15:37:23 -070083// Adapted from prune_dex_cache(const char* subdir) in frameworks/native/cmds/installd/commands.c
84// Note this should only be used during first boot.
Narayan Kamath28bc9872014-11-07 17:46:28 +000085static void RealPruneDalvikCache(const std::string& cache_dir_path);
Andreas Gampe8db9dcd2014-11-09 18:14:30 -080086
Narayan Kamath28bc9872014-11-07 17:46:28 +000087static void PruneDalvikCache(InstructionSet isa) {
Alex Light25396132014-08-27 15:37:23 -070088 CHECK_NE(isa, kNone);
Andreas Gampe8db9dcd2014-11-09 18:14:30 -080089 // Prune the base /data/dalvik-cache.
Narayan Kamath28bc9872014-11-07 17:46:28 +000090 RealPruneDalvikCache(GetDalvikCacheOrDie(".", false));
Andreas Gampe8db9dcd2014-11-09 18:14:30 -080091 // Prune /data/dalvik-cache/<isa>.
Narayan Kamath28bc9872014-11-07 17:46:28 +000092 RealPruneDalvikCache(GetDalvikCacheOrDie(GetInstructionSetString(isa), false));
Alex Light25396132014-08-27 15:37:23 -070093}
Andreas Gampe8db9dcd2014-11-09 18:14:30 -080094
Narayan Kamath28bc9872014-11-07 17:46:28 +000095static void RealPruneDalvikCache(const std::string& cache_dir_path) {
Alex Light25396132014-08-27 15:37:23 -070096 if (!OS::DirectoryExists(cache_dir_path.c_str())) {
97 return;
98 }
99 DIR* cache_dir = opendir(cache_dir_path.c_str());
100 if (cache_dir == nullptr) {
101 PLOG(WARNING) << "Unable to open " << cache_dir_path << " to delete it's contents";
102 return;
103 }
Alex Light25396132014-08-27 15:37:23 -0700104
105 for (struct dirent* de = readdir(cache_dir); de != nullptr; de = readdir(cache_dir)) {
106 const char* name = de->d_name;
107 if (strcmp(name, ".") == 0 || strcmp(name, "..") == 0) {
108 continue;
109 }
Andreas Gampe8db9dcd2014-11-09 18:14:30 -0800110 // We only want to delete regular files and symbolic links.
111 if (de->d_type != DT_REG && de->d_type != DT_LNK) {
Alex Light25396132014-08-27 15:37:23 -0700112 if (de->d_type != DT_DIR) {
113 // We do expect some directories (namely the <isa> for pruning the base dalvik-cache).
114 LOG(WARNING) << "Unexpected file type of " << std::hex << de->d_type << " encountered.";
115 }
116 continue;
117 }
Brian Carlstromdebdda02014-08-28 22:17:13 -0700118 std::string cache_file(cache_dir_path);
119 cache_file += '/';
120 cache_file += name;
121 if (TEMP_FAILURE_RETRY(unlink(cache_file.c_str())) != 0) {
122 PLOG(ERROR) << "Unable to unlink " << cache_file;
Alex Light25396132014-08-27 15:37:23 -0700123 continue;
124 }
125 }
126 CHECK_EQ(0, TEMP_FAILURE_RETRY(closedir(cache_dir))) << "Unable to close directory.";
127}
128
Narayan Kamath28bc9872014-11-07 17:46:28 +0000129// We write out an empty file to the zygote's ISA specific cache dir at the start of
130// every zygote boot and delete it when the boot completes. If we find a file already
131// present, it usually means the boot didn't complete. We wipe the entire dalvik
132// cache if that's the case.
Narayan Kamath5a2be3f2015-02-16 13:51:51 +0000133static void MarkZygoteStart(const InstructionSet isa, const uint32_t max_failed_boots) {
Narayan Kamath28bc9872014-11-07 17:46:28 +0000134 const std::string isa_subdir = GetDalvikCacheOrDie(GetInstructionSetString(isa), false);
135 const std::string boot_marker = isa_subdir + "/.booting";
Narayan Kamath5a2be3f2015-02-16 13:51:51 +0000136 const char* file_name = boot_marker.c_str();
Narayan Kamath28bc9872014-11-07 17:46:28 +0000137
Narayan Kamath5a2be3f2015-02-16 13:51:51 +0000138 uint32_t num_failed_boots = 0;
139 std::unique_ptr<File> file(OS::OpenFileReadWrite(file_name));
140 if (file.get() == nullptr) {
141 file.reset(OS::CreateEmptyFile(file_name));
142
143 if (file.get() == nullptr) {
144 PLOG(WARNING) << "Failed to create boot marker.";
145 return;
146 }
147 } else {
148 if (!file->ReadFully(&num_failed_boots, sizeof(num_failed_boots))) {
149 PLOG(WARNING) << "Failed to read boot marker.";
150 file->Erase();
151 return;
152 }
153 }
154
155 if (max_failed_boots != 0 && num_failed_boots > max_failed_boots) {
Narayan Kamath28bc9872014-11-07 17:46:28 +0000156 LOG(WARNING) << "Incomplete boot detected. Pruning dalvik cache";
157 RealPruneDalvikCache(isa_subdir);
158 }
159
Narayan Kamath5a2be3f2015-02-16 13:51:51 +0000160 ++num_failed_boots;
161 VLOG(startup) << "Number of failed boots on : " << boot_marker << " = " << num_failed_boots;
162
163 if (lseek(file->Fd(), 0, SEEK_SET) == -1) {
164 PLOG(WARNING) << "Failed to write boot marker.";
165 file->Erase();
166 return;
167 }
168
169 if (!file->WriteFully(&num_failed_boots, sizeof(num_failed_boots))) {
170 PLOG(WARNING) << "Failed to write boot marker.";
171 file->Erase();
172 return;
173 }
174
175 if (file->FlushCloseOrErase() != 0) {
176 PLOG(WARNING) << "Failed to flush boot marker.";
Narayan Kamath28bc9872014-11-07 17:46:28 +0000177 }
178}
179
Alex Light25396132014-08-27 15:37:23 -0700180static bool GenerateImage(const std::string& image_filename, InstructionSet image_isa,
181 std::string* error_msg) {
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700182 const std::string boot_class_path_string(Runtime::Current()->GetBootClassPathString());
183 std::vector<std::string> boot_class_path;
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700184 Split(boot_class_path_string, ':', &boot_class_path);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700185 if (boot_class_path.empty()) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700186 *error_msg = "Failed to generate image because no boot class path specified";
187 return false;
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700188 }
Alex Light25396132014-08-27 15:37:23 -0700189 // We should clean up so we are more likely to have room for the image.
190 if (Runtime::Current()->IsZygote()) {
Andreas Gampe3c13a792014-09-18 20:56:04 -0700191 LOG(INFO) << "Pruning dalvik-cache since we are generating an image and will need to recompile";
Narayan Kamath28bc9872014-11-07 17:46:28 +0000192 PruneDalvikCache(image_isa);
Alex Light25396132014-08-27 15:37:23 -0700193 }
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700194
Mathieu Chartier8bbc8c02013-07-31 16:27:01 -0700195 std::vector<std::string> arg_vector;
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700196
Tsu Chiang Chuang12e6d742014-05-22 10:22:25 -0700197 std::string dex2oat(Runtime::Current()->GetCompilerExecutable());
Mathieu Chartier08d7d442013-07-31 18:08:51 -0700198 arg_vector.push_back(dex2oat);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700199
200 std::string image_option_string("--image=");
Narayan Kamath52f84882014-05-02 10:10:39 +0100201 image_option_string += image_filename;
Mathieu Chartier8bbc8c02013-07-31 16:27:01 -0700202 arg_vector.push_back(image_option_string);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700203
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700204 for (size_t i = 0; i < boot_class_path.size(); i++) {
Mathieu Chartier8bbc8c02013-07-31 16:27:01 -0700205 arg_vector.push_back(std::string("--dex-file=") + boot_class_path[i]);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700206 }
207
208 std::string oat_file_option_string("--oat-file=");
Brian Carlstrom2f1e15c2014-10-27 16:27:06 -0700209 oat_file_option_string += ImageHeader::GetOatLocationFromImageLocation(image_filename);
Mathieu Chartier8bbc8c02013-07-31 16:27:01 -0700210 arg_vector.push_back(oat_file_option_string);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700211
Sebastien Hertz0de11332015-05-13 12:14:05 +0200212 // Note: we do not generate a fully debuggable boot image so we do not pass the
213 // compiler flag --debuggable here.
214
Igor Murashkinb1d8c312015-08-04 11:18:43 -0700215 Runtime::Current()->AddCurrentRuntimeFeaturesAsDex2OatArguments(&arg_vector);
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700216 CHECK_EQ(image_isa, kRuntimeISA)
217 << "We should always be generating an image for the current isa.";
Ian Rogers8afeb852014-04-02 14:55:49 -0700218
Alex Lightcf4bf382014-07-24 11:29:14 -0700219 int32_t base_offset = ChooseRelocationOffsetDelta(ART_BASE_ADDRESS_MIN_DELTA,
220 ART_BASE_ADDRESS_MAX_DELTA);
221 LOG(INFO) << "Using an offset of 0x" << std::hex << base_offset << " from default "
222 << "art base address of 0x" << std::hex << ART_BASE_ADDRESS;
223 arg_vector.push_back(StringPrintf("--base=0x%x", ART_BASE_ADDRESS + base_offset));
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700224
Brian Carlstrom57309db2014-07-30 15:13:25 -0700225 if (!kIsTargetBuild) {
Mathieu Chartier8bbc8c02013-07-31 16:27:01 -0700226 arg_vector.push_back("--host");
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700227 }
228
Brian Carlstrom6449c622014-02-10 23:48:36 -0800229 const std::vector<std::string>& compiler_options = Runtime::Current()->GetImageCompilerOptions();
Brian Carlstrom2ec65202014-03-03 15:16:37 -0800230 for (size_t i = 0; i < compiler_options.size(); ++i) {
Brian Carlstrom6449c622014-02-10 23:48:36 -0800231 arg_vector.push_back(compiler_options[i].c_str());
232 }
233
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700234 std::string command_line(Join(arg_vector, ' '));
235 LOG(INFO) << "GenerateImage: " << command_line;
Brian Carlstrom6449c622014-02-10 23:48:36 -0800236 return Exec(arg_vector, error_msg);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700237}
238
Narayan Kamath52f84882014-05-02 10:10:39 +0100239bool ImageSpace::FindImageFilename(const char* image_location,
240 const InstructionSet image_isa,
Alex Lighta59dd802014-07-02 16:28:08 -0700241 std::string* system_filename,
242 bool* has_system,
243 std::string* cache_filename,
244 bool* dalvik_cache_exists,
Andreas Gampe3c13a792014-09-18 20:56:04 -0700245 bool* has_cache,
246 bool* is_global_cache) {
Alex Lighta59dd802014-07-02 16:28:08 -0700247 *has_system = false;
248 *has_cache = false;
Brian Carlstrom0e12bdc2014-05-14 17:44:28 -0700249 // image_location = /system/framework/boot.art
250 // system_image_location = /system/framework/<image_isa>/boot.art
251 std::string system_image_filename(GetSystemImageFilename(image_location, image_isa));
252 if (OS::FileExists(system_image_filename.c_str())) {
Alex Lighta59dd802014-07-02 16:28:08 -0700253 *system_filename = system_image_filename;
254 *has_system = true;
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700255 }
Narayan Kamath52f84882014-05-02 10:10:39 +0100256
Alex Lighta59dd802014-07-02 16:28:08 -0700257 bool have_android_data = false;
258 *dalvik_cache_exists = false;
259 std::string dalvik_cache;
260 GetDalvikCache(GetInstructionSetString(image_isa), true, &dalvik_cache,
Andreas Gampe3c13a792014-09-18 20:56:04 -0700261 &have_android_data, dalvik_cache_exists, is_global_cache);
Narayan Kamath52f84882014-05-02 10:10:39 +0100262
Alex Lighta59dd802014-07-02 16:28:08 -0700263 if (have_android_data && *dalvik_cache_exists) {
264 // Always set output location even if it does not exist,
265 // so that the caller knows where to create the image.
266 //
267 // image_location = /system/framework/boot.art
268 // *image_filename = /data/dalvik-cache/<image_isa>/boot.art
269 std::string error_msg;
270 if (!GetDalvikCacheFilename(image_location, dalvik_cache.c_str(), cache_filename, &error_msg)) {
271 LOG(WARNING) << error_msg;
272 return *has_system;
273 }
274 *has_cache = OS::FileExists(cache_filename->c_str());
275 }
276 return *has_system || *has_cache;
277}
278
279static bool ReadSpecificImageHeader(const char* filename, ImageHeader* image_header) {
280 std::unique_ptr<File> image_file(OS::OpenFileForReading(filename));
281 if (image_file.get() == nullptr) {
282 return false;
283 }
284 const bool success = image_file->ReadFully(image_header, sizeof(ImageHeader));
285 if (!success || !image_header->IsValid()) {
286 return false;
287 }
288 return true;
289}
290
Alex Light6e183f22014-07-18 14:57:04 -0700291// Relocate the image at image_location to dest_filename and relocate it by a random amount.
292static bool RelocateImage(const char* image_location, const char* dest_filename,
Alex Lighta59dd802014-07-02 16:28:08 -0700293 InstructionSet isa, std::string* error_msg) {
Alex Light25396132014-08-27 15:37:23 -0700294 // We should clean up so we are more likely to have room for the image.
295 if (Runtime::Current()->IsZygote()) {
296 LOG(INFO) << "Pruning dalvik-cache since we are relocating an image and will need to recompile";
Narayan Kamath28bc9872014-11-07 17:46:28 +0000297 PruneDalvikCache(isa);
Alex Light25396132014-08-27 15:37:23 -0700298 }
299
Alex Lighta59dd802014-07-02 16:28:08 -0700300 std::string patchoat(Runtime::Current()->GetPatchoatExecutable());
301
302 std::string input_image_location_arg("--input-image-location=");
303 input_image_location_arg += image_location;
304
305 std::string output_image_filename_arg("--output-image-file=");
306 output_image_filename_arg += dest_filename;
307
Alex Lighta59dd802014-07-02 16:28:08 -0700308 std::string instruction_set_arg("--instruction-set=");
309 instruction_set_arg += GetInstructionSetString(isa);
310
311 std::string base_offset_arg("--base-offset-delta=");
312 StringAppendF(&base_offset_arg, "%d", ChooseRelocationOffsetDelta(ART_BASE_ADDRESS_MIN_DELTA,
313 ART_BASE_ADDRESS_MAX_DELTA));
314
315 std::vector<std::string> argv;
316 argv.push_back(patchoat);
317
318 argv.push_back(input_image_location_arg);
319 argv.push_back(output_image_filename_arg);
320
Alex Lighta59dd802014-07-02 16:28:08 -0700321 argv.push_back(instruction_set_arg);
322 argv.push_back(base_offset_arg);
323
324 std::string command_line(Join(argv, ' '));
325 LOG(INFO) << "RelocateImage: " << command_line;
326 return Exec(argv, error_msg);
327}
328
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700329static ImageHeader* ReadSpecificImageHeader(const char* filename, std::string* error_msg) {
Alex Lighta59dd802014-07-02 16:28:08 -0700330 std::unique_ptr<ImageHeader> hdr(new ImageHeader);
331 if (!ReadSpecificImageHeader(filename, hdr.get())) {
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700332 *error_msg = StringPrintf("Unable to read image header for %s", filename);
Alex Lighta59dd802014-07-02 16:28:08 -0700333 return nullptr;
334 }
335 return hdr.release();
Narayan Kamath52f84882014-05-02 10:10:39 +0100336}
337
338ImageHeader* ImageSpace::ReadImageHeaderOrDie(const char* image_location,
339 const InstructionSet image_isa) {
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700340 std::string error_msg;
341 ImageHeader* image_header = ReadImageHeader(image_location, image_isa, &error_msg);
342 if (image_header == nullptr) {
343 LOG(FATAL) << error_msg;
344 }
345 return image_header;
346}
347
348ImageHeader* ImageSpace::ReadImageHeader(const char* image_location,
349 const InstructionSet image_isa,
350 std::string* error_msg) {
Alex Lighta59dd802014-07-02 16:28:08 -0700351 std::string system_filename;
352 bool has_system = false;
353 std::string cache_filename;
354 bool has_cache = false;
355 bool dalvik_cache_exists = false;
Andreas Gampe3c13a792014-09-18 20:56:04 -0700356 bool is_global_cache = false;
Alex Lighta59dd802014-07-02 16:28:08 -0700357 if (FindImageFilename(image_location, image_isa, &system_filename, &has_system,
Andreas Gampe3c13a792014-09-18 20:56:04 -0700358 &cache_filename, &dalvik_cache_exists, &has_cache, &is_global_cache)) {
Alex Lighta59dd802014-07-02 16:28:08 -0700359 if (Runtime::Current()->ShouldRelocate()) {
360 if (has_system && has_cache) {
361 std::unique_ptr<ImageHeader> sys_hdr(new ImageHeader);
362 std::unique_ptr<ImageHeader> cache_hdr(new ImageHeader);
363 if (!ReadSpecificImageHeader(system_filename.c_str(), sys_hdr.get())) {
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700364 *error_msg = StringPrintf("Unable to read image header for %s at %s",
365 image_location, system_filename.c_str());
Alex Lighta59dd802014-07-02 16:28:08 -0700366 return nullptr;
367 }
368 if (!ReadSpecificImageHeader(cache_filename.c_str(), cache_hdr.get())) {
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700369 *error_msg = StringPrintf("Unable to read image header for %s at %s",
370 image_location, cache_filename.c_str());
Alex Lighta59dd802014-07-02 16:28:08 -0700371 return nullptr;
372 }
373 if (sys_hdr->GetOatChecksum() != cache_hdr->GetOatChecksum()) {
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700374 *error_msg = StringPrintf("Unable to find a relocated version of image file %s",
375 image_location);
Alex Lighta59dd802014-07-02 16:28:08 -0700376 return nullptr;
377 }
378 return cache_hdr.release();
379 } else if (!has_cache) {
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700380 *error_msg = StringPrintf("Unable to find a relocated version of image file %s",
381 image_location);
Alex Lighta59dd802014-07-02 16:28:08 -0700382 return nullptr;
383 } else if (!has_system && has_cache) {
384 // This can probably just use the cache one.
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700385 return ReadSpecificImageHeader(cache_filename.c_str(), error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -0700386 }
387 } else {
388 // We don't want to relocate, Just pick the appropriate one if we have it and return.
389 if (has_system && has_cache) {
390 // We want the cache if the checksum matches, otherwise the system.
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700391 std::unique_ptr<ImageHeader> system(ReadSpecificImageHeader(system_filename.c_str(),
392 error_msg));
393 std::unique_ptr<ImageHeader> cache(ReadSpecificImageHeader(cache_filename.c_str(),
394 error_msg));
Alex Lighta59dd802014-07-02 16:28:08 -0700395 if (system.get() == nullptr ||
396 (cache.get() != nullptr && cache->GetOatChecksum() == system->GetOatChecksum())) {
397 return cache.release();
398 } else {
399 return system.release();
400 }
401 } else if (has_system) {
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700402 return ReadSpecificImageHeader(system_filename.c_str(), error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -0700403 } else if (has_cache) {
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700404 return ReadSpecificImageHeader(cache_filename.c_str(), error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -0700405 }
Narayan Kamath52f84882014-05-02 10:10:39 +0100406 }
Narayan Kamath52f84882014-05-02 10:10:39 +0100407 }
408
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700409 *error_msg = StringPrintf("Unable to find image file for %s", image_location);
Narayan Kamath52f84882014-05-02 10:10:39 +0100410 return nullptr;
411}
412
Alex Lighta59dd802014-07-02 16:28:08 -0700413static bool ChecksumsMatch(const char* image_a, const char* image_b) {
414 ImageHeader hdr_a;
415 ImageHeader hdr_b;
416 return ReadSpecificImageHeader(image_a, &hdr_a) && ReadSpecificImageHeader(image_b, &hdr_b)
417 && hdr_a.GetOatChecksum() == hdr_b.GetOatChecksum();
418}
419
Andreas Gampe3c13a792014-09-18 20:56:04 -0700420static bool ImageCreationAllowed(bool is_global_cache, std::string* error_msg) {
421 // Anyone can write into a "local" cache.
422 if (!is_global_cache) {
423 return true;
424 }
425
426 // Only the zygote is allowed to create the global boot image.
427 if (Runtime::Current()->IsZygote()) {
428 return true;
429 }
430
431 *error_msg = "Only the zygote can create the global boot image.";
432 return false;
433}
434
Andreas Gampe70be1fb2014-10-31 16:45:19 -0700435static constexpr uint64_t kLowSpaceValue = 50 * MB;
436static constexpr uint64_t kTmpFsSentinelValue = 384 * MB;
437
438// Read the free space of the cache partition and make a decision whether to keep the generated
439// image. This is to try to mitigate situations where the system might run out of space later.
440static bool CheckSpace(const std::string& cache_filename, std::string* error_msg) {
441 // Using statvfs vs statvfs64 because of b/18207376, and it is enough for all practical purposes.
442 struct statvfs buf;
443
444 int res = TEMP_FAILURE_RETRY(statvfs(cache_filename.c_str(), &buf));
445 if (res != 0) {
446 // Could not stat. Conservatively tell the system to delete the image.
447 *error_msg = "Could not stat the filesystem, assuming low-memory situation.";
448 return false;
449 }
450
451 uint64_t fs_overall_size = buf.f_bsize * static_cast<uint64_t>(buf.f_blocks);
452 // Zygote is privileged, but other things are not. Use bavail.
453 uint64_t fs_free_size = buf.f_bsize * static_cast<uint64_t>(buf.f_bavail);
454
455 // Take the overall size as an indicator for a tmpfs, which is being used for the decryption
456 // environment. We do not want to fail quickening the boot image there, as it is beneficial
457 // for time-to-UI.
458 if (fs_overall_size > kTmpFsSentinelValue) {
459 if (fs_free_size < kLowSpaceValue) {
460 *error_msg = StringPrintf("Low-memory situation: only %4.2f megabytes available after image"
461 " generation, need at least %" PRIu64 ".",
462 static_cast<double>(fs_free_size) / MB,
463 kLowSpaceValue / MB);
464 return false;
465 }
466 }
467 return true;
468}
469
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800470ImageSpace* ImageSpace::CreateBootImage(const char* image_location,
471 const InstructionSet image_isa,
472 bool secondary_image,
473 std::string* error_msg) {
Alex Lighta59dd802014-07-02 16:28:08 -0700474 std::string system_filename;
475 bool has_system = false;
476 std::string cache_filename;
477 bool has_cache = false;
478 bool dalvik_cache_exists = false;
Andreas Gampe3c13a792014-09-18 20:56:04 -0700479 bool is_global_cache = true;
Alex Lighta59dd802014-07-02 16:28:08 -0700480 const bool found_image = FindImageFilename(image_location, image_isa, &system_filename,
481 &has_system, &cache_filename, &dalvik_cache_exists,
Andreas Gampe3c13a792014-09-18 20:56:04 -0700482 &has_cache, &is_global_cache);
Narayan Kamathd1c606f2014-06-09 16:50:19 +0100483
Jeff Haodcdc85b2015-12-04 14:06:18 -0800484 if (Runtime::Current()->IsZygote() && !secondary_image) {
Narayan Kamath5a2be3f2015-02-16 13:51:51 +0000485 MarkZygoteStart(image_isa, Runtime::Current()->GetZygoteMaxFailedBoots());
Narayan Kamath28bc9872014-11-07 17:46:28 +0000486 }
487
Alex Lighta59dd802014-07-02 16:28:08 -0700488 ImageSpace* space;
489 bool relocate = Runtime::Current()->ShouldRelocate();
Alex Light64ad14d2014-08-19 14:23:13 -0700490 bool can_compile = Runtime::Current()->IsImageDex2OatEnabled();
Narayan Kamathd1c606f2014-06-09 16:50:19 +0100491 if (found_image) {
Alex Lighta59dd802014-07-02 16:28:08 -0700492 const std::string* image_filename;
493 bool is_system = false;
494 bool relocated_version_used = false;
495 if (relocate) {
Alex Light64ad14d2014-08-19 14:23:13 -0700496 if (!dalvik_cache_exists) {
497 *error_msg = StringPrintf("Requiring relocation for image '%s' at '%s' but we do not have "
498 "any dalvik_cache to find/place it in.",
499 image_location, system_filename.c_str());
500 return nullptr;
501 }
Alex Lighta59dd802014-07-02 16:28:08 -0700502 if (has_system) {
503 if (has_cache && ChecksumsMatch(system_filename.c_str(), cache_filename.c_str())) {
504 // We already have a relocated version
505 image_filename = &cache_filename;
506 relocated_version_used = true;
507 } else {
508 // We cannot have a relocated version, Relocate the system one and use it.
Andreas Gampe3c13a792014-09-18 20:56:04 -0700509
510 std::string reason;
511 bool success;
512
513 // Check whether we are allowed to relocate.
514 if (!can_compile) {
515 reason = "Image dex2oat disabled by -Xnoimage-dex2oat.";
516 success = false;
517 } else if (!ImageCreationAllowed(is_global_cache, &reason)) {
518 // Whether we can write to the cache.
519 success = false;
Andreas Gampe8994a042015-12-30 19:03:17 +0000520 } else if (secondary_image) {
521 reason = "Should not have to patch secondary image.";
522 success = false;
Andreas Gampe3c13a792014-09-18 20:56:04 -0700523 } else {
524 // Try to relocate.
525 success = RelocateImage(image_location, cache_filename.c_str(), image_isa, &reason);
526 }
527
528 if (success) {
Alex Lighta59dd802014-07-02 16:28:08 -0700529 relocated_version_used = true;
530 image_filename = &cache_filename;
531 } else {
Andreas Gampe3c13a792014-09-18 20:56:04 -0700532 *error_msg = StringPrintf("Unable to relocate image '%s' from '%s' to '%s': %s",
Alex Light64ad14d2014-08-19 14:23:13 -0700533 image_location, system_filename.c_str(),
534 cache_filename.c_str(), reason.c_str());
Brian Carlstrome9105f72014-10-28 15:53:43 -0700535 // We failed to create files, remove any possibly garbage output.
536 // Since ImageCreationAllowed was true above, we are the zygote
537 // and therefore the only process expected to generate these for
538 // the device.
Narayan Kamath28bc9872014-11-07 17:46:28 +0000539 PruneDalvikCache(image_isa);
Alex Lighta59dd802014-07-02 16:28:08 -0700540 return nullptr;
541 }
542 }
543 } else {
544 CHECK(has_cache);
545 // We can just use cache's since it should be fine. This might or might not be relocated.
546 image_filename = &cache_filename;
547 }
548 } else {
549 if (has_system && has_cache) {
550 // Check they have the same cksum. If they do use the cache. Otherwise system.
551 if (ChecksumsMatch(system_filename.c_str(), cache_filename.c_str())) {
552 image_filename = &cache_filename;
553 relocated_version_used = true;
554 } else {
555 image_filename = &system_filename;
Alex Light1a762132014-07-31 09:32:13 -0700556 is_system = true;
Alex Lighta59dd802014-07-02 16:28:08 -0700557 }
558 } else if (has_system) {
559 image_filename = &system_filename;
Alex Light1a762132014-07-31 09:32:13 -0700560 is_system = true;
Alex Lighta59dd802014-07-02 16:28:08 -0700561 } else {
562 CHECK(has_cache);
563 image_filename = &cache_filename;
564 }
565 }
566 {
567 // Note that we must not use the file descriptor associated with
568 // ScopedFlock::GetFile to Init the image file. We want the file
569 // descriptor (and the associated exclusive lock) to be released when
570 // we leave Create.
571 ScopedFlock image_lock;
Alex Light64ad14d2014-08-19 14:23:13 -0700572 image_lock.Init(image_filename->c_str(), error_msg);
Alex Lightb6cabc12014-08-21 09:45:00 -0700573 VLOG(startup) << "Using image file " << image_filename->c_str() << " for image location "
574 << image_location;
Alex Lightb93637a2014-07-31 10:48:46 -0700575 // If we are in /system we can assume the image is good. We can also
576 // assume this if we are using a relocated image (i.e. image checksum
577 // matches) since this is only different by the offset. We need this to
578 // make sure that host tests continue to work.
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800579 // Since we are the boot image, pass null since we load the oat file from the boot image oat
580 // file name.
581 space = ImageSpace::Init(image_filename->c_str(),
582 image_location,
583 !(is_system || relocated_version_used),
584 /* oat_file */nullptr,
585 error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -0700586 }
Narayan Kamath52f84882014-05-02 10:10:39 +0100587 if (space != nullptr) {
588 return space;
589 }
590
Alex Lighta59dd802014-07-02 16:28:08 -0700591 if (relocated_version_used) {
Brian Carlstrome9105f72014-10-28 15:53:43 -0700592 // Something is wrong with the relocated copy (even though checksums match). Cleanup.
593 // This can happen if the .oat is corrupt, since the above only checks the .art checksums.
594 // TODO: Check the oat file validity earlier.
595 *error_msg = StringPrintf("Attempted to use relocated version of %s at %s generated from %s "
596 "but image failed to load: %s",
597 image_location, cache_filename.c_str(), system_filename.c_str(),
598 error_msg->c_str());
Narayan Kamath28bc9872014-11-07 17:46:28 +0000599 PruneDalvikCache(image_isa);
Alex Lighta59dd802014-07-02 16:28:08 -0700600 return nullptr;
601 } else if (is_system) {
Brian Carlstrome9105f72014-10-28 15:53:43 -0700602 // If the /system file exists, it should be up-to-date, don't try to generate it.
Alex Light64ad14d2014-08-19 14:23:13 -0700603 *error_msg = StringPrintf("Failed to load /system image '%s': %s",
604 image_filename->c_str(), error_msg->c_str());
Narayan Kamath52f84882014-05-02 10:10:39 +0100605 return nullptr;
Mathieu Chartierc7cb1902014-03-05 14:41:03 -0800606 } else {
Brian Carlstrome9105f72014-10-28 15:53:43 -0700607 // Otherwise, log a warning and fall through to GenerateImage.
Alex Light64ad14d2014-08-19 14:23:13 -0700608 LOG(WARNING) << *error_msg;
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700609 }
610 }
Narayan Kamath52f84882014-05-02 10:10:39 +0100611
Alex Light64ad14d2014-08-19 14:23:13 -0700612 if (!can_compile) {
613 *error_msg = "Not attempting to compile image because -Xnoimage-dex2oat";
614 return nullptr;
615 } else if (!dalvik_cache_exists) {
616 *error_msg = StringPrintf("No place to put generated image.");
617 return nullptr;
Andreas Gampe3c13a792014-09-18 20:56:04 -0700618 } else if (!ImageCreationAllowed(is_global_cache, error_msg)) {
619 return nullptr;
Andreas Gampe8994a042015-12-30 19:03:17 +0000620 } else if (secondary_image) {
621 *error_msg = "Cannot compile a secondary image.";
622 return nullptr;
Alex Light25396132014-08-27 15:37:23 -0700623 } else if (!GenerateImage(cache_filename, image_isa, error_msg)) {
Alex Light64ad14d2014-08-19 14:23:13 -0700624 *error_msg = StringPrintf("Failed to generate image '%s': %s",
625 cache_filename.c_str(), error_msg->c_str());
Brian Carlstrome9105f72014-10-28 15:53:43 -0700626 // We failed to create files, remove any possibly garbage output.
627 // Since ImageCreationAllowed was true above, we are the zygote
628 // and therefore the only process expected to generate these for
629 // the device.
Narayan Kamath28bc9872014-11-07 17:46:28 +0000630 PruneDalvikCache(image_isa);
Alex Light64ad14d2014-08-19 14:23:13 -0700631 return nullptr;
632 } else {
Andreas Gampe70be1fb2014-10-31 16:45:19 -0700633 // Check whether there is enough space left over after we have generated the image.
634 if (!CheckSpace(cache_filename, error_msg)) {
635 // No. Delete the generated image and try to run out of the dex files.
Narayan Kamath28bc9872014-11-07 17:46:28 +0000636 PruneDalvikCache(image_isa);
Andreas Gampe70be1fb2014-10-31 16:45:19 -0700637 return nullptr;
638 }
639
Alex Lighta59dd802014-07-02 16:28:08 -0700640 // Note that we must not use the file descriptor associated with
641 // ScopedFlock::GetFile to Init the image file. We want the file
642 // descriptor (and the associated exclusive lock) to be released when
643 // we leave Create.
644 ScopedFlock image_lock;
Alex Light64ad14d2014-08-19 14:23:13 -0700645 image_lock.Init(cache_filename.c_str(), error_msg);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800646 space = ImageSpace::Init(cache_filename.c_str(), image_location, true, nullptr, error_msg);
Alex Light64ad14d2014-08-19 14:23:13 -0700647 if (space == nullptr) {
648 *error_msg = StringPrintf("Failed to load generated image '%s': %s",
649 cache_filename.c_str(), error_msg->c_str());
650 }
651 return space;
Alex Lighta59dd802014-07-02 16:28:08 -0700652 }
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700653}
654
Mathieu Chartier31e89252013-08-28 11:29:12 -0700655void ImageSpace::VerifyImageAllocations() {
Ian Rogers13735952014-10-08 12:43:28 -0700656 uint8_t* current = Begin() + RoundUp(sizeof(ImageHeader), kObjectAlignment);
Mathieu Chartier31e89252013-08-28 11:29:12 -0700657 while (current < End()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700658 CHECK_ALIGNED(current, kObjectAlignment);
659 auto* obj = reinterpret_cast<mirror::Object*>(current);
Mathieu Chartier31e89252013-08-28 11:29:12 -0700660 CHECK(obj->GetClass() != nullptr) << "Image object at address " << obj << " has null class";
Mathieu Chartierc7853442015-03-27 14:35:38 -0700661 CHECK(live_bitmap_->Test(obj)) << PrettyTypeOf(obj);
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -0700662 if (kUseBakerOrBrooksReadBarrier) {
663 obj->AssertReadBarrierPointer();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800664 }
Mathieu Chartier31e89252013-08-28 11:29:12 -0700665 current += RoundUp(obj->SizeOf(), kObjectAlignment);
666 }
667}
668
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800669// Helper class for relocating from one range of memory to another.
670class RelocationRange {
671 public:
672 RelocationRange() = default;
673 RelocationRange(const RelocationRange&) = default;
674 RelocationRange(uintptr_t source, uintptr_t dest, uintptr_t length)
675 : source_(source),
676 dest_(dest),
677 length_(length) {}
678
679 bool ContainsSource(uintptr_t address) const {
680 return address - source_ < length_;
681 }
682
683 // Translate a source address to the destination space.
684 uintptr_t ToDest(uintptr_t address) const {
685 DCHECK(ContainsSource(address));
686 return address + Delta();
687 }
688
689 // Returns the delta between the dest from the source.
690 off_t Delta() const {
691 return dest_ - source_;
692 }
693
694 uintptr_t Source() const {
695 return source_;
696 }
697
698 uintptr_t Dest() const {
699 return dest_;
700 }
701
702 uintptr_t Length() const {
703 return length_;
704 }
705
706 private:
707 const uintptr_t source_;
708 const uintptr_t dest_;
709 const uintptr_t length_;
710};
711
712class FixupVisitor : public ValueObject {
713 public:
714 FixupVisitor(const RelocationRange& boot_image,
715 const RelocationRange& boot_oat,
716 const RelocationRange& app_image,
717 const RelocationRange& app_oat)
718 : boot_image_(boot_image),
719 boot_oat_(boot_oat),
720 app_image_(app_image),
721 app_oat_(app_oat) {}
722
723 // Return the relocated address of a heap object.
724 template <typename T>
725 ALWAYS_INLINE T* ForwardObject(T* src) const {
726 const uintptr_t uint_src = reinterpret_cast<uintptr_t>(src);
727 if (boot_image_.ContainsSource(uint_src)) {
728 return reinterpret_cast<T*>(boot_image_.ToDest(uint_src));
729 }
730 if (app_image_.ContainsSource(uint_src)) {
731 return reinterpret_cast<T*>(app_image_.ToDest(uint_src));
732 }
733 return src;
734 }
735
736 // Return the relocated address of a code pointer (contained by an oat file).
737 ALWAYS_INLINE const void* ForwardCode(const void* src) const {
738 const uintptr_t uint_src = reinterpret_cast<uintptr_t>(src);
739 if (boot_oat_.ContainsSource(uint_src)) {
740 return reinterpret_cast<const void*>(boot_oat_.ToDest(uint_src));
741 }
742 if (app_oat_.ContainsSource(uint_src)) {
743 return reinterpret_cast<const void*>(app_oat_.ToDest(uint_src));
744 }
745 return src;
746 }
747
748 protected:
749 // Source section.
750 const RelocationRange boot_image_;
751 const RelocationRange boot_oat_;
752 const RelocationRange app_image_;
753 const RelocationRange app_oat_;
754};
755
756std::ostream& operator<<(std::ostream& os, const RelocationRange& reloc) {
757 return os << "(" << reinterpret_cast<const void*>(reloc.Source()) << "-"
758 << reinterpret_cast<const void*>(reloc.Source() + reloc.Length()) << ")->("
759 << reinterpret_cast<const void*>(reloc.Dest()) << "-"
760 << reinterpret_cast<const void*>(reloc.Dest() + reloc.Length()) << ")";
761}
762
763// Adapt for mirror::Class::FixupNativePointers.
764class FixupObjectAdapter : public FixupVisitor {
765 public:
766 template<typename... Args>
767 explicit FixupObjectAdapter(Args... args) : FixupVisitor(args...) {}
768
769 template <typename T>
770 T* operator()(T* obj) const {
771 return ForwardObject(obj);
772 }
773};
774
775class FixupClassVisitor : public FixupVisitor {
776 public:
777 template<typename... Args>
778 explicit FixupClassVisitor(Args... args) : FixupVisitor(args...) {}
779
780 // The image space is contained so the GC doesn't need to know about it. Avoid requiring mutator
781 // lock to prevent possible pauses.
782 ALWAYS_INLINE void operator()(mirror::Object* obj) const NO_THREAD_SAFETY_ANALYSIS {
783 mirror::Class* klass = obj->GetClass<kVerifyNone, kWithoutReadBarrier>();
784 DCHECK(klass != nullptr) << "Null class in image";
785 // No AsClass since our fields aren't quite fixed up yet.
786 mirror::Class* new_klass = down_cast<mirror::Class*>(ForwardObject(klass));
787 // Keep clean if possible.
788 if (klass != new_klass) {
789 obj->SetClass<kVerifyNone>(new_klass);
790 }
791 }
792};
793
794class FixupRootVisitor : public FixupVisitor {
795 public:
796 template<typename... Args>
797 explicit FixupRootVisitor(Args... args) : FixupVisitor(args...) {}
798
799 ALWAYS_INLINE void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
800 SHARED_REQUIRES(Locks::mutator_lock_) {
801 if (!root->IsNull()) {
802 VisitRoot(root);
803 }
804 }
805
806 ALWAYS_INLINE void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
807 SHARED_REQUIRES(Locks::mutator_lock_) {
808 mirror::Object* ref = root->AsMirrorPtr();
809 mirror::Object* new_ref = ForwardObject(ref);
810 if (ref != new_ref) {
811 root->Assign(new_ref);
812 }
813 }
814};
815
816class FixupObjectVisitor : public FixupVisitor {
817 public:
818 template<typename... Args>
819 explicit FixupObjectVisitor(Args... args) : FixupVisitor(args...) {}
820
821 // Fix up separately since we also need to fix up method entrypoints.
822 ALWAYS_INLINE void VisitRootIfNonNull(
823 mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const {}
824
825 ALWAYS_INLINE void VisitRoot(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED)
826 const {}
827
828 ALWAYS_INLINE void operator()(mirror::Object* obj,
829 MemberOffset offset,
830 bool is_static ATTRIBUTE_UNUSED) const
831 NO_THREAD_SAFETY_ANALYSIS {
832 // There could be overlap between ranges, we must avoid visiting the same reference twice.
833 // Avoid the class field since we already fixed it up in FixupClassVisitor.
834 if (offset.Uint32Value() != mirror::Object::ClassOffset().Uint32Value()) {
835 // Space is not yet added to the heap, don't do a read barrier.
836 mirror::Object* ref = obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(
837 offset);
838 // Use SetFieldObjectWithoutWriteBarrier to avoid card marking since we are writing to the
839 // image.
840 obj->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(offset, ForwardObject(ref));
841 }
842 }
843
844 // java.lang.ref.Reference visitor.
845 void operator()(mirror::Class* klass ATTRIBUTE_UNUSED, mirror::Reference* ref) const
846 SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
847 mirror::Object* obj = ref->GetReferent<kWithoutReadBarrier>();
848 ref->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
849 mirror::Reference::ReferentOffset(),
850 ForwardObject(obj));
851 }
852
853 ALWAYS_INLINE void operator()(mirror::Object* obj) const NO_THREAD_SAFETY_ANALYSIS {
854 obj->VisitReferences</*visit native roots*/false, kVerifyNone, kWithoutReadBarrier>(
855 *this,
856 *this);
857 // We want to use our own class loader and not the one in the image.
858 if (obj->IsClass<kVerifyNone, kWithoutReadBarrier>()) {
859 mirror::Class* klass = obj->AsClass<kVerifyNone, kWithoutReadBarrier>();
860 FixupObjectAdapter visitor(boot_image_, boot_oat_, app_image_, app_oat_);
Mathieu Chartierdfe02f62016-02-01 20:15:11 -0800861 klass->FixupNativePointers<kVerifyNone, kWithoutReadBarrier>(klass, sizeof(void*), visitor);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800862 // Deal with the arrays.
863 mirror::PointerArray* vtable = klass->GetVTable<kVerifyNone, kWithoutReadBarrier>();
864 if (vtable != nullptr) {
Mathieu Chartierdfe02f62016-02-01 20:15:11 -0800865 vtable->Fixup<kVerifyNone, kWithoutReadBarrier>(vtable, sizeof(void*), visitor);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800866 }
867 mirror::IfTable* iftable = klass->GetIfTable<kVerifyNone, kWithoutReadBarrier>();
868 if (iftable != nullptr) {
Mathieu Chartierdfe02f62016-02-01 20:15:11 -0800869 for (int32_t i = 0, count = iftable->Count(); i < count; ++i) {
870 if (iftable->GetMethodArrayCount<kVerifyNone, kWithoutReadBarrier>(i) > 0) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800871 mirror::PointerArray* methods =
872 iftable->GetMethodArray<kVerifyNone, kWithoutReadBarrier>(i);
873 DCHECK(methods != nullptr);
Mathieu Chartierdfe02f62016-02-01 20:15:11 -0800874 methods->Fixup<kVerifyNone, kWithoutReadBarrier>(methods, sizeof(void*), visitor);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800875 }
876 }
877 }
878 }
879 }
880};
881
882class ForwardObjectAdapter {
883 public:
884 ALWAYS_INLINE ForwardObjectAdapter(const FixupVisitor* visitor) : visitor_(visitor) {}
885
886 template <typename T>
887 ALWAYS_INLINE T* operator()(T* src) const {
888 return visitor_->ForwardObject(src);
889 }
890
891 private:
892 const FixupVisitor* const visitor_;
893};
894
895class ForwardCodeAdapter {
896 public:
897 ALWAYS_INLINE ForwardCodeAdapter(const FixupVisitor* visitor) : visitor_(visitor) {}
898
899 template <typename T>
900 ALWAYS_INLINE T* operator()(T* src) const {
901 return visitor_->ForwardCode(src);
902 }
903
904 private:
905 const FixupVisitor* const visitor_;
906};
907
908class FixupArtMethodVisitor : public FixupVisitor, public ArtMethodVisitor {
909 public:
910 template<typename... Args>
911 explicit FixupArtMethodVisitor(bool fixup_heap_objects, Args... args)
912 : FixupVisitor(args...),
913 fixup_heap_objects_(fixup_heap_objects) {}
914
915 virtual void Visit(ArtMethod* method) NO_THREAD_SAFETY_ANALYSIS {
916 if (fixup_heap_objects_) {
917 method->UpdateObjectsForImageRelocation(ForwardObjectAdapter(this));
918 }
Mathieu Chartiera57ee9d2016-02-03 11:48:27 -0800919 method->UpdateEntrypoints<kWithoutReadBarrier>(ForwardCodeAdapter(this));
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800920 }
921
922 private:
923 const bool fixup_heap_objects_;
924};
925
926class FixupArtFieldVisitor : public FixupVisitor, public ArtFieldVisitor {
927 public:
928 template<typename... Args>
929 explicit FixupArtFieldVisitor(Args... args) : FixupVisitor(args...) {}
930
931 virtual void Visit(ArtField* field) NO_THREAD_SAFETY_ANALYSIS {
932 field->UpdateObjects(ForwardObjectAdapter(this));
933 }
934};
935
936// Relocate an image space mapped at target_base which possibly used to be at a different base
937// address. Only needs a single image space, not one for both source and destination.
938// In place means modifying a single ImageSpace in place rather than relocating from one ImageSpace
939// to another.
940static bool RelocateInPlace(ImageHeader& image_header,
941 uint8_t* target_base,
942 accounting::ContinuousSpaceBitmap* bitmap,
943 const OatFile* app_oat_file,
944 std::string* error_msg) {
945 DCHECK(error_msg != nullptr);
946 if (!image_header.IsPic()) {
947 if (image_header.GetImageBegin() == target_base) {
948 return true;
949 }
950 *error_msg = StringPrintf("Cannot relocate non-pic image for oat file %s",
951 (app_oat_file != nullptr) ? app_oat_file->GetLocation().c_str() : "");
952 return false;
953 }
954 // Set up sections.
955 uint32_t boot_image_begin = 0;
956 uint32_t boot_image_end = 0;
957 uint32_t boot_oat_begin = 0;
958 uint32_t boot_oat_end = 0;
959 gc::Heap* const heap = Runtime::Current()->GetHeap();
960 heap->GetBootImagesSize(&boot_image_begin, &boot_image_end, &boot_oat_begin, &boot_oat_end);
961 CHECK_NE(boot_image_begin, boot_image_end)
962 << "Can not relocate app image without boot image space";
963 CHECK_NE(boot_oat_begin, boot_oat_end) << "Can not relocate app image without boot oat file";
964 const uint32_t boot_image_size = boot_image_end - boot_image_begin;
965 const uint32_t boot_oat_size = boot_oat_end - boot_oat_begin;
966 const uint32_t image_header_boot_image_size = image_header.GetBootImageSize();
967 const uint32_t image_header_boot_oat_size = image_header.GetBootOatSize();
968 if (boot_image_size != image_header_boot_image_size) {
969 *error_msg = StringPrintf("Boot image size %" PRIu64 " does not match expected size %"
970 PRIu64,
971 static_cast<uint64_t>(boot_image_size),
972 static_cast<uint64_t>(image_header_boot_image_size));
973 return false;
974 }
975 if (boot_oat_size != image_header_boot_oat_size) {
976 *error_msg = StringPrintf("Boot oat size %" PRIu64 " does not match expected size %"
977 PRIu64,
978 static_cast<uint64_t>(boot_oat_size),
979 static_cast<uint64_t>(image_header_boot_oat_size));
980 return false;
981 }
982 TimingLogger logger(__FUNCTION__, true, false);
983 RelocationRange boot_image(image_header.GetBootImageBegin(),
984 boot_image_begin,
985 boot_image_size);
986 RelocationRange boot_oat(image_header.GetBootOatBegin(),
987 boot_oat_begin,
988 boot_oat_size);
989 RelocationRange app_image(reinterpret_cast<uintptr_t>(image_header.GetImageBegin()),
990 reinterpret_cast<uintptr_t>(target_base),
991 image_header.GetImageSize());
992 // Use the oat data section since this is where the OatFile::Begin is.
993 RelocationRange app_oat(reinterpret_cast<uintptr_t>(image_header.GetOatDataBegin()),
994 // Not necessarily in low 4GB.
995 reinterpret_cast<uintptr_t>(app_oat_file->Begin()),
996 image_header.GetOatDataEnd() - image_header.GetOatDataBegin());
997 VLOG(image) << "App image " << app_image;
998 VLOG(image) << "App oat " << app_oat;
999 VLOG(image) << "Boot image " << boot_image;
1000 VLOG(image) << "Boot oat " << boot_oat;
1001 // True if we need to fixup any heap pointers, otherwise only code pointers.
1002 const bool fixup_image = boot_image.Delta() != 0 || app_image.Delta() != 0;
1003 const bool fixup_code = boot_oat.Delta() != 0 || app_oat.Delta() != 0;
1004 if (!fixup_image && !fixup_code) {
1005 // Nothing to fix up.
1006 return true;
1007 }
Mathieu Chartierdfe02f62016-02-01 20:15:11 -08001008 ScopedDebugDisallowReadBarriers sddrb(Thread::Current());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001009 // Need to update the image to be at the target base.
1010 const ImageSection& objects_section = image_header.GetImageSection(ImageHeader::kSectionObjects);
1011 uintptr_t objects_begin = reinterpret_cast<uintptr_t>(target_base + objects_section.Offset());
1012 uintptr_t objects_end = reinterpret_cast<uintptr_t>(target_base + objects_section.End());
1013 // Two pass approach, fix up all classes first, then fix up non class-objects.
1014 FixupObjectVisitor fixup_object_visitor(boot_image, boot_oat, app_image, app_oat);
1015 if (fixup_image) {
1016 TimingLogger::ScopedTiming timing("Fixup classes", &logger);
1017 // Fixup class only touches app image classes, don't need the mutator lock since the space is
1018 // not yet visible to the GC.
1019 FixupClassVisitor fixup_class_visitor(boot_image, boot_oat, app_image, app_oat);
1020 bitmap->VisitMarkedRange(objects_begin, objects_end, fixup_class_visitor);
1021 // Fixup objects may read fields in the boot image, use the mutator lock here for sanity. Though
1022 // its probably not required.
1023 ScopedObjectAccess soa(Thread::Current());
1024 timing.NewTiming("Fixup objects");
1025 bitmap->VisitMarkedRange(objects_begin, objects_end, fixup_object_visitor);
1026 FixupObjectAdapter fixup_adapter(boot_image, boot_oat, app_image, app_oat);
1027 // Fixup image roots.
Mathieu Chartier4a26f172016-01-26 14:26:18 -08001028 CHECK(app_image.ContainsSource(reinterpret_cast<uintptr_t>(
1029 image_header.GetImageRoots<kWithoutReadBarrier>())));
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001030 image_header.RelocateImageObjects(app_image.Delta());
1031 CHECK_EQ(image_header.GetImageBegin(), target_base);
1032 // Fix up dex cache DexFile pointers.
Mathieu Chartier4a26f172016-01-26 14:26:18 -08001033 auto* dex_caches = image_header.GetImageRoot<kWithoutReadBarrier>(ImageHeader::kDexCaches)->
Mathieu Chartierdfe02f62016-02-01 20:15:11 -08001034 AsObjectArray<mirror::DexCache, kVerifyNone, kWithoutReadBarrier>();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001035 for (int32_t i = 0, count = dex_caches->GetLength(); i < count; ++i) {
Mathieu Chartier60bc39c2016-01-27 18:37:48 -08001036 mirror::DexCache* dex_cache = dex_caches->Get<kVerifyNone, kWithoutReadBarrier>(i);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001037 // Fix up dex cache pointers.
1038 GcRoot<mirror::String>* strings = dex_cache->GetStrings();
1039 if (strings != nullptr) {
1040 GcRoot<mirror::String>* new_strings = fixup_adapter.ForwardObject(strings);
1041 if (strings != new_strings) {
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001042 dex_cache->SetStrings(new_strings);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001043 }
Mathieu Chartier60bc39c2016-01-27 18:37:48 -08001044 dex_cache->FixupStrings<kWithoutReadBarrier>(new_strings, fixup_adapter);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001045 }
1046 GcRoot<mirror::Class>* types = dex_cache->GetResolvedTypes();
1047 if (types != nullptr) {
1048 GcRoot<mirror::Class>* new_types = fixup_adapter.ForwardObject(types);
1049 if (types != new_types) {
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001050 dex_cache->SetResolvedTypes(new_types);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001051 }
Mathieu Chartier60bc39c2016-01-27 18:37:48 -08001052 dex_cache->FixupResolvedTypes<kWithoutReadBarrier>(new_types, fixup_adapter);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001053 }
1054 ArtMethod** methods = dex_cache->GetResolvedMethods();
1055 if (methods != nullptr) {
1056 ArtMethod** new_methods = fixup_adapter.ForwardObject(methods);
1057 if (methods != new_methods) {
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001058 dex_cache->SetResolvedMethods(new_methods);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001059 }
1060 for (size_t j = 0, num = dex_cache->NumResolvedMethods(); j != num; ++j) {
1061 ArtMethod* orig = mirror::DexCache::GetElementPtrSize(new_methods, j, sizeof(void*));
1062 ArtMethod* copy = fixup_adapter.ForwardObject(orig);
1063 if (orig != copy) {
1064 mirror::DexCache::SetElementPtrSize(new_methods, j, copy, sizeof(void*));
1065 }
1066 }
1067 }
1068 ArtField** fields = dex_cache->GetResolvedFields();
1069 if (fields != nullptr) {
1070 ArtField** new_fields = fixup_adapter.ForwardObject(fields);
1071 if (fields != new_fields) {
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001072 dex_cache->SetResolvedFields(new_fields);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001073 }
1074 for (size_t j = 0, num = dex_cache->NumResolvedFields(); j != num; ++j) {
1075 ArtField* orig = mirror::DexCache::GetElementPtrSize(new_fields, j, sizeof(void*));
1076 ArtField* copy = fixup_adapter.ForwardObject(orig);
1077 if (orig != copy) {
1078 mirror::DexCache::SetElementPtrSize(new_fields, j, copy, sizeof(void*));
1079 }
1080 }
1081 }
1082 }
1083 }
1084 {
1085 // Only touches objects in the app image, no need for mutator lock.
1086 TimingLogger::ScopedTiming timing("Fixup methods", &logger);
1087 FixupArtMethodVisitor method_visitor(fixup_image, boot_image, boot_oat, app_image, app_oat);
1088 image_header.GetImageSection(ImageHeader::kSectionArtMethods).VisitPackedArtMethods(
1089 &method_visitor,
1090 target_base,
1091 sizeof(void*));
1092 }
1093 if (fixup_image) {
1094 {
1095 // Only touches objects in the app image, no need for mutator lock.
1096 TimingLogger::ScopedTiming timing("Fixup fields", &logger);
1097 FixupArtFieldVisitor field_visitor(boot_image, boot_oat, app_image, app_oat);
1098 image_header.GetImageSection(ImageHeader::kSectionArtFields).VisitPackedArtFields(
1099 &field_visitor,
1100 target_base);
1101 }
1102 // In the app image case, the image methods are actually in the boot image.
1103 image_header.RelocateImageMethods(boot_image.Delta());
1104 const auto& class_table_section = image_header.GetImageSection(ImageHeader::kSectionClassTable);
1105 if (class_table_section.Size() > 0u) {
1106 // Note that we require that ReadFromMemory does not make an internal copy of the elements.
1107 // This also relies on visit roots not doing any verification which could fail after we update
1108 // the roots to be the image addresses.
1109 ScopedObjectAccess soa(Thread::Current());
1110 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
1111 ClassTable temp_table;
1112 temp_table.ReadFromMemory(target_base + class_table_section.Offset());
1113 FixupRootVisitor root_visitor(boot_image, boot_oat, app_image, app_oat);
1114 temp_table.VisitRoots(root_visitor);
1115 }
1116 }
1117 if (VLOG_IS_ON(image)) {
1118 logger.Dump(LOG(INFO));
1119 }
1120 return true;
1121}
1122
1123ImageSpace* ImageSpace::Init(const char* image_filename,
1124 const char* image_location,
1125 bool validate_oat_file,
1126 const OatFile* oat_file,
1127 std::string* error_msg) {
Narayan Kamath52f84882014-05-02 10:10:39 +01001128 CHECK(image_filename != nullptr);
1129 CHECK(image_location != nullptr);
Ian Rogers1d54e732013-05-02 21:10:01 -07001130
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001131 TimingLogger logger(__FUNCTION__, true, false);
1132 VLOG(image) << "ImageSpace::Init entering image_filename=" << image_filename;
Nicolas Geoffray1bc977c2016-01-23 14:15:49 +00001133
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001134 std::unique_ptr<File> file;
1135 {
1136 TimingLogger::ScopedTiming timing("OpenImageFile", &logger);
1137 file.reset(OS::OpenFileForReading(image_filename));
1138 if (file == nullptr) {
1139 *error_msg = StringPrintf("Failed to open '%s'", image_filename);
1140 return nullptr;
1141 }
Nicolas Geoffray1bc977c2016-01-23 14:15:49 +00001142 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001143 ImageHeader temp_image_header;
1144 ImageHeader* image_header = &temp_image_header;
1145 {
1146 TimingLogger::ScopedTiming timing("ReadImageHeader", &logger);
1147 bool success = file->ReadFully(image_header, sizeof(*image_header));
1148 if (!success || !image_header->IsValid()) {
1149 *error_msg = StringPrintf("Invalid image header in '%s'", image_filename);
1150 return nullptr;
1151 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001152 }
Mathieu Chartierceb07b32015-12-10 09:33:21 -08001153 // Check that the file is larger or equal to the header size + data size.
1154 const uint64_t image_file_size = static_cast<uint64_t>(file->GetLength());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001155 if (image_file_size < sizeof(ImageHeader) + image_header->GetDataSize()) {
Mathieu Chartierceb07b32015-12-10 09:33:21 -08001156 *error_msg = StringPrintf("Image file truncated: %" PRIu64 " vs. %" PRIu64 ".",
1157 image_file_size,
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001158 sizeof(ImageHeader) + image_header->GetDataSize());
Andreas Gampe6c8b49f2015-02-19 11:42:36 -08001159 return nullptr;
1160 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001161
Mathieu Chartier9ff84602016-01-29 12:22:17 -08001162 if (oat_file != nullptr) {
1163 // If we have an oat file, check the oat file checksum. The oat file is only non-null for the
1164 // app image case. Otherwise, we open the oat file after the image and check the checksum there.
1165 const uint32_t oat_checksum = oat_file->GetOatHeader().GetChecksum();
1166 const uint32_t image_oat_checksum = image_header->GetOatChecksum();
1167 if (oat_checksum != image_oat_checksum) {
1168 *error_msg = StringPrintf("Oat checksum 0x%x does not match the image one 0x%x in image %s",
1169 oat_checksum,
1170 image_oat_checksum,
1171 image_filename);
1172 return nullptr;
1173 }
1174 }
1175
Jeff Haodcdc85b2015-12-04 14:06:18 -08001176 if (VLOG_IS_ON(startup)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001177 LOG(INFO) << "Dumping image sections";
1178 for (size_t i = 0; i < ImageHeader::kSectionCount; ++i) {
1179 const auto section_idx = static_cast<ImageHeader::ImageSections>(i);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001180 auto& section = image_header->GetImageSection(section_idx);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001181 LOG(INFO) << section_idx << " start="
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001182 << reinterpret_cast<void*>(image_header->GetImageBegin() + section.Offset()) << " "
1183 << section;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001184 }
1185 }
1186
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001187 const auto& bitmap_section = image_header->GetImageSection(ImageHeader::kSectionImageBitmap);
Mathieu Chartierceb07b32015-12-10 09:33:21 -08001188 // The location we want to map from is the first aligned page after the end of the stored
1189 // (possibly compressed) data.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001190 const size_t image_bitmap_offset = RoundUp(sizeof(ImageHeader) + image_header->GetDataSize(),
Mathieu Chartierceb07b32015-12-10 09:33:21 -08001191 kPageSize);
1192 const size_t end_of_bitmap = image_bitmap_offset + bitmap_section.Size();
Mathieu Chartierc7853442015-03-27 14:35:38 -07001193 if (end_of_bitmap != image_file_size) {
1194 *error_msg = StringPrintf(
1195 "Image file size does not equal end of bitmap: size=%" PRIu64 " vs. %zu.", image_file_size,
1196 end_of_bitmap);
Andreas Gampe6c8b49f2015-02-19 11:42:36 -08001197 return nullptr;
1198 }
1199
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001200 // The preferred address to map the image, null specifies any address. If we manage to map the
1201 // image at the image begin, the amount of fixup work required is minimized.
1202 std::vector<uint8_t*> addresses(1, image_header->GetImageBegin());
1203 if (image_header->IsPic()) {
1204 // Can also map at a random low_4gb address since we can relocate in-place.
1205 addresses.push_back(nullptr);
1206 }
1207
Mathieu Chartier31e89252013-08-28 11:29:12 -07001208 // Note: The image header is part of the image due to mmap page alignment required of offset.
Mathieu Chartierceb07b32015-12-10 09:33:21 -08001209 std::unique_ptr<MemMap> map;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001210 std::string temp_error_msg;
1211 for (uint8_t* address : addresses) {
1212 TimingLogger::ScopedTiming timing("MapImageFile", &logger);
1213 // Only care about the error message for the last address in addresses. We want to avoid the
1214 // overhead of printing the process maps if we can relocate.
1215 std::string* out_error_msg = (address == addresses.back()) ? &temp_error_msg : nullptr;
1216 if (image_header->GetStorageMode() == ImageHeader::kStorageModeUncompressed) {
1217 map.reset(MemMap::MapFileAtAddress(address,
1218 image_header->GetImageSize(),
1219 PROT_READ | PROT_WRITE,
1220 MAP_PRIVATE,
1221 file->Fd(),
1222 0,
1223 /*low_4gb*/true,
1224 /*reuse*/false,
1225 image_filename,
1226 /*out*/out_error_msg));
1227 } else {
1228 // Reserve output and decompress into it.
1229 map.reset(MemMap::MapAnonymous(image_location,
1230 address,
1231 image_header->GetImageSize(),
1232 PROT_READ | PROT_WRITE,
1233 /*low_4gb*/true,
1234 /*reuse*/false,
1235 out_error_msg));
1236 if (map != nullptr) {
1237 const size_t stored_size = image_header->GetDataSize();
1238 const size_t write_offset = sizeof(ImageHeader); // Skip the header.
1239 std::unique_ptr<MemMap> temp_map(MemMap::MapFile(sizeof(ImageHeader) + stored_size,
1240 PROT_READ,
1241 MAP_PRIVATE,
1242 file->Fd(),
1243 /*offset*/0,
1244 /*low_4gb*/false,
1245 image_filename,
1246 out_error_msg));
1247 if (temp_map == nullptr) {
1248 DCHECK(!out_error_msg->empty());
1249 return nullptr;
1250 }
1251 memcpy(map->Begin(), image_header, sizeof(ImageHeader));
1252 const uint64_t start = NanoTime();
1253 const size_t decompressed_size = LZ4_decompress_safe(
1254 reinterpret_cast<char*>(temp_map->Begin()) + sizeof(ImageHeader),
1255 reinterpret_cast<char*>(map->Begin()) + write_offset,
1256 stored_size,
1257 map->Size());
1258 VLOG(image) << "Decompressing image took " << PrettyDuration(NanoTime() - start);
1259 if (decompressed_size + sizeof(ImageHeader) != image_header->GetImageSize()) {
1260 *error_msg = StringPrintf("Decompressed size does not match expected image size %zu vs %zu",
1261 decompressed_size + sizeof(ImageHeader),
1262 image_header->GetImageSize());
1263 return nullptr;
1264 }
1265 }
1266 }
Mathieu Chartierceb07b32015-12-10 09:33:21 -08001267 if (map != nullptr) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001268 break;
Mathieu Chartierceb07b32015-12-10 09:33:21 -08001269 }
1270 }
1271
Mathieu Chartier42bddce2015-11-09 15:16:56 -08001272 if (map == nullptr) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001273 DCHECK(!temp_error_msg.empty());
1274 *error_msg = temp_error_msg;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001275 return nullptr;
Ian Rogers1d54e732013-05-02 21:10:01 -07001276 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001277 DCHECK_EQ(0, memcmp(image_header, map->Begin(), sizeof(ImageHeader)));
Ian Rogers1d54e732013-05-02 21:10:01 -07001278
Mathieu Chartierceb07b32015-12-10 09:33:21 -08001279 std::unique_ptr<MemMap> image_bitmap_map(MemMap::MapFileAtAddress(nullptr,
1280 bitmap_section.Size(),
1281 PROT_READ, MAP_PRIVATE,
1282 file->Fd(),
1283 image_bitmap_offset,
1284 /*low_4gb*/false,
1285 /*reuse*/false,
1286 image_filename,
1287 error_msg));
1288 if (image_bitmap_map == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001289 *error_msg = StringPrintf("Failed to map image bitmap: %s", error_msg->c_str());
1290 return nullptr;
1291 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001292 // Loaded the map, use the image header from the file now in case we patch it with
1293 // RelocateInPlace.
1294 image_header = reinterpret_cast<ImageHeader*>(map->Begin());
1295 const uint32_t bitmap_index = bitmap_index_.FetchAndAddSequentiallyConsistent(1);
1296 std::string bitmap_name(StringPrintf("imagespace %s live-bitmap %u",
1297 image_filename,
Mathieu Chartier31e89252013-08-28 11:29:12 -07001298 bitmap_index));
Mathieu Chartier2d124ec2016-01-05 18:03:15 -08001299 // Bitmap only needs to cover until the end of the mirror objects section.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001300 const ImageSection& image_objects = image_header->GetImageSection(ImageHeader::kSectionObjects);
1301 // We only want the mirror object, not the ArtFields and ArtMethods.
1302 uint8_t* const image_end = map->Begin() + image_objects.End();
1303 std::unique_ptr<accounting::ContinuousSpaceBitmap> bitmap;
1304 {
1305 TimingLogger::ScopedTiming timing("CreateImageBitmap", &logger);
1306 bitmap.reset(
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001307 accounting::ContinuousSpaceBitmap::CreateFromMemMap(
Mathieu Chartierceb07b32015-12-10 09:33:21 -08001308 bitmap_name,
1309 image_bitmap_map.release(),
1310 reinterpret_cast<uint8_t*>(map->Begin()),
Mathieu Chartier2d124ec2016-01-05 18:03:15 -08001311 image_objects.End()));
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001312 if (bitmap == nullptr) {
1313 *error_msg = StringPrintf("Could not create bitmap '%s'", bitmap_name.c_str());
1314 return nullptr;
1315 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001316 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001317 {
1318 TimingLogger::ScopedTiming timing("RelocateImage", &logger);
1319 if (!RelocateInPlace(*image_header,
1320 map->Begin(),
1321 bitmap.get(),
1322 oat_file,
1323 error_msg)) {
1324 return nullptr;
1325 }
1326 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001327 // We only want the mirror object, not the ArtFields and ArtMethods.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001328 std::unique_ptr<ImageSpace> space(new ImageSpace(image_filename,
1329 image_location,
1330 map.release(),
1331 bitmap.release(),
Mathieu Chartier2d124ec2016-01-05 18:03:15 -08001332 image_end));
Hiroshi Yamauchibd0fb612014-05-20 13:46:00 -07001333
1334 // VerifyImageAllocations() will be called later in Runtime::Init()
1335 // as some class roots like ArtMethod::java_lang_reflect_ArtMethod_
1336 // and ArtField::java_lang_reflect_ArtField_, which are used from
1337 // Object::SizeOf() which VerifyImageAllocations() calls, are not
1338 // set yet at this point.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001339 if (oat_file == nullptr) {
1340 TimingLogger::ScopedTiming timing("OpenOatFile", &logger);
1341 space->oat_file_.reset(space->OpenOatFile(image_filename, error_msg));
1342 if (space->oat_file_ == nullptr) {
1343 DCHECK(!error_msg->empty());
1344 return nullptr;
1345 }
1346 space->oat_file_non_owned_ = space->oat_file_.get();
1347 } else {
1348 space->oat_file_non_owned_ = oat_file;
Nicolas Geoffray1bc977c2016-01-23 14:15:49 +00001349 }
Nicolas Geoffray1bc977c2016-01-23 14:15:49 +00001350
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001351 if (validate_oat_file) {
1352 TimingLogger::ScopedTiming timing("ValidateOatFile", &logger);
1353 if (!space->ValidateOatFile(error_msg)) {
1354 DCHECK(!error_msg->empty());
1355 return nullptr;
1356 }
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001357 }
1358
Vladimir Marko7624d252014-05-02 14:40:15 +01001359 Runtime* runtime = Runtime::Current();
Vladimir Marko7624d252014-05-02 14:40:15 +01001360
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001361 // If oat_file is null, then it is the boot image space. Use oat_file_non_owned_ from the space
1362 // to set the runtime methods.
1363 CHECK_EQ(oat_file != nullptr, image_header->IsAppImage());
1364 if (image_header->IsAppImage()) {
1365 CHECK_EQ(runtime->GetResolutionMethod(),
1366 image_header->GetImageMethod(ImageHeader::kResolutionMethod));
1367 CHECK_EQ(runtime->GetImtConflictMethod(),
1368 image_header->GetImageMethod(ImageHeader::kImtConflictMethod));
1369 CHECK_EQ(runtime->GetImtUnimplementedMethod(),
1370 image_header->GetImageMethod(ImageHeader::kImtUnimplementedMethod));
1371 CHECK_EQ(runtime->GetCalleeSaveMethod(Runtime::kSaveAll),
1372 image_header->GetImageMethod(ImageHeader::kCalleeSaveMethod));
1373 CHECK_EQ(runtime->GetCalleeSaveMethod(Runtime::kRefsOnly),
1374 image_header->GetImageMethod(ImageHeader::kRefsOnlySaveMethod));
1375 CHECK_EQ(runtime->GetCalleeSaveMethod(Runtime::kRefsAndArgs),
1376 image_header->GetImageMethod(ImageHeader::kRefsAndArgsSaveMethod));
1377 } else if (!runtime->HasResolutionMethod()) {
1378 runtime->SetInstructionSet(space->oat_file_non_owned_->GetOatHeader().GetInstructionSet());
1379 runtime->SetResolutionMethod(image_header->GetImageMethod(ImageHeader::kResolutionMethod));
1380 runtime->SetImtConflictMethod(image_header->GetImageMethod(ImageHeader::kImtConflictMethod));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001381 runtime->SetImtUnimplementedMethod(
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001382 image_header->GetImageMethod(ImageHeader::kImtUnimplementedMethod));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001383 runtime->SetCalleeSaveMethod(
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001384 image_header->GetImageMethod(ImageHeader::kCalleeSaveMethod), Runtime::kSaveAll);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001385 runtime->SetCalleeSaveMethod(
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001386 image_header->GetImageMethod(ImageHeader::kRefsOnlySaveMethod), Runtime::kRefsOnly);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001387 runtime->SetCalleeSaveMethod(
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001388 image_header->GetImageMethod(ImageHeader::kRefsAndArgsSaveMethod), Runtime::kRefsAndArgs);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001389 }
Vladimir Marko7624d252014-05-02 14:40:15 +01001390
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001391 VLOG(image) << "ImageSpace::Init exiting " << *space.get();
1392 if (VLOG_IS_ON(image)) {
1393 logger.Dump(LOG(INFO));
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001394 }
1395 return space.release();
1396}
1397
Nicolas Geoffray9583fbc2014-02-28 15:21:07 +00001398OatFile* ImageSpace::OpenOatFile(const char* image_path, std::string* error_msg) const {
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001399 const ImageHeader& image_header = GetImageHeader();
Nicolas Geoffray9583fbc2014-02-28 15:21:07 +00001400 std::string oat_filename = ImageHeader::GetOatLocationFromImageLocation(image_path);
1401
Igor Murashkin46774762014-10-22 11:37:02 -07001402 CHECK(image_header.GetOatDataBegin() != nullptr);
1403
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -07001404 OatFile* oat_file = OatFile::Open(oat_filename,
1405 oat_filename,
1406 image_header.GetOatDataBegin(),
Igor Murashkin46774762014-10-22 11:37:02 -07001407 image_header.GetOatFileBegin(),
Richard Uhlere5fed032015-03-18 08:21:11 -07001408 !Runtime::Current()->IsAotCompiler(),
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -07001409 nullptr,
1410 error_msg);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001411 if (oat_file == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001412 *error_msg = StringPrintf("Failed to open oat file '%s' referenced from image %s: %s",
1413 oat_filename.c_str(), GetName(), error_msg->c_str());
1414 return nullptr;
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001415 }
1416 uint32_t oat_checksum = oat_file->GetOatHeader().GetChecksum();
1417 uint32_t image_oat_checksum = image_header.GetOatChecksum();
1418 if (oat_checksum != image_oat_checksum) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001419 *error_msg = StringPrintf("Failed to match oat file checksum 0x%x to expected oat checksum 0x%x"
1420 " in image %s", oat_checksum, image_oat_checksum, GetName());
1421 return nullptr;
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001422 }
Alex Lighta59dd802014-07-02 16:28:08 -07001423 int32_t image_patch_delta = image_header.GetPatchDelta();
1424 int32_t oat_patch_delta = oat_file->GetOatHeader().GetImagePatchDelta();
Igor Murashkin46774762014-10-22 11:37:02 -07001425 if (oat_patch_delta != image_patch_delta && !image_header.CompilePic()) {
Alex Lighta59dd802014-07-02 16:28:08 -07001426 // We should have already relocated by this point. Bail out.
1427 *error_msg = StringPrintf("Failed to match oat file patch delta %d to expected patch delta %d "
1428 "in image %s", oat_patch_delta, image_patch_delta, GetName());
1429 return nullptr;
1430 }
1431
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001432 return oat_file;
1433}
1434
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001435bool ImageSpace::ValidateOatFile(std::string* error_msg) const {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001436 CHECK(oat_file_.get() != nullptr);
Mathieu Chartier31e89252013-08-28 11:29:12 -07001437 for (const OatFile::OatDexFile* oat_dex_file : oat_file_->GetOatDexFiles()) {
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001438 const std::string& dex_file_location = oat_dex_file->GetDexFileLocation();
1439 uint32_t dex_file_location_checksum;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001440 if (!DexFile::GetChecksum(dex_file_location.c_str(), &dex_file_location_checksum, error_msg)) {
1441 *error_msg = StringPrintf("Failed to get checksum of dex file '%s' referenced by image %s: "
1442 "%s", dex_file_location.c_str(), GetName(), error_msg->c_str());
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001443 return false;
1444 }
1445 if (dex_file_location_checksum != oat_dex_file->GetDexFileLocationChecksum()) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001446 *error_msg = StringPrintf("ValidateOatFile found checksum mismatch between oat file '%s' and "
1447 "dex file '%s' (0x%x != 0x%x)",
1448 oat_file_->GetLocation().c_str(), dex_file_location.c_str(),
1449 oat_dex_file->GetDexFileLocationChecksum(),
1450 dex_file_location_checksum);
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001451 return false;
1452 }
1453 }
1454 return true;
1455}
1456
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001457const OatFile* ImageSpace::GetOatFile() const {
Andreas Gampe88da3b02015-06-12 20:38:49 -07001458 return oat_file_non_owned_;
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001459}
1460
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -07001461std::unique_ptr<const OatFile> ImageSpace::ReleaseOatFile() {
1462 CHECK(oat_file_ != nullptr);
1463 return std::move(oat_file_);
Ian Rogers1d54e732013-05-02 21:10:01 -07001464}
1465
Ian Rogers1d54e732013-05-02 21:10:01 -07001466void ImageSpace::Dump(std::ostream& os) const {
1467 os << GetType()
Mathieu Chartier590fee92013-09-13 13:46:47 -07001468 << " begin=" << reinterpret_cast<void*>(Begin())
Ian Rogers1d54e732013-05-02 21:10:01 -07001469 << ",end=" << reinterpret_cast<void*>(End())
1470 << ",size=" << PrettySize(Size())
1471 << ",name=\"" << GetName() << "\"]";
1472}
1473
Andreas Gampe8994a042015-12-30 19:03:17 +00001474void ImageSpace::CreateMultiImageLocations(const std::string& input_image_file_name,
1475 const std::string& boot_classpath,
1476 std::vector<std::string>* image_file_names) {
1477 DCHECK(image_file_names != nullptr);
1478
1479 std::vector<std::string> images;
1480 Split(boot_classpath, ':', &images);
1481
1482 // Add the rest into the list. We have to adjust locations, possibly:
1483 //
1484 // For example, image_file_name is /a/b/c/d/e.art
1485 // images[0] is f/c/d/e.art
1486 // ----------------------------------------------
1487 // images[1] is g/h/i/j.art -> /a/b/h/i/j.art
1488
1489 // Derive pattern.
1490 std::vector<std::string> left;
1491 Split(input_image_file_name, '/', &left);
1492 std::vector<std::string> right;
1493 Split(images[0], '/', &right);
1494
1495 size_t common = 1;
1496 while (common < left.size() && common < right.size()) {
1497 if (left[left.size() - common - 1] != right[right.size() - common - 1]) {
1498 break;
1499 }
1500 common++;
1501 }
1502
1503 std::vector<std::string> prefix_vector(left.begin(), left.end() - common);
1504 std::string common_prefix = Join(prefix_vector, '/');
1505 if (!common_prefix.empty() && common_prefix[0] != '/' && input_image_file_name[0] == '/') {
1506 common_prefix = "/" + common_prefix;
1507 }
1508
1509 // Apply pattern to images[1] .. images[n].
1510 for (size_t i = 1; i < images.size(); ++i) {
1511 std::string image = images[i];
1512
1513 size_t rslash = std::string::npos;
1514 for (size_t j = 0; j < common; ++j) {
1515 if (rslash != std::string::npos) {
1516 rslash--;
1517 }
1518
1519 rslash = image.rfind('/', rslash);
1520 if (rslash == std::string::npos) {
1521 rslash = 0;
1522 }
1523 if (rslash == 0) {
1524 break;
1525 }
1526 }
1527 std::string image_part = image.substr(rslash);
1528
1529 std::string new_image = common_prefix + (StartsWith(image_part, "/") ? "" : "/") +
1530 image_part;
1531 image_file_names->push_back(new_image);
1532 }
1533}
1534
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001535ImageSpace* ImageSpace::CreateFromAppImage(const char* image,
1536 const OatFile* oat_file,
1537 std::string* error_msg) {
1538 return gc::space::ImageSpace::Init(image,
1539 image,
1540 /*validate_oat_file*/false,
1541 oat_file,
1542 /*out*/error_msg);
1543}
1544
Ian Rogers1d54e732013-05-02 21:10:01 -07001545} // namespace space
1546} // namespace gc
1547} // namespace art