blob: a40e408bc84484f39f50270126f45bd6dac1a587 [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
Mathieu Chartierceb07b32015-12-10 09:33:21 -080019#include <lz4.h>
20#include <random>
Andreas Gampe70be1fb2014-10-31 16:45:19 -070021#include <sys/statvfs.h>
Alex Light25396132014-08-27 15:37:23 -070022#include <sys/types.h>
Narayan Kamath5a2be3f2015-02-16 13:51:51 +000023#include <unistd.h>
Alex Light25396132014-08-27 15:37:23 -070024
Mathieu Chartiere401d142015-04-22 13:56:20 -070025#include "art_method.h"
Andreas Gampe542451c2016-07-26 09:02:02 -070026#include "base/enums.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"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080030#include "base/systrace.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010031#include "base/time_utils.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"
Andreas Gampebec63582015-11-20 19:26:51 -080034#include "image_space_fs.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070035#include "mirror/class-inl.h"
36#include "mirror/object-inl.h"
Brian Carlstrom56d947f2013-07-15 13:14:23 -070037#include "oat_file.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070038#include "os.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070039#include "space-inl.h"
40#include "utils.h"
41
42namespace art {
43namespace gc {
44namespace space {
45
Ian Rogersef7d42f2014-01-06 12:55:46 -080046Atomic<uint32_t> ImageSpace::bitmap_index_(0);
Ian Rogers1d54e732013-05-02 21:10:01 -070047
Jeff Haodcdc85b2015-12-04 14:06:18 -080048ImageSpace::ImageSpace(const std::string& image_filename,
49 const char* image_location,
50 MemMap* mem_map,
51 accounting::ContinuousSpaceBitmap* live_bitmap,
Mathieu Chartier2d124ec2016-01-05 18:03:15 -080052 uint8_t* end)
53 : MemMapSpace(image_filename,
54 mem_map,
55 mem_map->Begin(),
56 end,
57 end,
Narayan Kamath52f84882014-05-02 10:10:39 +010058 kGcRetentionPolicyNeverCollect),
Jeff Haodcdc85b2015-12-04 14:06:18 -080059 oat_file_non_owned_(nullptr),
Mathieu Chartier2d124ec2016-01-05 18:03:15 -080060 image_location_(image_location) {
Mathieu Chartier590fee92013-09-13 13:46:47 -070061 DCHECK(live_bitmap != nullptr);
Mathieu Chartier31e89252013-08-28 11:29:12 -070062 live_bitmap_.reset(live_bitmap);
Ian Rogers1d54e732013-05-02 21:10:01 -070063}
64
Alex Lightcf4bf382014-07-24 11:29:14 -070065static int32_t ChooseRelocationOffsetDelta(int32_t min_delta, int32_t max_delta) {
66 CHECK_ALIGNED(min_delta, kPageSize);
67 CHECK_ALIGNED(max_delta, kPageSize);
68 CHECK_LT(min_delta, max_delta);
69
Alex Light15324762015-11-19 11:03:10 -080070 int32_t r = GetRandomNumber<int32_t>(min_delta, max_delta);
Alex Lightcf4bf382014-07-24 11:29:14 -070071 if (r % 2 == 0) {
72 r = RoundUp(r, kPageSize);
73 } else {
74 r = RoundDown(r, kPageSize);
75 }
76 CHECK_LE(min_delta, r);
77 CHECK_GE(max_delta, r);
78 CHECK_ALIGNED(r, kPageSize);
79 return r;
80}
81
Andreas Gampea463b6a2016-08-12 21:53:32 -070082static int32_t ChooseRelocationOffsetDelta() {
83 return ChooseRelocationOffsetDelta(ART_BASE_ADDRESS_MIN_DELTA, ART_BASE_ADDRESS_MAX_DELTA);
84}
85
86static bool GenerateImage(const std::string& image_filename,
87 InstructionSet image_isa,
Alex Light25396132014-08-27 15:37:23 -070088 std::string* error_msg) {
Brian Carlstrom56d947f2013-07-15 13:14:23 -070089 const std::string boot_class_path_string(Runtime::Current()->GetBootClassPathString());
90 std::vector<std::string> boot_class_path;
Ian Rogers6f3dbba2014-10-14 17:41:57 -070091 Split(boot_class_path_string, ':', &boot_class_path);
Brian Carlstrom56d947f2013-07-15 13:14:23 -070092 if (boot_class_path.empty()) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -070093 *error_msg = "Failed to generate image because no boot class path specified";
94 return false;
Brian Carlstrom56d947f2013-07-15 13:14:23 -070095 }
Alex Light25396132014-08-27 15:37:23 -070096 // We should clean up so we are more likely to have room for the image.
97 if (Runtime::Current()->IsZygote()) {
Andreas Gampe3c13a792014-09-18 20:56:04 -070098 LOG(INFO) << "Pruning dalvik-cache since we are generating an image and will need to recompile";
Narayan Kamath28bc9872014-11-07 17:46:28 +000099 PruneDalvikCache(image_isa);
Alex Light25396132014-08-27 15:37:23 -0700100 }
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700101
Mathieu Chartier8bbc8c02013-07-31 16:27:01 -0700102 std::vector<std::string> arg_vector;
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700103
Tsu Chiang Chuang12e6d742014-05-22 10:22:25 -0700104 std::string dex2oat(Runtime::Current()->GetCompilerExecutable());
Mathieu Chartier08d7d442013-07-31 18:08:51 -0700105 arg_vector.push_back(dex2oat);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700106
107 std::string image_option_string("--image=");
Narayan Kamath52f84882014-05-02 10:10:39 +0100108 image_option_string += image_filename;
Mathieu Chartier8bbc8c02013-07-31 16:27:01 -0700109 arg_vector.push_back(image_option_string);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700110
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700111 for (size_t i = 0; i < boot_class_path.size(); i++) {
Mathieu Chartier8bbc8c02013-07-31 16:27:01 -0700112 arg_vector.push_back(std::string("--dex-file=") + boot_class_path[i]);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700113 }
114
115 std::string oat_file_option_string("--oat-file=");
Brian Carlstrom2f1e15c2014-10-27 16:27:06 -0700116 oat_file_option_string += ImageHeader::GetOatLocationFromImageLocation(image_filename);
Mathieu Chartier8bbc8c02013-07-31 16:27:01 -0700117 arg_vector.push_back(oat_file_option_string);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700118
Sebastien Hertz0de11332015-05-13 12:14:05 +0200119 // Note: we do not generate a fully debuggable boot image so we do not pass the
120 // compiler flag --debuggable here.
121
Igor Murashkinb1d8c312015-08-04 11:18:43 -0700122 Runtime::Current()->AddCurrentRuntimeFeaturesAsDex2OatArguments(&arg_vector);
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700123 CHECK_EQ(image_isa, kRuntimeISA)
124 << "We should always be generating an image for the current isa.";
Ian Rogers8afeb852014-04-02 14:55:49 -0700125
Andreas Gampea463b6a2016-08-12 21:53:32 -0700126 int32_t base_offset = ChooseRelocationOffsetDelta();
Alex Lightcf4bf382014-07-24 11:29:14 -0700127 LOG(INFO) << "Using an offset of 0x" << std::hex << base_offset << " from default "
128 << "art base address of 0x" << std::hex << ART_BASE_ADDRESS;
129 arg_vector.push_back(StringPrintf("--base=0x%x", ART_BASE_ADDRESS + base_offset));
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700130
Brian Carlstrom57309db2014-07-30 15:13:25 -0700131 if (!kIsTargetBuild) {
Mathieu Chartier8bbc8c02013-07-31 16:27:01 -0700132 arg_vector.push_back("--host");
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700133 }
134
Brian Carlstrom6449c622014-02-10 23:48:36 -0800135 const std::vector<std::string>& compiler_options = Runtime::Current()->GetImageCompilerOptions();
Brian Carlstrom2ec65202014-03-03 15:16:37 -0800136 for (size_t i = 0; i < compiler_options.size(); ++i) {
Brian Carlstrom6449c622014-02-10 23:48:36 -0800137 arg_vector.push_back(compiler_options[i].c_str());
138 }
139
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700140 std::string command_line(Join(arg_vector, ' '));
141 LOG(INFO) << "GenerateImage: " << command_line;
Brian Carlstrom6449c622014-02-10 23:48:36 -0800142 return Exec(arg_vector, error_msg);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700143}
144
Andreas Gampea463b6a2016-08-12 21:53:32 -0700145static bool FindImageFilenameImpl(const char* image_location,
146 const InstructionSet image_isa,
147 bool* has_system,
148 std::string* system_filename,
149 bool* dalvik_cache_exists,
150 std::string* dalvik_cache,
151 bool* is_global_cache,
152 bool* has_cache,
153 std::string* cache_filename) {
154 DCHECK(dalvik_cache != nullptr);
155
Alex Lighta59dd802014-07-02 16:28:08 -0700156 *has_system = false;
157 *has_cache = false;
Brian Carlstrom0e12bdc2014-05-14 17:44:28 -0700158 // image_location = /system/framework/boot.art
159 // system_image_location = /system/framework/<image_isa>/boot.art
160 std::string system_image_filename(GetSystemImageFilename(image_location, image_isa));
161 if (OS::FileExists(system_image_filename.c_str())) {
Alex Lighta59dd802014-07-02 16:28:08 -0700162 *system_filename = system_image_filename;
163 *has_system = true;
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700164 }
Narayan Kamath52f84882014-05-02 10:10:39 +0100165
Alex Lighta59dd802014-07-02 16:28:08 -0700166 bool have_android_data = false;
167 *dalvik_cache_exists = false;
Andreas Gampea463b6a2016-08-12 21:53:32 -0700168 GetDalvikCache(GetInstructionSetString(image_isa),
169 true,
170 dalvik_cache,
171 &have_android_data,
172 dalvik_cache_exists,
173 is_global_cache);
Narayan Kamath52f84882014-05-02 10:10:39 +0100174
Alex Lighta59dd802014-07-02 16:28:08 -0700175 if (have_android_data && *dalvik_cache_exists) {
176 // Always set output location even if it does not exist,
177 // so that the caller knows where to create the image.
178 //
179 // image_location = /system/framework/boot.art
180 // *image_filename = /data/dalvik-cache/<image_isa>/boot.art
181 std::string error_msg;
Andreas Gampea463b6a2016-08-12 21:53:32 -0700182 if (!GetDalvikCacheFilename(image_location,
183 dalvik_cache->c_str(),
184 cache_filename,
185 &error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -0700186 LOG(WARNING) << error_msg;
187 return *has_system;
188 }
189 *has_cache = OS::FileExists(cache_filename->c_str());
190 }
191 return *has_system || *has_cache;
192}
193
Andreas Gampea463b6a2016-08-12 21:53:32 -0700194bool ImageSpace::FindImageFilename(const char* image_location,
195 const InstructionSet image_isa,
196 std::string* system_filename,
197 bool* has_system,
198 std::string* cache_filename,
199 bool* dalvik_cache_exists,
200 bool* has_cache,
201 bool* is_global_cache) {
202 std::string dalvik_cache_unused;
203 return FindImageFilenameImpl(image_location,
204 image_isa,
205 has_system,
206 system_filename,
207 dalvik_cache_exists,
208 &dalvik_cache_unused,
209 is_global_cache,
210 has_cache,
211 cache_filename);
212}
213
Alex Lighta59dd802014-07-02 16:28:08 -0700214static bool ReadSpecificImageHeader(const char* filename, ImageHeader* image_header) {
215 std::unique_ptr<File> image_file(OS::OpenFileForReading(filename));
216 if (image_file.get() == nullptr) {
217 return false;
218 }
219 const bool success = image_file->ReadFully(image_header, sizeof(ImageHeader));
220 if (!success || !image_header->IsValid()) {
221 return false;
222 }
223 return true;
224}
225
Alex Light6e183f22014-07-18 14:57:04 -0700226// Relocate the image at image_location to dest_filename and relocate it by a random amount.
Andreas Gampea463b6a2016-08-12 21:53:32 -0700227static bool RelocateImage(const char* image_location,
228 const char* dest_filename,
229 InstructionSet isa,
230 std::string* error_msg) {
Alex Light25396132014-08-27 15:37:23 -0700231 // We should clean up so we are more likely to have room for the image.
232 if (Runtime::Current()->IsZygote()) {
233 LOG(INFO) << "Pruning dalvik-cache since we are relocating an image and will need to recompile";
Narayan Kamath28bc9872014-11-07 17:46:28 +0000234 PruneDalvikCache(isa);
Alex Light25396132014-08-27 15:37:23 -0700235 }
236
Alex Lighta59dd802014-07-02 16:28:08 -0700237 std::string patchoat(Runtime::Current()->GetPatchoatExecutable());
238
239 std::string input_image_location_arg("--input-image-location=");
240 input_image_location_arg += image_location;
241
242 std::string output_image_filename_arg("--output-image-file=");
243 output_image_filename_arg += dest_filename;
244
Alex Lighta59dd802014-07-02 16:28:08 -0700245 std::string instruction_set_arg("--instruction-set=");
246 instruction_set_arg += GetInstructionSetString(isa);
247
248 std::string base_offset_arg("--base-offset-delta=");
Andreas Gampea463b6a2016-08-12 21:53:32 -0700249 StringAppendF(&base_offset_arg, "%d", ChooseRelocationOffsetDelta());
Alex Lighta59dd802014-07-02 16:28:08 -0700250
251 std::vector<std::string> argv;
252 argv.push_back(patchoat);
253
254 argv.push_back(input_image_location_arg);
255 argv.push_back(output_image_filename_arg);
256
Alex Lighta59dd802014-07-02 16:28:08 -0700257 argv.push_back(instruction_set_arg);
258 argv.push_back(base_offset_arg);
259
260 std::string command_line(Join(argv, ' '));
261 LOG(INFO) << "RelocateImage: " << command_line;
262 return Exec(argv, error_msg);
263}
264
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700265static ImageHeader* ReadSpecificImageHeader(const char* filename, std::string* error_msg) {
Alex Lighta59dd802014-07-02 16:28:08 -0700266 std::unique_ptr<ImageHeader> hdr(new ImageHeader);
267 if (!ReadSpecificImageHeader(filename, hdr.get())) {
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700268 *error_msg = StringPrintf("Unable to read image header for %s", filename);
Alex Lighta59dd802014-07-02 16:28:08 -0700269 return nullptr;
270 }
271 return hdr.release();
Narayan Kamath52f84882014-05-02 10:10:39 +0100272}
273
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700274ImageHeader* ImageSpace::ReadImageHeader(const char* image_location,
275 const InstructionSet image_isa,
276 std::string* error_msg) {
Alex Lighta59dd802014-07-02 16:28:08 -0700277 std::string system_filename;
278 bool has_system = false;
279 std::string cache_filename;
280 bool has_cache = false;
281 bool dalvik_cache_exists = false;
Andreas Gampe3c13a792014-09-18 20:56:04 -0700282 bool is_global_cache = false;
Alex Lighta59dd802014-07-02 16:28:08 -0700283 if (FindImageFilename(image_location, image_isa, &system_filename, &has_system,
Andreas Gampe3c13a792014-09-18 20:56:04 -0700284 &cache_filename, &dalvik_cache_exists, &has_cache, &is_global_cache)) {
Alex Lighta59dd802014-07-02 16:28:08 -0700285 if (Runtime::Current()->ShouldRelocate()) {
286 if (has_system && has_cache) {
287 std::unique_ptr<ImageHeader> sys_hdr(new ImageHeader);
288 std::unique_ptr<ImageHeader> cache_hdr(new ImageHeader);
289 if (!ReadSpecificImageHeader(system_filename.c_str(), sys_hdr.get())) {
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700290 *error_msg = StringPrintf("Unable to read image header for %s at %s",
291 image_location, system_filename.c_str());
Alex Lighta59dd802014-07-02 16:28:08 -0700292 return nullptr;
293 }
294 if (!ReadSpecificImageHeader(cache_filename.c_str(), cache_hdr.get())) {
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700295 *error_msg = StringPrintf("Unable to read image header for %s at %s",
296 image_location, cache_filename.c_str());
Alex Lighta59dd802014-07-02 16:28:08 -0700297 return nullptr;
298 }
299 if (sys_hdr->GetOatChecksum() != cache_hdr->GetOatChecksum()) {
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700300 *error_msg = StringPrintf("Unable to find a relocated version of image file %s",
301 image_location);
Alex Lighta59dd802014-07-02 16:28:08 -0700302 return nullptr;
303 }
304 return cache_hdr.release();
305 } else if (!has_cache) {
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700306 *error_msg = StringPrintf("Unable to find a relocated version of image file %s",
307 image_location);
Alex Lighta59dd802014-07-02 16:28:08 -0700308 return nullptr;
309 } else if (!has_system && has_cache) {
310 // This can probably just use the cache one.
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700311 return ReadSpecificImageHeader(cache_filename.c_str(), error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -0700312 }
313 } else {
314 // We don't want to relocate, Just pick the appropriate one if we have it and return.
315 if (has_system && has_cache) {
316 // We want the cache if the checksum matches, otherwise the system.
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700317 std::unique_ptr<ImageHeader> system(ReadSpecificImageHeader(system_filename.c_str(),
318 error_msg));
319 std::unique_ptr<ImageHeader> cache(ReadSpecificImageHeader(cache_filename.c_str(),
320 error_msg));
Alex Lighta59dd802014-07-02 16:28:08 -0700321 if (system.get() == nullptr ||
322 (cache.get() != nullptr && cache->GetOatChecksum() == system->GetOatChecksum())) {
323 return cache.release();
324 } else {
325 return system.release();
326 }
327 } else if (has_system) {
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700328 return ReadSpecificImageHeader(system_filename.c_str(), error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -0700329 } else if (has_cache) {
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700330 return ReadSpecificImageHeader(cache_filename.c_str(), error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -0700331 }
Narayan Kamath52f84882014-05-02 10:10:39 +0100332 }
Narayan Kamath52f84882014-05-02 10:10:39 +0100333 }
334
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700335 *error_msg = StringPrintf("Unable to find image file for %s", image_location);
Narayan Kamath52f84882014-05-02 10:10:39 +0100336 return nullptr;
337}
338
Andreas Gampea463b6a2016-08-12 21:53:32 -0700339static bool ChecksumsMatch(const char* image_a, const char* image_b, std::string* error_msg) {
340 DCHECK(error_msg != nullptr);
341
Alex Lighta59dd802014-07-02 16:28:08 -0700342 ImageHeader hdr_a;
343 ImageHeader hdr_b;
Andreas Gampea463b6a2016-08-12 21:53:32 -0700344
345 if (!ReadSpecificImageHeader(image_a, &hdr_a)) {
346 *error_msg = StringPrintf("Cannot read header of %s", image_a);
347 return false;
348 }
349 if (!ReadSpecificImageHeader(image_b, &hdr_b)) {
350 *error_msg = StringPrintf("Cannot read header of %s", image_b);
351 return false;
352 }
353
354 if (hdr_a.GetOatChecksum() != hdr_b.GetOatChecksum()) {
355 *error_msg = StringPrintf("Checksum mismatch: %u(%s) vs %u(%s)",
356 hdr_a.GetOatChecksum(),
357 image_a,
358 hdr_b.GetOatChecksum(),
359 image_b);
360 return false;
361 }
362
363 return true;
Alex Lighta59dd802014-07-02 16:28:08 -0700364}
365
Robert Sesekbfa1f8d2016-08-15 15:21:09 -0400366static bool CanWriteToDalvikCache(const InstructionSet isa) {
367 const std::string dalvik_cache = GetDalvikCache(GetInstructionSetString(isa));
368 if (access(dalvik_cache.c_str(), O_RDWR) == 0) {
369 return true;
370 } else if (errno != EACCES) {
371 PLOG(WARNING) << "CanWriteToDalvikCache returned error other than EACCES";
372 }
373 return false;
374}
375
376static bool ImageCreationAllowed(bool is_global_cache,
377 const InstructionSet isa,
378 std::string* error_msg) {
Andreas Gampe3c13a792014-09-18 20:56:04 -0700379 // Anyone can write into a "local" cache.
380 if (!is_global_cache) {
381 return true;
382 }
383
Robert Sesekbfa1f8d2016-08-15 15:21:09 -0400384 // Only the zygote running as root is allowed to create the global boot image.
385 // If the zygote is running as non-root (and cannot write to the dalvik-cache),
386 // then image creation is not allowed..
Andreas Gampe3c13a792014-09-18 20:56:04 -0700387 if (Runtime::Current()->IsZygote()) {
Robert Sesekbfa1f8d2016-08-15 15:21:09 -0400388 return CanWriteToDalvikCache(isa);
Andreas Gampe3c13a792014-09-18 20:56:04 -0700389 }
390
391 *error_msg = "Only the zygote can create the global boot image.";
392 return false;
393}
394
Mathieu Chartier31e89252013-08-28 11:29:12 -0700395void ImageSpace::VerifyImageAllocations() {
Ian Rogers13735952014-10-08 12:43:28 -0700396 uint8_t* current = Begin() + RoundUp(sizeof(ImageHeader), kObjectAlignment);
Mathieu Chartier31e89252013-08-28 11:29:12 -0700397 while (current < End()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700398 CHECK_ALIGNED(current, kObjectAlignment);
399 auto* obj = reinterpret_cast<mirror::Object*>(current);
Mathieu Chartier31e89252013-08-28 11:29:12 -0700400 CHECK(obj->GetClass() != nullptr) << "Image object at address " << obj << " has null class";
Mathieu Chartierc7853442015-03-27 14:35:38 -0700401 CHECK(live_bitmap_->Test(obj)) << PrettyTypeOf(obj);
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -0700402 if (kUseBakerOrBrooksReadBarrier) {
403 obj->AssertReadBarrierPointer();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800404 }
Mathieu Chartier31e89252013-08-28 11:29:12 -0700405 current += RoundUp(obj->SizeOf(), kObjectAlignment);
406 }
407}
408
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800409// Helper class for relocating from one range of memory to another.
410class RelocationRange {
411 public:
412 RelocationRange() = default;
413 RelocationRange(const RelocationRange&) = default;
414 RelocationRange(uintptr_t source, uintptr_t dest, uintptr_t length)
415 : source_(source),
416 dest_(dest),
417 length_(length) {}
418
Mathieu Chartier91edc622016-02-16 17:16:01 -0800419 bool InSource(uintptr_t address) const {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800420 return address - source_ < length_;
421 }
422
Mathieu Chartier91edc622016-02-16 17:16:01 -0800423 bool InDest(uintptr_t address) const {
424 return address - dest_ < length_;
425 }
426
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800427 // Translate a source address to the destination space.
428 uintptr_t ToDest(uintptr_t address) const {
Mathieu Chartier91edc622016-02-16 17:16:01 -0800429 DCHECK(InSource(address));
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800430 return address + Delta();
431 }
432
433 // Returns the delta between the dest from the source.
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800434 uintptr_t Delta() const {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800435 return dest_ - source_;
436 }
437
438 uintptr_t Source() const {
439 return source_;
440 }
441
442 uintptr_t Dest() const {
443 return dest_;
444 }
445
446 uintptr_t Length() const {
447 return length_;
448 }
449
450 private:
451 const uintptr_t source_;
452 const uintptr_t dest_;
453 const uintptr_t length_;
454};
455
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800456std::ostream& operator<<(std::ostream& os, const RelocationRange& reloc) {
457 return os << "(" << reinterpret_cast<const void*>(reloc.Source()) << "-"
458 << reinterpret_cast<const void*>(reloc.Source() + reloc.Length()) << ")->("
459 << reinterpret_cast<const void*>(reloc.Dest()) << "-"
460 << reinterpret_cast<const void*>(reloc.Dest() + reloc.Length()) << ")";
461}
462
Andreas Gampea463b6a2016-08-12 21:53:32 -0700463// Helper class encapsulating loading, so we can access private ImageSpace members (this is a
464// friend class), but not declare functions in the header.
465class ImageSpaceLoader {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800466 public:
Andreas Gampea463b6a2016-08-12 21:53:32 -0700467 static std::unique_ptr<ImageSpace> Load(const char* image_location,
468 const std::string& image_filename,
469 bool is_zygote,
470 bool is_global_cache,
Andreas Gampe44c8ed62016-08-19 16:43:00 -0700471 bool validate_oat_file,
Andreas Gampea463b6a2016-08-12 21:53:32 -0700472 std::string* error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700473 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampea463b6a2016-08-12 21:53:32 -0700474 // Note that we must not use the file descriptor associated with
475 // ScopedFlock::GetFile to Init the image file. We want the file
476 // descriptor (and the associated exclusive lock) to be released when
477 // we leave Create.
478 ScopedFlock image_lock;
479 // Should this be a RDWR lock? This is only a defensive measure, as at
480 // this point the image should exist.
481 // However, only the zygote can write into the global dalvik-cache, so
482 // restrict to zygote processes, or any process that isn't using
483 // /data/dalvik-cache (which we assume to be allowed to write there).
484 const bool rw_lock = is_zygote || !is_global_cache;
485 image_lock.Init(image_filename.c_str(),
486 rw_lock ? (O_CREAT | O_RDWR) : O_RDONLY /* flags */,
487 true /* block */,
488 error_msg);
489 VLOG(startup) << "Using image file " << image_filename.c_str() << " for image location "
490 << image_location;
491 // If we are in /system we can assume the image is good. We can also
492 // assume this if we are using a relocated image (i.e. image checksum
493 // matches) since this is only different by the offset. We need this to
494 // make sure that host tests continue to work.
495 // Since we are the boot image, pass null since we load the oat file from the boot image oat
496 // file name.
497 return Init(image_filename.c_str(),
498 image_location,
Andreas Gampe44c8ed62016-08-19 16:43:00 -0700499 validate_oat_file,
Andreas Gampea463b6a2016-08-12 21:53:32 -0700500 /* oat_file */nullptr,
501 error_msg);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800502 }
503
Andreas Gampea463b6a2016-08-12 21:53:32 -0700504 static std::unique_ptr<ImageSpace> Init(const char* image_filename,
505 const char* image_location,
506 bool validate_oat_file,
507 const OatFile* oat_file,
508 std::string* error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700509 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampea463b6a2016-08-12 21:53:32 -0700510 CHECK(image_filename != nullptr);
511 CHECK(image_location != nullptr);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800512
Andreas Gampea463b6a2016-08-12 21:53:32 -0700513 TimingLogger logger(__PRETTY_FUNCTION__, true, VLOG_IS_ON(image));
514 VLOG(image) << "ImageSpace::Init entering image_filename=" << image_filename;
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800515
Andreas Gampea463b6a2016-08-12 21:53:32 -0700516 std::unique_ptr<File> file;
Mathieu Chartier92ec5942016-04-11 12:03:48 -0700517 {
Andreas Gampea463b6a2016-08-12 21:53:32 -0700518 TimingLogger::ScopedTiming timing("OpenImageFile", &logger);
519 file.reset(OS::OpenFileForReading(image_filename));
520 if (file == nullptr) {
521 *error_msg = StringPrintf("Failed to open '%s'", image_filename);
522 return nullptr;
Mathieu Chartier92ec5942016-04-11 12:03:48 -0700523 }
Andreas Gampea463b6a2016-08-12 21:53:32 -0700524 }
525 ImageHeader temp_image_header;
526 ImageHeader* image_header = &temp_image_header;
527 {
528 TimingLogger::ScopedTiming timing("ReadImageHeader", &logger);
529 bool success = file->ReadFully(image_header, sizeof(*image_header));
530 if (!success || !image_header->IsValid()) {
531 *error_msg = StringPrintf("Invalid image header in '%s'", image_filename);
532 return nullptr;
533 }
534 }
535 // Check that the file is larger or equal to the header size + data size.
536 const uint64_t image_file_size = static_cast<uint64_t>(file->GetLength());
537 if (image_file_size < sizeof(ImageHeader) + image_header->GetDataSize()) {
538 *error_msg = StringPrintf("Image file truncated: %" PRIu64 " vs. %" PRIu64 ".",
539 image_file_size,
540 sizeof(ImageHeader) + image_header->GetDataSize());
541 return nullptr;
542 }
543
544 if (oat_file != nullptr) {
545 // If we have an oat file, check the oat file checksum. The oat file is only non-null for the
546 // app image case. Otherwise, we open the oat file after the image and check the checksum there.
547 const uint32_t oat_checksum = oat_file->GetOatHeader().GetChecksum();
548 const uint32_t image_oat_checksum = image_header->GetOatChecksum();
549 if (oat_checksum != image_oat_checksum) {
550 *error_msg = StringPrintf("Oat checksum 0x%x does not match the image one 0x%x in image %s",
551 oat_checksum,
552 image_oat_checksum,
553 image_filename);
554 return nullptr;
Mathieu Chartier92ec5942016-04-11 12:03:48 -0700555 }
556 }
557
Andreas Gampea463b6a2016-08-12 21:53:32 -0700558 if (VLOG_IS_ON(startup)) {
559 LOG(INFO) << "Dumping image sections";
560 for (size_t i = 0; i < ImageHeader::kSectionCount; ++i) {
561 const auto section_idx = static_cast<ImageHeader::ImageSections>(i);
562 auto& section = image_header->GetImageSection(section_idx);
563 LOG(INFO) << section_idx << " start="
564 << reinterpret_cast<void*>(image_header->GetImageBegin() + section.Offset()) << " "
565 << section;
Mathieu Chartier92ec5942016-04-11 12:03:48 -0700566 }
Andreas Gampea463b6a2016-08-12 21:53:32 -0700567 }
568
569 const auto& bitmap_section = image_header->GetImageSection(ImageHeader::kSectionImageBitmap);
570 // The location we want to map from is the first aligned page after the end of the stored
571 // (possibly compressed) data.
572 const size_t image_bitmap_offset = RoundUp(sizeof(ImageHeader) + image_header->GetDataSize(),
573 kPageSize);
574 const size_t end_of_bitmap = image_bitmap_offset + bitmap_section.Size();
575 if (end_of_bitmap != image_file_size) {
576 *error_msg = StringPrintf(
577 "Image file size does not equal end of bitmap: size=%" PRIu64 " vs. %zu.", image_file_size,
578 end_of_bitmap);
579 return nullptr;
580 }
581
582 std::unique_ptr<MemMap> map;
583 // GetImageBegin is the preferred address to map the image. If we manage to map the
584 // image at the image begin, the amount of fixup work required is minimized.
585 map.reset(LoadImageFile(image_filename,
586 image_location,
587 *image_header,
588 image_header->GetImageBegin(),
589 file->Fd(),
590 logger,
591 error_msg));
592 // If the header specifies PIC mode, we can also map at a random low_4gb address since we can
593 // relocate in-place.
594 if (map == nullptr && image_header->IsPic()) {
595 map.reset(LoadImageFile(image_filename,
596 image_location,
597 *image_header,
598 /* address */ nullptr,
599 file->Fd(),
600 logger,
601 error_msg));
602 }
603 // Were we able to load something and continue?
604 if (map == nullptr) {
605 DCHECK(!error_msg->empty());
606 return nullptr;
607 }
608 DCHECK_EQ(0, memcmp(image_header, map->Begin(), sizeof(ImageHeader)));
609
610 std::unique_ptr<MemMap> image_bitmap_map(MemMap::MapFileAtAddress(nullptr,
611 bitmap_section.Size(),
612 PROT_READ, MAP_PRIVATE,
613 file->Fd(),
614 image_bitmap_offset,
615 /*low_4gb*/false,
616 /*reuse*/false,
617 image_filename,
618 error_msg));
619 if (image_bitmap_map == nullptr) {
620 *error_msg = StringPrintf("Failed to map image bitmap: %s", error_msg->c_str());
621 return nullptr;
622 }
623 // Loaded the map, use the image header from the file now in case we patch it with
624 // RelocateInPlace.
625 image_header = reinterpret_cast<ImageHeader*>(map->Begin());
626 const uint32_t bitmap_index = ImageSpace::bitmap_index_.FetchAndAddSequentiallyConsistent(1);
627 std::string bitmap_name(StringPrintf("imagespace %s live-bitmap %u",
628 image_filename,
629 bitmap_index));
630 // Bitmap only needs to cover until the end of the mirror objects section.
631 const ImageSection& image_objects = image_header->GetImageSection(ImageHeader::kSectionObjects);
632 // We only want the mirror object, not the ArtFields and ArtMethods.
633 uint8_t* const image_end = map->Begin() + image_objects.End();
634 std::unique_ptr<accounting::ContinuousSpaceBitmap> bitmap;
635 {
636 TimingLogger::ScopedTiming timing("CreateImageBitmap", &logger);
637 bitmap.reset(
638 accounting::ContinuousSpaceBitmap::CreateFromMemMap(
639 bitmap_name,
640 image_bitmap_map.release(),
641 reinterpret_cast<uint8_t*>(map->Begin()),
642 image_objects.End()));
643 if (bitmap == nullptr) {
644 *error_msg = StringPrintf("Could not create bitmap '%s'", bitmap_name.c_str());
645 return nullptr;
646 }
647 }
648 {
649 TimingLogger::ScopedTiming timing("RelocateImage", &logger);
650 if (!RelocateInPlace(*image_header,
651 map->Begin(),
652 bitmap.get(),
653 oat_file,
654 error_msg)) {
655 return nullptr;
656 }
657 }
658 // We only want the mirror object, not the ArtFields and ArtMethods.
659 std::unique_ptr<ImageSpace> space(new ImageSpace(image_filename,
660 image_location,
661 map.release(),
662 bitmap.release(),
663 image_end));
664
665 // VerifyImageAllocations() will be called later in Runtime::Init()
666 // as some class roots like ArtMethod::java_lang_reflect_ArtMethod_
667 // and ArtField::java_lang_reflect_ArtField_, which are used from
668 // Object::SizeOf() which VerifyImageAllocations() calls, are not
669 // set yet at this point.
670 if (oat_file == nullptr) {
671 TimingLogger::ScopedTiming timing("OpenOatFile", &logger);
672 space->oat_file_ = OpenOatFile(*space, image_filename, error_msg);
673 if (space->oat_file_ == nullptr) {
674 DCHECK(!error_msg->empty());
675 return nullptr;
676 }
677 space->oat_file_non_owned_ = space->oat_file_.get();
678 } else {
679 space->oat_file_non_owned_ = oat_file;
680 }
681
682 if (validate_oat_file) {
683 TimingLogger::ScopedTiming timing("ValidateOatFile", &logger);
684 CHECK(space->oat_file_ != nullptr);
685 if (!ValidateOatFile(*space, *space->oat_file_, error_msg)) {
686 DCHECK(!error_msg->empty());
687 return nullptr;
688 }
689 }
690
691 Runtime* runtime = Runtime::Current();
692
693 // If oat_file is null, then it is the boot image space. Use oat_file_non_owned_ from the space
694 // to set the runtime methods.
695 CHECK_EQ(oat_file != nullptr, image_header->IsAppImage());
696 if (image_header->IsAppImage()) {
697 CHECK_EQ(runtime->GetResolutionMethod(),
698 image_header->GetImageMethod(ImageHeader::kResolutionMethod));
699 CHECK_EQ(runtime->GetImtConflictMethod(),
700 image_header->GetImageMethod(ImageHeader::kImtConflictMethod));
701 CHECK_EQ(runtime->GetImtUnimplementedMethod(),
702 image_header->GetImageMethod(ImageHeader::kImtUnimplementedMethod));
703 CHECK_EQ(runtime->GetCalleeSaveMethod(Runtime::kSaveAllCalleeSaves),
704 image_header->GetImageMethod(ImageHeader::kSaveAllCalleeSavesMethod));
705 CHECK_EQ(runtime->GetCalleeSaveMethod(Runtime::kSaveRefsOnly),
706 image_header->GetImageMethod(ImageHeader::kSaveRefsOnlyMethod));
707 CHECK_EQ(runtime->GetCalleeSaveMethod(Runtime::kSaveRefsAndArgs),
708 image_header->GetImageMethod(ImageHeader::kSaveRefsAndArgsMethod));
709 CHECK_EQ(runtime->GetCalleeSaveMethod(Runtime::kSaveEverything),
710 image_header->GetImageMethod(ImageHeader::kSaveEverythingMethod));
711 } else if (!runtime->HasResolutionMethod()) {
712 runtime->SetInstructionSet(space->oat_file_non_owned_->GetOatHeader().GetInstructionSet());
713 runtime->SetResolutionMethod(image_header->GetImageMethod(ImageHeader::kResolutionMethod));
714 runtime->SetImtConflictMethod(image_header->GetImageMethod(ImageHeader::kImtConflictMethod));
715 runtime->SetImtUnimplementedMethod(
716 image_header->GetImageMethod(ImageHeader::kImtUnimplementedMethod));
717 runtime->SetCalleeSaveMethod(
718 image_header->GetImageMethod(ImageHeader::kSaveAllCalleeSavesMethod),
719 Runtime::kSaveAllCalleeSaves);
720 runtime->SetCalleeSaveMethod(
721 image_header->GetImageMethod(ImageHeader::kSaveRefsOnlyMethod), Runtime::kSaveRefsOnly);
722 runtime->SetCalleeSaveMethod(
723 image_header->GetImageMethod(ImageHeader::kSaveRefsAndArgsMethod),
724 Runtime::kSaveRefsAndArgs);
725 runtime->SetCalleeSaveMethod(
726 image_header->GetImageMethod(ImageHeader::kSaveEverythingMethod), Runtime::kSaveEverything);
727 }
728
729 VLOG(image) << "ImageSpace::Init exiting " << *space.get();
730 if (VLOG_IS_ON(image)) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700731 logger.Dump(LOG_STREAM(INFO));
Andreas Gampea463b6a2016-08-12 21:53:32 -0700732 }
733 return space;
734 }
735
736 private:
737 static MemMap* LoadImageFile(const char* image_filename,
738 const char* image_location,
739 const ImageHeader& image_header,
740 uint8_t* address,
741 int fd,
742 TimingLogger& logger,
743 std::string* error_msg) {
744 TimingLogger::ScopedTiming timing("MapImageFile", &logger);
745 const ImageHeader::StorageMode storage_mode = image_header.GetStorageMode();
746 if (storage_mode == ImageHeader::kStorageModeUncompressed) {
747 return MemMap::MapFileAtAddress(address,
748 image_header.GetImageSize(),
749 PROT_READ | PROT_WRITE,
750 MAP_PRIVATE,
751 fd,
752 0,
753 /*low_4gb*/true,
754 /*reuse*/false,
755 image_filename,
756 error_msg);
757 }
758
759 if (storage_mode != ImageHeader::kStorageModeLZ4 &&
760 storage_mode != ImageHeader::kStorageModeLZ4HC) {
761 *error_msg = StringPrintf("Invalid storage mode in image header %d",
762 static_cast<int>(storage_mode));
763 return nullptr;
764 }
765
766 // Reserve output and decompress into it.
767 std::unique_ptr<MemMap> map(MemMap::MapAnonymous(image_location,
768 address,
769 image_header.GetImageSize(),
770 PROT_READ | PROT_WRITE,
771 /*low_4gb*/true,
772 /*reuse*/false,
773 error_msg));
774 if (map != nullptr) {
775 const size_t stored_size = image_header.GetDataSize();
776 const size_t decompress_offset = sizeof(ImageHeader); // Skip the header.
777 std::unique_ptr<MemMap> temp_map(MemMap::MapFile(sizeof(ImageHeader) + stored_size,
778 PROT_READ,
779 MAP_PRIVATE,
780 fd,
781 /*offset*/0,
782 /*low_4gb*/false,
783 image_filename,
784 error_msg));
785 if (temp_map == nullptr) {
786 DCHECK(!error_msg->empty());
787 return nullptr;
788 }
789 memcpy(map->Begin(), &image_header, sizeof(ImageHeader));
790 const uint64_t start = NanoTime();
791 // LZ4HC and LZ4 have same internal format, both use LZ4_decompress.
792 TimingLogger::ScopedTiming timing2("LZ4 decompress image", &logger);
793 const size_t decompressed_size = LZ4_decompress_safe(
794 reinterpret_cast<char*>(temp_map->Begin()) + sizeof(ImageHeader),
795 reinterpret_cast<char*>(map->Begin()) + decompress_offset,
796 stored_size,
797 map->Size() - decompress_offset);
798 VLOG(image) << "Decompressing image took " << PrettyDuration(NanoTime() - start);
799 if (decompressed_size + sizeof(ImageHeader) != image_header.GetImageSize()) {
800 *error_msg = StringPrintf(
801 "Decompressed size does not match expected image size %zu vs %zu",
802 decompressed_size + sizeof(ImageHeader),
803 image_header.GetImageSize());
804 return nullptr;
805 }
806 }
807
808 return map.release();
809 }
810
811 class FixupVisitor : public ValueObject {
812 public:
813 FixupVisitor(const RelocationRange& boot_image,
814 const RelocationRange& boot_oat,
815 const RelocationRange& app_image,
816 const RelocationRange& app_oat)
817 : boot_image_(boot_image),
818 boot_oat_(boot_oat),
819 app_image_(app_image),
820 app_oat_(app_oat) {}
821
822 // Return the relocated address of a heap object.
823 template <typename T>
824 ALWAYS_INLINE T* ForwardObject(T* src) const {
825 const uintptr_t uint_src = reinterpret_cast<uintptr_t>(src);
826 if (boot_image_.InSource(uint_src)) {
827 return reinterpret_cast<T*>(boot_image_.ToDest(uint_src));
828 }
829 if (app_image_.InSource(uint_src)) {
830 return reinterpret_cast<T*>(app_image_.ToDest(uint_src));
831 }
832 // Since we are fixing up the app image, there should only be pointers to the app image and
833 // boot image.
834 DCHECK(src == nullptr) << reinterpret_cast<const void*>(src);
835 return src;
836 }
837
838 // Return the relocated address of a code pointer (contained by an oat file).
839 ALWAYS_INLINE const void* ForwardCode(const void* src) const {
840 const uintptr_t uint_src = reinterpret_cast<uintptr_t>(src);
841 if (boot_oat_.InSource(uint_src)) {
842 return reinterpret_cast<const void*>(boot_oat_.ToDest(uint_src));
843 }
844 if (app_oat_.InSource(uint_src)) {
845 return reinterpret_cast<const void*>(app_oat_.ToDest(uint_src));
846 }
847 DCHECK(src == nullptr) << src;
848 return src;
849 }
850
851 // Must be called on pointers that already have been relocated to the destination relocation.
852 ALWAYS_INLINE bool IsInAppImage(mirror::Object* object) const {
853 return app_image_.InDest(reinterpret_cast<uintptr_t>(object));
854 }
855
856 protected:
857 // Source section.
858 const RelocationRange boot_image_;
859 const RelocationRange boot_oat_;
860 const RelocationRange app_image_;
861 const RelocationRange app_oat_;
862 };
863
864 // Adapt for mirror::Class::FixupNativePointers.
865 class FixupObjectAdapter : public FixupVisitor {
866 public:
867 template<typename... Args>
868 explicit FixupObjectAdapter(Args... args) : FixupVisitor(args...) {}
869
870 template <typename T>
871 T* operator()(T* obj) const {
872 return ForwardObject(obj);
873 }
874 };
875
876 class FixupRootVisitor : public FixupVisitor {
877 public:
878 template<typename... Args>
879 explicit FixupRootVisitor(Args... args) : FixupVisitor(args...) {}
880
881 ALWAYS_INLINE void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700882 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampea463b6a2016-08-12 21:53:32 -0700883 if (!root->IsNull()) {
884 VisitRoot(root);
885 }
886 }
887
888 ALWAYS_INLINE void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700889 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampea463b6a2016-08-12 21:53:32 -0700890 mirror::Object* ref = root->AsMirrorPtr();
891 mirror::Object* new_ref = ForwardObject(ref);
892 if (ref != new_ref) {
893 root->Assign(new_ref);
894 }
895 }
896 };
897
898 class FixupObjectVisitor : public FixupVisitor {
899 public:
900 template<typename... Args>
901 explicit FixupObjectVisitor(gc::accounting::ContinuousSpaceBitmap* visited,
902 const PointerSize pointer_size,
903 Args... args)
904 : FixupVisitor(args...),
905 pointer_size_(pointer_size),
906 visited_(visited) {}
907
908 // Fix up separately since we also need to fix up method entrypoints.
909 ALWAYS_INLINE void VisitRootIfNonNull(
910 mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const {}
911
912 ALWAYS_INLINE void VisitRoot(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED)
913 const {}
914
915 ALWAYS_INLINE void operator()(mirror::Object* obj,
916 MemberOffset offset,
917 bool is_static ATTRIBUTE_UNUSED) const
918 NO_THREAD_SAFETY_ANALYSIS {
919 // There could be overlap between ranges, we must avoid visiting the same reference twice.
920 // Avoid the class field since we already fixed it up in FixupClassVisitor.
921 if (offset.Uint32Value() != mirror::Object::ClassOffset().Uint32Value()) {
922 // Space is not yet added to the heap, don't do a read barrier.
923 mirror::Object* ref = obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(
924 offset);
925 // Use SetFieldObjectWithoutWriteBarrier to avoid card marking since we are writing to the
926 // image.
927 obj->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(offset, ForwardObject(ref));
928 }
929 }
930
931 // Visit a pointer array and forward corresponding native data. Ignores pointer arrays in the
932 // boot image. Uses the bitmap to ensure the same array is not visited multiple times.
933 template <typename Visitor>
934 void UpdatePointerArrayContents(mirror::PointerArray* array, const Visitor& visitor) const
935 NO_THREAD_SAFETY_ANALYSIS {
936 DCHECK(array != nullptr);
937 DCHECK(visitor.IsInAppImage(array));
938 // The bit for the array contents is different than the bit for the array. Since we may have
939 // already visited the array as a long / int array from walking the bitmap without knowing it
940 // was a pointer array.
941 static_assert(kObjectAlignment == 8u, "array bit may be in another object");
942 mirror::Object* const contents_bit = reinterpret_cast<mirror::Object*>(
943 reinterpret_cast<uintptr_t>(array) + kObjectAlignment);
944 // If the bit is not set then the contents have not yet been updated.
945 if (!visited_->Test(contents_bit)) {
946 array->Fixup<kVerifyNone, kWithoutReadBarrier>(array, pointer_size_, visitor);
947 visited_->Set(contents_bit);
948 }
949 }
950
951 // java.lang.ref.Reference visitor.
952 void operator()(mirror::Class* klass ATTRIBUTE_UNUSED, mirror::Reference* ref) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700953 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Andreas Gampea463b6a2016-08-12 21:53:32 -0700954 mirror::Object* obj = ref->GetReferent<kWithoutReadBarrier>();
955 ref->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
956 mirror::Reference::ReferentOffset(),
957 ForwardObject(obj));
958 }
959
960 void operator()(mirror::Object* obj) const NO_THREAD_SAFETY_ANALYSIS {
961 if (visited_->Test(obj)) {
962 // Already visited.
963 return;
964 }
965 visited_->Set(obj);
966
967 // Handle class specially first since we need it to be updated to properly visit the rest of
968 // the instance fields.
969 {
970 mirror::Class* klass = obj->GetClass<kVerifyNone, kWithoutReadBarrier>();
971 DCHECK(klass != nullptr) << "Null class in image";
972 // No AsClass since our fields aren't quite fixed up yet.
973 mirror::Class* new_klass = down_cast<mirror::Class*>(ForwardObject(klass));
974 if (klass != new_klass) {
975 obj->SetClass<kVerifyNone>(new_klass);
976 }
977 if (new_klass != klass && IsInAppImage(new_klass)) {
978 // Make sure the klass contents are fixed up since we depend on it to walk the fields.
979 operator()(new_klass);
980 }
981 }
982
983 obj->VisitReferences</*visit native roots*/false, kVerifyNone, kWithoutReadBarrier>(
984 *this,
985 *this);
986 // Note that this code relies on no circular dependencies.
987 // We want to use our own class loader and not the one in the image.
988 if (obj->IsClass<kVerifyNone, kWithoutReadBarrier>()) {
989 mirror::Class* as_klass = obj->AsClass<kVerifyNone, kWithoutReadBarrier>();
990 FixupObjectAdapter visitor(boot_image_, boot_oat_, app_image_, app_oat_);
991 as_klass->FixupNativePointers<kVerifyNone, kWithoutReadBarrier>(as_klass,
992 pointer_size_,
993 visitor);
994 // Deal with the pointer arrays. Use the helper function since multiple classes can reference
995 // the same arrays.
996 mirror::PointerArray* const vtable = as_klass->GetVTable<kVerifyNone, kWithoutReadBarrier>();
997 if (vtable != nullptr && IsInAppImage(vtable)) {
998 operator()(vtable);
999 UpdatePointerArrayContents(vtable, visitor);
1000 }
1001 mirror::IfTable* iftable = as_klass->GetIfTable<kVerifyNone, kWithoutReadBarrier>();
1002 // Ensure iftable arrays are fixed up since we need GetMethodArray to return the valid
1003 // contents.
1004 if (iftable != nullptr && IsInAppImage(iftable)) {
1005 operator()(iftable);
1006 for (int32_t i = 0, count = iftable->Count(); i < count; ++i) {
1007 if (iftable->GetMethodArrayCount<kVerifyNone, kWithoutReadBarrier>(i) > 0) {
1008 mirror::PointerArray* methods =
1009 iftable->GetMethodArray<kVerifyNone, kWithoutReadBarrier>(i);
1010 if (visitor.IsInAppImage(methods)) {
1011 operator()(methods);
1012 DCHECK(methods != nullptr);
1013 UpdatePointerArrayContents(methods, visitor);
1014 }
Mathieu Chartier92ec5942016-04-11 12:03:48 -07001015 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001016 }
1017 }
1018 }
1019 }
Mathieu Chartier91edc622016-02-16 17:16:01 -08001020
Andreas Gampea463b6a2016-08-12 21:53:32 -07001021 private:
1022 const PointerSize pointer_size_;
1023 gc::accounting::ContinuousSpaceBitmap* const visited_;
1024 };
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001025
Andreas Gampea463b6a2016-08-12 21:53:32 -07001026 class ForwardObjectAdapter {
1027 public:
1028 ALWAYS_INLINE explicit ForwardObjectAdapter(const FixupVisitor* visitor) : visitor_(visitor) {}
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001029
Andreas Gampea463b6a2016-08-12 21:53:32 -07001030 template <typename T>
1031 ALWAYS_INLINE T* operator()(T* src) const {
1032 return visitor_->ForwardObject(src);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001033 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001034
Andreas Gampea463b6a2016-08-12 21:53:32 -07001035 private:
1036 const FixupVisitor* const visitor_;
1037 };
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001038
Andreas Gampea463b6a2016-08-12 21:53:32 -07001039 class ForwardCodeAdapter {
1040 public:
1041 ALWAYS_INLINE explicit ForwardCodeAdapter(const FixupVisitor* visitor)
1042 : visitor_(visitor) {}
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001043
Andreas Gampea463b6a2016-08-12 21:53:32 -07001044 template <typename T>
1045 ALWAYS_INLINE T* operator()(T* src) const {
1046 return visitor_->ForwardCode(src);
1047 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001048
Andreas Gampea463b6a2016-08-12 21:53:32 -07001049 private:
1050 const FixupVisitor* const visitor_;
1051 };
1052
1053 class FixupArtMethodVisitor : public FixupVisitor, public ArtMethodVisitor {
1054 public:
1055 template<typename... Args>
1056 explicit FixupArtMethodVisitor(bool fixup_heap_objects, PointerSize pointer_size, Args... args)
1057 : FixupVisitor(args...),
1058 fixup_heap_objects_(fixup_heap_objects),
1059 pointer_size_(pointer_size) {}
1060
1061 virtual void Visit(ArtMethod* method) NO_THREAD_SAFETY_ANALYSIS {
1062 // TODO: Separate visitor for runtime vs normal methods.
1063 if (UNLIKELY(method->IsRuntimeMethod())) {
1064 ImtConflictTable* table = method->GetImtConflictTable(pointer_size_);
1065 if (table != nullptr) {
1066 ImtConflictTable* new_table = ForwardObject(table);
1067 if (table != new_table) {
1068 method->SetImtConflictTable(new_table, pointer_size_);
1069 }
1070 }
1071 const void* old_code = method->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size_);
1072 const void* new_code = ForwardCode(old_code);
1073 if (old_code != new_code) {
1074 method->SetEntryPointFromQuickCompiledCodePtrSize(new_code, pointer_size_);
1075 }
1076 } else {
1077 if (fixup_heap_objects_) {
1078 method->UpdateObjectsForImageRelocation(ForwardObjectAdapter(this), pointer_size_);
1079 }
1080 method->UpdateEntrypoints<kWithoutReadBarrier>(ForwardCodeAdapter(this), pointer_size_);
1081 }
1082 }
1083
1084 private:
1085 const bool fixup_heap_objects_;
1086 const PointerSize pointer_size_;
1087 };
1088
1089 class FixupArtFieldVisitor : public FixupVisitor, public ArtFieldVisitor {
1090 public:
1091 template<typename... Args>
1092 explicit FixupArtFieldVisitor(Args... args) : FixupVisitor(args...) {}
1093
1094 virtual void Visit(ArtField* field) NO_THREAD_SAFETY_ANALYSIS {
1095 field->UpdateObjects(ForwardObjectAdapter(this));
1096 }
1097 };
1098
1099 // Relocate an image space mapped at target_base which possibly used to be at a different base
1100 // address. Only needs a single image space, not one for both source and destination.
1101 // In place means modifying a single ImageSpace in place rather than relocating from one ImageSpace
1102 // to another.
1103 static bool RelocateInPlace(ImageHeader& image_header,
1104 uint8_t* target_base,
1105 accounting::ContinuousSpaceBitmap* bitmap,
1106 const OatFile* app_oat_file,
1107 std::string* error_msg) {
1108 DCHECK(error_msg != nullptr);
1109 if (!image_header.IsPic()) {
1110 if (image_header.GetImageBegin() == target_base) {
1111 return true;
1112 }
1113 *error_msg = StringPrintf("Cannot relocate non-pic image for oat file %s",
1114 (app_oat_file != nullptr) ? app_oat_file->GetLocation().c_str() : "");
1115 return false;
1116 }
1117 // Set up sections.
1118 uint32_t boot_image_begin = 0;
1119 uint32_t boot_image_end = 0;
1120 uint32_t boot_oat_begin = 0;
1121 uint32_t boot_oat_end = 0;
1122 const PointerSize pointer_size = image_header.GetPointerSize();
1123 gc::Heap* const heap = Runtime::Current()->GetHeap();
1124 heap->GetBootImagesSize(&boot_image_begin, &boot_image_end, &boot_oat_begin, &boot_oat_end);
1125 if (boot_image_begin == boot_image_end) {
1126 *error_msg = "Can not relocate app image without boot image space";
1127 return false;
1128 }
1129 if (boot_oat_begin == boot_oat_end) {
1130 *error_msg = "Can not relocate app image without boot oat file";
1131 return false;
1132 }
1133 const uint32_t boot_image_size = boot_image_end - boot_image_begin;
1134 const uint32_t boot_oat_size = boot_oat_end - boot_oat_begin;
1135 const uint32_t image_header_boot_image_size = image_header.GetBootImageSize();
1136 const uint32_t image_header_boot_oat_size = image_header.GetBootOatSize();
1137 if (boot_image_size != image_header_boot_image_size) {
1138 *error_msg = StringPrintf("Boot image size %" PRIu64 " does not match expected size %"
1139 PRIu64,
1140 static_cast<uint64_t>(boot_image_size),
1141 static_cast<uint64_t>(image_header_boot_image_size));
1142 return false;
1143 }
1144 if (boot_oat_size != image_header_boot_oat_size) {
1145 *error_msg = StringPrintf("Boot oat size %" PRIu64 " does not match expected size %"
1146 PRIu64,
1147 static_cast<uint64_t>(boot_oat_size),
1148 static_cast<uint64_t>(image_header_boot_oat_size));
1149 return false;
1150 }
1151 TimingLogger logger(__FUNCTION__, true, false);
1152 RelocationRange boot_image(image_header.GetBootImageBegin(),
1153 boot_image_begin,
1154 boot_image_size);
1155 RelocationRange boot_oat(image_header.GetBootOatBegin(),
1156 boot_oat_begin,
1157 boot_oat_size);
1158 RelocationRange app_image(reinterpret_cast<uintptr_t>(image_header.GetImageBegin()),
1159 reinterpret_cast<uintptr_t>(target_base),
1160 image_header.GetImageSize());
1161 // Use the oat data section since this is where the OatFile::Begin is.
1162 RelocationRange app_oat(reinterpret_cast<uintptr_t>(image_header.GetOatDataBegin()),
1163 // Not necessarily in low 4GB.
1164 reinterpret_cast<uintptr_t>(app_oat_file->Begin()),
1165 image_header.GetOatDataEnd() - image_header.GetOatDataBegin());
1166 VLOG(image) << "App image " << app_image;
1167 VLOG(image) << "App oat " << app_oat;
1168 VLOG(image) << "Boot image " << boot_image;
1169 VLOG(image) << "Boot oat " << boot_oat;
1170 // True if we need to fixup any heap pointers, otherwise only code pointers.
1171 const bool fixup_image = boot_image.Delta() != 0 || app_image.Delta() != 0;
1172 const bool fixup_code = boot_oat.Delta() != 0 || app_oat.Delta() != 0;
1173 if (!fixup_image && !fixup_code) {
1174 // Nothing to fix up.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001175 return true;
1176 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07001177 ScopedDebugDisallowReadBarriers sddrb(Thread::Current());
1178 // Need to update the image to be at the target base.
1179 const ImageSection& objects_section = image_header.GetImageSection(ImageHeader::kSectionObjects);
1180 uintptr_t objects_begin = reinterpret_cast<uintptr_t>(target_base + objects_section.Offset());
1181 uintptr_t objects_end = reinterpret_cast<uintptr_t>(target_base + objects_section.End());
1182 FixupObjectAdapter fixup_adapter(boot_image, boot_oat, app_image, app_oat);
1183 if (fixup_image) {
1184 // Two pass approach, fix up all classes first, then fix up non class-objects.
1185 // The visited bitmap is used to ensure that pointer arrays are not forwarded twice.
1186 std::unique_ptr<gc::accounting::ContinuousSpaceBitmap> visited_bitmap(
1187 gc::accounting::ContinuousSpaceBitmap::Create("Relocate bitmap",
1188 target_base,
1189 image_header.GetImageSize()));
1190 FixupObjectVisitor fixup_object_visitor(visited_bitmap.get(),
1191 pointer_size,
1192 boot_image,
1193 boot_oat,
1194 app_image,
1195 app_oat);
1196 TimingLogger::ScopedTiming timing("Fixup classes", &logger);
1197 // Fixup objects may read fields in the boot image, use the mutator lock here for sanity. Though
1198 // its probably not required.
1199 ScopedObjectAccess soa(Thread::Current());
1200 timing.NewTiming("Fixup objects");
1201 bitmap->VisitMarkedRange(objects_begin, objects_end, fixup_object_visitor);
1202 // Fixup image roots.
1203 CHECK(app_image.InSource(reinterpret_cast<uintptr_t>(
1204 image_header.GetImageRoots<kWithoutReadBarrier>())));
1205 image_header.RelocateImageObjects(app_image.Delta());
1206 CHECK_EQ(image_header.GetImageBegin(), target_base);
1207 // Fix up dex cache DexFile pointers.
1208 auto* dex_caches = image_header.GetImageRoot<kWithoutReadBarrier>(ImageHeader::kDexCaches)->
1209 AsObjectArray<mirror::DexCache, kVerifyNone, kWithoutReadBarrier>();
1210 for (int32_t i = 0, count = dex_caches->GetLength(); i < count; ++i) {
1211 mirror::DexCache* dex_cache = dex_caches->Get<kVerifyNone, kWithoutReadBarrier>(i);
1212 // Fix up dex cache pointers.
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07001213 mirror::StringDexCacheType* strings = dex_cache->GetStrings();
Andreas Gampea463b6a2016-08-12 21:53:32 -07001214 if (strings != nullptr) {
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07001215 mirror::StringDexCacheType* new_strings = fixup_adapter.ForwardObject(strings);
Andreas Gampea463b6a2016-08-12 21:53:32 -07001216 if (strings != new_strings) {
1217 dex_cache->SetStrings(new_strings);
1218 }
1219 dex_cache->FixupStrings<kWithoutReadBarrier>(new_strings, fixup_adapter);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001220 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07001221 GcRoot<mirror::Class>* types = dex_cache->GetResolvedTypes();
1222 if (types != nullptr) {
1223 GcRoot<mirror::Class>* new_types = fixup_adapter.ForwardObject(types);
1224 if (types != new_types) {
1225 dex_cache->SetResolvedTypes(new_types);
1226 }
1227 dex_cache->FixupResolvedTypes<kWithoutReadBarrier>(new_types, fixup_adapter);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001228 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07001229 ArtMethod** methods = dex_cache->GetResolvedMethods();
1230 if (methods != nullptr) {
1231 ArtMethod** new_methods = fixup_adapter.ForwardObject(methods);
1232 if (methods != new_methods) {
1233 dex_cache->SetResolvedMethods(new_methods);
1234 }
1235 for (size_t j = 0, num = dex_cache->NumResolvedMethods(); j != num; ++j) {
1236 ArtMethod* orig = mirror::DexCache::GetElementPtrSize(new_methods, j, pointer_size);
1237 ArtMethod* copy = fixup_adapter.ForwardObject(orig);
1238 if (orig != copy) {
1239 mirror::DexCache::SetElementPtrSize(new_methods, j, copy, pointer_size);
1240 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001241 }
1242 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07001243 ArtField** fields = dex_cache->GetResolvedFields();
1244 if (fields != nullptr) {
1245 ArtField** new_fields = fixup_adapter.ForwardObject(fields);
1246 if (fields != new_fields) {
1247 dex_cache->SetResolvedFields(new_fields);
1248 }
1249 for (size_t j = 0, num = dex_cache->NumResolvedFields(); j != num; ++j) {
1250 ArtField* orig = mirror::DexCache::GetElementPtrSize(new_fields, j, pointer_size);
1251 ArtField* copy = fixup_adapter.ForwardObject(orig);
1252 if (orig != copy) {
1253 mirror::DexCache::SetElementPtrSize(new_fields, j, copy, pointer_size);
1254 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001255 }
1256 }
1257 }
1258 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001259 {
1260 // Only touches objects in the app image, no need for mutator lock.
Andreas Gampea463b6a2016-08-12 21:53:32 -07001261 TimingLogger::ScopedTiming timing("Fixup methods", &logger);
1262 FixupArtMethodVisitor method_visitor(fixup_image,
1263 pointer_size,
1264 boot_image,
1265 boot_oat,
1266 app_image,
1267 app_oat);
1268 image_header.VisitPackedArtMethods(&method_visitor, target_base, pointer_size);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001269 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07001270 if (fixup_image) {
1271 {
1272 // Only touches objects in the app image, no need for mutator lock.
1273 TimingLogger::ScopedTiming timing("Fixup fields", &logger);
1274 FixupArtFieldVisitor field_visitor(boot_image, boot_oat, app_image, app_oat);
1275 image_header.VisitPackedArtFields(&field_visitor, target_base);
1276 }
1277 {
1278 TimingLogger::ScopedTiming timing("Fixup imt", &logger);
1279 image_header.VisitPackedImTables(fixup_adapter, target_base, pointer_size);
1280 }
1281 {
1282 TimingLogger::ScopedTiming timing("Fixup conflict tables", &logger);
1283 image_header.VisitPackedImtConflictTables(fixup_adapter, target_base, pointer_size);
1284 }
1285 // In the app image case, the image methods are actually in the boot image.
1286 image_header.RelocateImageMethods(boot_image.Delta());
1287 const auto& class_table_section = image_header.GetImageSection(ImageHeader::kSectionClassTable);
1288 if (class_table_section.Size() > 0u) {
1289 // Note that we require that ReadFromMemory does not make an internal copy of the elements.
1290 // This also relies on visit roots not doing any verification which could fail after we update
1291 // the roots to be the image addresses.
1292 ScopedObjectAccess soa(Thread::Current());
1293 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
1294 ClassTable temp_table;
1295 temp_table.ReadFromMemory(target_base + class_table_section.Offset());
1296 FixupRootVisitor root_visitor(boot_image, boot_oat, app_image, app_oat);
1297 temp_table.VisitRoots(root_visitor);
1298 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001299 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07001300 if (VLOG_IS_ON(image)) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07001301 logger.Dump(LOG_STREAM(INFO));
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001302 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07001303 return true;
Andreas Gampe7fa55782016-06-15 17:45:01 -07001304 }
1305
Andreas Gampea463b6a2016-08-12 21:53:32 -07001306 static std::unique_ptr<OatFile> OpenOatFile(const ImageSpace& image,
1307 const char* image_path,
1308 std::string* error_msg) {
1309 const ImageHeader& image_header = image.GetImageHeader();
1310 std::string oat_filename = ImageHeader::GetOatLocationFromImageLocation(image_path);
Andreas Gampe7fa55782016-06-15 17:45:01 -07001311
Andreas Gampea463b6a2016-08-12 21:53:32 -07001312 CHECK(image_header.GetOatDataBegin() != nullptr);
1313
1314 std::unique_ptr<OatFile> oat_file(OatFile::Open(oat_filename,
1315 oat_filename,
1316 image_header.GetOatDataBegin(),
1317 image_header.GetOatFileBegin(),
1318 !Runtime::Current()->IsAotCompiler(),
1319 /*low_4gb*/false,
1320 nullptr,
1321 error_msg));
1322 if (oat_file == nullptr) {
1323 *error_msg = StringPrintf("Failed to open oat file '%s' referenced from image %s: %s",
1324 oat_filename.c_str(),
1325 image.GetName(),
1326 error_msg->c_str());
Andreas Gampe7fa55782016-06-15 17:45:01 -07001327 return nullptr;
1328 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07001329 uint32_t oat_checksum = oat_file->GetOatHeader().GetChecksum();
1330 uint32_t image_oat_checksum = image_header.GetOatChecksum();
Mathieu Chartier9ff84602016-01-29 12:22:17 -08001331 if (oat_checksum != image_oat_checksum) {
Andreas Gampea463b6a2016-08-12 21:53:32 -07001332 *error_msg = StringPrintf("Failed to match oat file checksum 0x%x to expected oat checksum 0x%x"
1333 " in image %s",
Mathieu Chartier9ff84602016-01-29 12:22:17 -08001334 oat_checksum,
1335 image_oat_checksum,
Andreas Gampea463b6a2016-08-12 21:53:32 -07001336 image.GetName());
Mathieu Chartier9ff84602016-01-29 12:22:17 -08001337 return nullptr;
1338 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07001339 int32_t image_patch_delta = image_header.GetPatchDelta();
1340 int32_t oat_patch_delta = oat_file->GetOatHeader().GetImagePatchDelta();
1341 if (oat_patch_delta != image_patch_delta && !image_header.CompilePic()) {
1342 // We should have already relocated by this point. Bail out.
1343 *error_msg = StringPrintf("Failed to match oat file patch delta %d to expected patch delta %d "
1344 "in image %s",
1345 oat_patch_delta,
1346 image_patch_delta,
1347 image.GetName());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001348 return nullptr;
1349 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07001350
1351 return oat_file;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001352 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07001353
1354 static bool ValidateOatFile(const ImageSpace& space,
1355 const OatFile& oat_file,
1356 std::string* error_msg) {
1357 for (const OatFile::OatDexFile* oat_dex_file : oat_file.GetOatDexFiles()) {
1358 const std::string& dex_file_location = oat_dex_file->GetDexFileLocation();
1359 uint32_t dex_file_location_checksum;
1360 if (!DexFile::GetChecksum(dex_file_location.c_str(), &dex_file_location_checksum, error_msg)) {
1361 *error_msg = StringPrintf("Failed to get checksum of dex file '%s' referenced by image %s: "
1362 "%s",
1363 dex_file_location.c_str(),
1364 space.GetName(),
1365 error_msg->c_str());
1366 return false;
1367 }
1368 if (dex_file_location_checksum != oat_dex_file->GetDexFileLocationChecksum()) {
1369 *error_msg = StringPrintf("ValidateOatFile found checksum mismatch between oat file '%s' and "
1370 "dex file '%s' (0x%x != 0x%x)",
1371 oat_file.GetLocation().c_str(),
1372 dex_file_location.c_str(),
1373 oat_dex_file->GetDexFileLocationChecksum(),
1374 dex_file_location_checksum);
1375 return false;
1376 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001377 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07001378 return true;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001379 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07001380};
Hiroshi Yamauchibd0fb612014-05-20 13:46:00 -07001381
Andreas Gampea463b6a2016-08-12 21:53:32 -07001382static constexpr uint64_t kLowSpaceValue = 50 * MB;
1383static constexpr uint64_t kTmpFsSentinelValue = 384 * MB;
1384
1385// Read the free space of the cache partition and make a decision whether to keep the generated
1386// image. This is to try to mitigate situations where the system might run out of space later.
1387static bool CheckSpace(const std::string& cache_filename, std::string* error_msg) {
1388 // Using statvfs vs statvfs64 because of b/18207376, and it is enough for all practical purposes.
1389 struct statvfs buf;
1390
1391 int res = TEMP_FAILURE_RETRY(statvfs(cache_filename.c_str(), &buf));
1392 if (res != 0) {
1393 // Could not stat. Conservatively tell the system to delete the image.
1394 *error_msg = "Could not stat the filesystem, assuming low-memory situation.";
1395 return false;
Nicolas Geoffray1bc977c2016-01-23 14:15:49 +00001396 }
Nicolas Geoffray1bc977c2016-01-23 14:15:49 +00001397
Andreas Gampea463b6a2016-08-12 21:53:32 -07001398 uint64_t fs_overall_size = buf.f_bsize * static_cast<uint64_t>(buf.f_blocks);
1399 // Zygote is privileged, but other things are not. Use bavail.
1400 uint64_t fs_free_size = buf.f_bsize * static_cast<uint64_t>(buf.f_bavail);
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001401
Andreas Gampea463b6a2016-08-12 21:53:32 -07001402 // Take the overall size as an indicator for a tmpfs, which is being used for the decryption
1403 // environment. We do not want to fail quickening the boot image there, as it is beneficial
1404 // for time-to-UI.
1405 if (fs_overall_size > kTmpFsSentinelValue) {
1406 if (fs_free_size < kLowSpaceValue) {
1407 *error_msg = StringPrintf("Low-memory situation: only %4.2f megabytes available, need at "
1408 "least %" PRIu64 ".",
1409 static_cast<double>(fs_free_size) / MB,
1410 kLowSpaceValue / MB);
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001411 return false;
1412 }
1413 }
1414 return true;
1415}
1416
Andreas Gampea463b6a2016-08-12 21:53:32 -07001417std::unique_ptr<ImageSpace> ImageSpace::CreateBootImage(const char* image_location,
1418 const InstructionSet image_isa,
1419 bool secondary_image,
1420 std::string* error_msg) {
1421 ScopedTrace trace(__FUNCTION__);
1422
1423 // Step 0: Extra zygote work.
1424
1425 // Step 0.a: If we're the zygote, mark boot.
1426 const bool is_zygote = Runtime::Current()->IsZygote();
Robert Sesekbfa1f8d2016-08-15 15:21:09 -04001427 if (is_zygote && !secondary_image && CanWriteToDalvikCache(image_isa)) {
Andreas Gampea463b6a2016-08-12 21:53:32 -07001428 MarkZygoteStart(image_isa, Runtime::Current()->GetZygoteMaxFailedBoots());
1429 }
1430
1431 // Step 0.b: If we're the zygote, check for free space, and prune the cache preemptively,
1432 // if necessary. While the runtime may be fine (it is pretty tolerant to
1433 // out-of-disk-space situations), other parts of the platform are not.
1434 //
1435 // The advantage of doing this proactively is that the later steps are simplified,
1436 // i.e., we do not need to code retries.
1437 std::string system_filename;
1438 bool has_system = false;
1439 std::string cache_filename;
1440 bool has_cache = false;
1441 bool dalvik_cache_exists = false;
1442 bool is_global_cache = true;
1443 std::string dalvik_cache;
1444 bool found_image = FindImageFilenameImpl(image_location,
1445 image_isa,
1446 &has_system,
1447 &system_filename,
1448 &dalvik_cache_exists,
1449 &dalvik_cache,
1450 &is_global_cache,
1451 &has_cache,
1452 &cache_filename);
1453
1454 if (is_zygote && dalvik_cache_exists) {
1455 DCHECK(!dalvik_cache.empty());
1456 std::string local_error_msg;
1457 if (!CheckSpace(dalvik_cache, &local_error_msg)) {
1458 LOG(WARNING) << local_error_msg << " Preemptively pruning the dalvik cache.";
1459 PruneDalvikCache(image_isa);
1460
1461 // Re-evaluate the image.
1462 found_image = FindImageFilenameImpl(image_location,
1463 image_isa,
1464 &has_system,
1465 &system_filename,
1466 &dalvik_cache_exists,
1467 &dalvik_cache,
1468 &is_global_cache,
1469 &has_cache,
1470 &cache_filename);
1471 }
1472 }
1473
1474 // Collect all the errors.
1475 std::vector<std::string> error_msgs;
1476
1477 // Step 1: Check if we have an existing and relocated image.
1478
1479 // Step 1.a: Have files in system and cache. Then they need to match.
1480 if (found_image && has_system && has_cache) {
1481 std::string local_error_msg;
1482 // Check that the files are matching.
1483 if (ChecksumsMatch(system_filename.c_str(), cache_filename.c_str(), &local_error_msg)) {
1484 std::unique_ptr<ImageSpace> relocated_space =
1485 ImageSpaceLoader::Load(image_location,
1486 cache_filename,
1487 is_zygote,
1488 is_global_cache,
Andreas Gampe44c8ed62016-08-19 16:43:00 -07001489 /* validate_oat_file */ false,
Andreas Gampea463b6a2016-08-12 21:53:32 -07001490 &local_error_msg);
1491 if (relocated_space != nullptr) {
1492 return relocated_space;
1493 }
1494 }
1495 error_msgs.push_back(local_error_msg);
1496 }
1497
1498 // Step 1.b: Only have a cache file.
1499 if (found_image && !has_system && has_cache) {
1500 std::string local_error_msg;
1501 std::unique_ptr<ImageSpace> cache_space =
1502 ImageSpaceLoader::Load(image_location,
1503 cache_filename,
1504 is_zygote,
1505 is_global_cache,
Andreas Gampe44c8ed62016-08-19 16:43:00 -07001506 /* validate_oat_file */ true,
Andreas Gampea463b6a2016-08-12 21:53:32 -07001507 &local_error_msg);
1508 if (cache_space != nullptr) {
1509 return cache_space;
1510 }
1511 error_msgs.push_back(local_error_msg);
1512 }
1513
1514 // Step 2: We have an existing image in /system.
1515
1516 // Step 2.a: We are not required to relocate it. Then we can use it directly.
1517 bool relocate = Runtime::Current()->ShouldRelocate();
1518
1519 if (found_image && has_system && !relocate) {
1520 std::string local_error_msg;
1521 std::unique_ptr<ImageSpace> system_space =
1522 ImageSpaceLoader::Load(image_location,
1523 system_filename,
1524 is_zygote,
1525 is_global_cache,
Andreas Gampe44c8ed62016-08-19 16:43:00 -07001526 /* validate_oat_file */ false,
Andreas Gampea463b6a2016-08-12 21:53:32 -07001527 &local_error_msg);
1528 if (system_space != nullptr) {
1529 return system_space;
1530 }
1531 error_msgs.push_back(local_error_msg);
1532 }
1533
1534 // Step 2.b: We require a relocated image. Then we must patch it. This step fails if this is a
1535 // secondary image.
1536 if (found_image && has_system && relocate) {
1537 std::string local_error_msg;
1538 if (!Runtime::Current()->IsImageDex2OatEnabled()) {
1539 local_error_msg = "Patching disabled.";
1540 } else if (secondary_image) {
1541 local_error_msg = "Cannot patch a secondary image.";
Robert Sesekbfa1f8d2016-08-15 15:21:09 -04001542 } else if (ImageCreationAllowed(is_global_cache, image_isa, &local_error_msg)) {
Andreas Gampea463b6a2016-08-12 21:53:32 -07001543 bool patch_success =
1544 RelocateImage(image_location, cache_filename.c_str(), image_isa, &local_error_msg);
1545 if (patch_success) {
1546 std::unique_ptr<ImageSpace> patched_space =
1547 ImageSpaceLoader::Load(image_location,
1548 cache_filename,
1549 is_zygote,
1550 is_global_cache,
Andreas Gampe44c8ed62016-08-19 16:43:00 -07001551 /* validate_oat_file */ false,
Andreas Gampea463b6a2016-08-12 21:53:32 -07001552 &local_error_msg);
1553 if (patched_space != nullptr) {
1554 return patched_space;
1555 }
1556 }
1557 }
1558 error_msgs.push_back(StringPrintf("Cannot relocate image %s to %s: %s",
1559 image_location,
1560 cache_filename.c_str(),
1561 local_error_msg.c_str()));
1562 }
1563
1564 // Step 3: We do not have an existing image in /system, so generate an image into the dalvik
1565 // cache. This step fails if this is a secondary image.
1566 if (!has_system) {
1567 std::string local_error_msg;
1568 if (!Runtime::Current()->IsImageDex2OatEnabled()) {
1569 local_error_msg = "Image compilation disabled.";
1570 } else if (secondary_image) {
1571 local_error_msg = "Cannot compile a secondary image.";
Robert Sesekbfa1f8d2016-08-15 15:21:09 -04001572 } else if (ImageCreationAllowed(is_global_cache, image_isa, &local_error_msg)) {
Andreas Gampea463b6a2016-08-12 21:53:32 -07001573 bool compilation_success = GenerateImage(cache_filename, image_isa, &local_error_msg);
1574 if (compilation_success) {
1575 std::unique_ptr<ImageSpace> compiled_space =
1576 ImageSpaceLoader::Load(image_location,
1577 cache_filename,
1578 is_zygote,
1579 is_global_cache,
Andreas Gampe44c8ed62016-08-19 16:43:00 -07001580 /* validate_oat_file */ false,
Andreas Gampea463b6a2016-08-12 21:53:32 -07001581 &local_error_msg);
1582 if (compiled_space != nullptr) {
1583 return compiled_space;
1584 }
1585 }
1586 }
1587 error_msgs.push_back(StringPrintf("Cannot compile image to %s: %s",
1588 cache_filename.c_str(),
1589 local_error_msg.c_str()));
1590 }
1591
1592 // We failed. Prune the cache the free up space, create a compound error message and return no
1593 // image.
1594 PruneDalvikCache(image_isa);
1595
1596 std::ostringstream oss;
1597 bool first = true;
1598 for (auto msg : error_msgs) {
1599 if (!first) {
1600 oss << "\n ";
1601 }
1602 oss << msg;
1603 }
1604 *error_msg = oss.str();
1605
1606 return nullptr;
1607}
1608
1609std::unique_ptr<ImageSpace> ImageSpace::CreateFromAppImage(const char* image,
1610 const OatFile* oat_file,
1611 std::string* error_msg) {
1612 return ImageSpaceLoader::Init(image,
1613 image,
1614 /*validate_oat_file*/false,
1615 oat_file,
1616 /*out*/error_msg);
1617}
1618
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001619const OatFile* ImageSpace::GetOatFile() const {
Andreas Gampe88da3b02015-06-12 20:38:49 -07001620 return oat_file_non_owned_;
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001621}
1622
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -07001623std::unique_ptr<const OatFile> ImageSpace::ReleaseOatFile() {
1624 CHECK(oat_file_ != nullptr);
1625 return std::move(oat_file_);
Ian Rogers1d54e732013-05-02 21:10:01 -07001626}
1627
Ian Rogers1d54e732013-05-02 21:10:01 -07001628void ImageSpace::Dump(std::ostream& os) const {
1629 os << GetType()
Mathieu Chartier590fee92013-09-13 13:46:47 -07001630 << " begin=" << reinterpret_cast<void*>(Begin())
Ian Rogers1d54e732013-05-02 21:10:01 -07001631 << ",end=" << reinterpret_cast<void*>(End())
1632 << ",size=" << PrettySize(Size())
1633 << ",name=\"" << GetName() << "\"]";
1634}
1635
Mathieu Chartier866d8742016-09-21 15:24:18 -07001636std::string ImageSpace::GetMultiImageBootClassPath(
1637 const std::vector<const char*>& dex_locations,
1638 const std::vector<const char*>& oat_filenames,
1639 const std::vector<const char*>& image_filenames) {
1640 DCHECK_GT(oat_filenames.size(), 1u);
1641 // If the image filename was adapted (e.g., for our tests), we need to change this here,
1642 // too, but need to strip all path components (they will be re-established when loading).
1643 std::ostringstream bootcp_oss;
1644 bool first_bootcp = true;
1645 for (size_t i = 0; i < dex_locations.size(); ++i) {
1646 if (!first_bootcp) {
1647 bootcp_oss << ":";
1648 }
1649
1650 std::string dex_loc = dex_locations[i];
1651 std::string image_filename = image_filenames[i];
1652
1653 // Use the dex_loc path, but the image_filename name (without path elements).
1654 size_t dex_last_slash = dex_loc.rfind('/');
1655
1656 // npos is max(size_t). That makes this a bit ugly.
1657 size_t image_last_slash = image_filename.rfind('/');
1658 size_t image_last_at = image_filename.rfind('@');
1659 size_t image_last_sep = (image_last_slash == std::string::npos)
1660 ? image_last_at
1661 : (image_last_at == std::string::npos)
1662 ? std::string::npos
1663 : std::max(image_last_slash, image_last_at);
1664 // Note: whenever image_last_sep == npos, +1 overflow means using the full string.
1665
1666 if (dex_last_slash == std::string::npos) {
1667 dex_loc = image_filename.substr(image_last_sep + 1);
1668 } else {
1669 dex_loc = dex_loc.substr(0, dex_last_slash + 1) +
1670 image_filename.substr(image_last_sep + 1);
1671 }
1672
1673 // Image filenames already end with .art, no need to replace.
1674
1675 bootcp_oss << dex_loc;
1676 first_bootcp = false;
1677 }
1678 return bootcp_oss.str();
1679}
1680
1681void ImageSpace::ExtractMultiImageLocations(const std::string& input_image_file_name,
1682 const std::string& boot_classpath,
1683 std::vector<std::string>* image_file_names) {
Andreas Gampe8994a042015-12-30 19:03:17 +00001684 DCHECK(image_file_names != nullptr);
1685
1686 std::vector<std::string> images;
1687 Split(boot_classpath, ':', &images);
1688
1689 // Add the rest into the list. We have to adjust locations, possibly:
1690 //
1691 // For example, image_file_name is /a/b/c/d/e.art
1692 // images[0] is f/c/d/e.art
1693 // ----------------------------------------------
1694 // images[1] is g/h/i/j.art -> /a/b/h/i/j.art
Mathieu Chartier8b8f6d62016-03-08 16:50:20 -08001695 const std::string& first_image = images[0];
1696 // Length of common suffix.
1697 size_t common = 0;
1698 while (common < input_image_file_name.size() &&
1699 common < first_image.size() &&
1700 *(input_image_file_name.end() - common - 1) == *(first_image.end() - common - 1)) {
1701 ++common;
Andreas Gampe8994a042015-12-30 19:03:17 +00001702 }
Mathieu Chartier8b8f6d62016-03-08 16:50:20 -08001703 // We want to replace the prefix of the input image with the prefix of the boot class path.
1704 // This handles the case where the image file contains @ separators.
1705 // Example image_file_name is oats/system@framework@boot.art
1706 // images[0] is .../arm/boot.art
1707 // means that the image name prefix will be oats/system@framework@
1708 // so that the other images are openable.
1709 const size_t old_prefix_length = first_image.size() - common;
1710 const std::string new_prefix = input_image_file_name.substr(
1711 0,
1712 input_image_file_name.size() - common);
Andreas Gampe8994a042015-12-30 19:03:17 +00001713
1714 // Apply pattern to images[1] .. images[n].
1715 for (size_t i = 1; i < images.size(); ++i) {
Mathieu Chartier8b8f6d62016-03-08 16:50:20 -08001716 const std::string& image = images[i];
1717 CHECK_GT(image.length(), old_prefix_length);
1718 std::string suffix = image.substr(old_prefix_length);
1719 image_file_names->push_back(new_prefix + suffix);
Andreas Gampe8994a042015-12-30 19:03:17 +00001720 }
1721}
1722
Mathieu Chartierd5f3f322016-03-21 14:05:56 -07001723void ImageSpace::DumpSections(std::ostream& os) const {
1724 const uint8_t* base = Begin();
1725 const ImageHeader& header = GetImageHeader();
1726 for (size_t i = 0; i < ImageHeader::kSectionCount; ++i) {
1727 auto section_type = static_cast<ImageHeader::ImageSections>(i);
1728 const ImageSection& section = header.GetImageSection(section_type);
1729 os << section_type << " " << reinterpret_cast<const void*>(base + section.Offset())
1730 << "-" << reinterpret_cast<const void*>(base + section.End()) << "\n";
1731 }
1732}
1733
Ian Rogers1d54e732013-05-02 21:10:01 -07001734} // namespace space
1735} // namespace gc
1736} // namespace art