blob: 6019540c9e9f83832eef1e8fa15f7f177ebed95b [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";
David Sehr709b0702016-10-13 09:12:37 -0700401 CHECK(live_bitmap_->Test(obj)) << obj->PrettyTypeOf();
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700402 if (kUseBakerReadBarrier) {
403 obj->AssertReadBarrierState();
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
Mathieu Chartier31e88222016-10-14 18:43:19 -0700915 ALWAYS_INLINE void operator()(ObjPtr<mirror::Object> obj,
Andreas Gampea463b6a2016-08-12 21:53:32 -0700916 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.
Mathieu Chartier31e88222016-10-14 18:43:19 -0700952 void operator()(ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
953 ObjPtr<mirror::Reference> ref) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700954 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Andreas Gampea463b6a2016-08-12 21:53:32 -0700955 mirror::Object* obj = ref->GetReferent<kWithoutReadBarrier>();
956 ref->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
957 mirror::Reference::ReferentOffset(),
958 ForwardObject(obj));
959 }
960
961 void operator()(mirror::Object* obj) const NO_THREAD_SAFETY_ANALYSIS {
962 if (visited_->Test(obj)) {
963 // Already visited.
964 return;
965 }
966 visited_->Set(obj);
967
968 // Handle class specially first since we need it to be updated to properly visit the rest of
969 // the instance fields.
970 {
971 mirror::Class* klass = obj->GetClass<kVerifyNone, kWithoutReadBarrier>();
972 DCHECK(klass != nullptr) << "Null class in image";
973 // No AsClass since our fields aren't quite fixed up yet.
974 mirror::Class* new_klass = down_cast<mirror::Class*>(ForwardObject(klass));
975 if (klass != new_klass) {
976 obj->SetClass<kVerifyNone>(new_klass);
977 }
978 if (new_klass != klass && IsInAppImage(new_klass)) {
979 // Make sure the klass contents are fixed up since we depend on it to walk the fields.
980 operator()(new_klass);
981 }
982 }
983
984 obj->VisitReferences</*visit native roots*/false, kVerifyNone, kWithoutReadBarrier>(
985 *this,
986 *this);
987 // Note that this code relies on no circular dependencies.
988 // We want to use our own class loader and not the one in the image.
989 if (obj->IsClass<kVerifyNone, kWithoutReadBarrier>()) {
990 mirror::Class* as_klass = obj->AsClass<kVerifyNone, kWithoutReadBarrier>();
991 FixupObjectAdapter visitor(boot_image_, boot_oat_, app_image_, app_oat_);
992 as_klass->FixupNativePointers<kVerifyNone, kWithoutReadBarrier>(as_klass,
993 pointer_size_,
994 visitor);
995 // Deal with the pointer arrays. Use the helper function since multiple classes can reference
996 // the same arrays.
997 mirror::PointerArray* const vtable = as_klass->GetVTable<kVerifyNone, kWithoutReadBarrier>();
998 if (vtable != nullptr && IsInAppImage(vtable)) {
999 operator()(vtable);
1000 UpdatePointerArrayContents(vtable, visitor);
1001 }
1002 mirror::IfTable* iftable = as_klass->GetIfTable<kVerifyNone, kWithoutReadBarrier>();
1003 // Ensure iftable arrays are fixed up since we need GetMethodArray to return the valid
1004 // contents.
Mathieu Chartier6beced42016-11-15 15:51:31 -08001005 if (IsInAppImage(iftable)) {
Andreas Gampea463b6a2016-08-12 21:53:32 -07001006 operator()(iftable);
1007 for (int32_t i = 0, count = iftable->Count(); i < count; ++i) {
1008 if (iftable->GetMethodArrayCount<kVerifyNone, kWithoutReadBarrier>(i) > 0) {
1009 mirror::PointerArray* methods =
1010 iftable->GetMethodArray<kVerifyNone, kWithoutReadBarrier>(i);
1011 if (visitor.IsInAppImage(methods)) {
1012 operator()(methods);
1013 DCHECK(methods != nullptr);
1014 UpdatePointerArrayContents(methods, visitor);
1015 }
Mathieu Chartier92ec5942016-04-11 12:03:48 -07001016 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001017 }
1018 }
1019 }
1020 }
Mathieu Chartier91edc622016-02-16 17:16:01 -08001021
Andreas Gampea463b6a2016-08-12 21:53:32 -07001022 private:
1023 const PointerSize pointer_size_;
1024 gc::accounting::ContinuousSpaceBitmap* const visited_;
1025 };
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001026
Andreas Gampea463b6a2016-08-12 21:53:32 -07001027 class ForwardObjectAdapter {
1028 public:
1029 ALWAYS_INLINE explicit ForwardObjectAdapter(const FixupVisitor* visitor) : visitor_(visitor) {}
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001030
Andreas Gampea463b6a2016-08-12 21:53:32 -07001031 template <typename T>
1032 ALWAYS_INLINE T* operator()(T* src) const {
1033 return visitor_->ForwardObject(src);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001034 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001035
Andreas Gampea463b6a2016-08-12 21:53:32 -07001036 private:
1037 const FixupVisitor* const visitor_;
1038 };
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001039
Andreas Gampea463b6a2016-08-12 21:53:32 -07001040 class ForwardCodeAdapter {
1041 public:
1042 ALWAYS_INLINE explicit ForwardCodeAdapter(const FixupVisitor* visitor)
1043 : visitor_(visitor) {}
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001044
Andreas Gampea463b6a2016-08-12 21:53:32 -07001045 template <typename T>
1046 ALWAYS_INLINE T* operator()(T* src) const {
1047 return visitor_->ForwardCode(src);
1048 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001049
Andreas Gampea463b6a2016-08-12 21:53:32 -07001050 private:
1051 const FixupVisitor* const visitor_;
1052 };
1053
1054 class FixupArtMethodVisitor : public FixupVisitor, public ArtMethodVisitor {
1055 public:
1056 template<typename... Args>
1057 explicit FixupArtMethodVisitor(bool fixup_heap_objects, PointerSize pointer_size, Args... args)
1058 : FixupVisitor(args...),
1059 fixup_heap_objects_(fixup_heap_objects),
1060 pointer_size_(pointer_size) {}
1061
1062 virtual void Visit(ArtMethod* method) NO_THREAD_SAFETY_ANALYSIS {
1063 // TODO: Separate visitor for runtime vs normal methods.
1064 if (UNLIKELY(method->IsRuntimeMethod())) {
1065 ImtConflictTable* table = method->GetImtConflictTable(pointer_size_);
1066 if (table != nullptr) {
1067 ImtConflictTable* new_table = ForwardObject(table);
1068 if (table != new_table) {
1069 method->SetImtConflictTable(new_table, pointer_size_);
1070 }
1071 }
1072 const void* old_code = method->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size_);
1073 const void* new_code = ForwardCode(old_code);
1074 if (old_code != new_code) {
1075 method->SetEntryPointFromQuickCompiledCodePtrSize(new_code, pointer_size_);
1076 }
1077 } else {
1078 if (fixup_heap_objects_) {
1079 method->UpdateObjectsForImageRelocation(ForwardObjectAdapter(this), pointer_size_);
1080 }
1081 method->UpdateEntrypoints<kWithoutReadBarrier>(ForwardCodeAdapter(this), pointer_size_);
1082 }
1083 }
1084
1085 private:
1086 const bool fixup_heap_objects_;
1087 const PointerSize pointer_size_;
1088 };
1089
1090 class FixupArtFieldVisitor : public FixupVisitor, public ArtFieldVisitor {
1091 public:
1092 template<typename... Args>
1093 explicit FixupArtFieldVisitor(Args... args) : FixupVisitor(args...) {}
1094
1095 virtual void Visit(ArtField* field) NO_THREAD_SAFETY_ANALYSIS {
1096 field->UpdateObjects(ForwardObjectAdapter(this));
1097 }
1098 };
1099
1100 // Relocate an image space mapped at target_base which possibly used to be at a different base
1101 // address. Only needs a single image space, not one for both source and destination.
1102 // In place means modifying a single ImageSpace in place rather than relocating from one ImageSpace
1103 // to another.
1104 static bool RelocateInPlace(ImageHeader& image_header,
1105 uint8_t* target_base,
1106 accounting::ContinuousSpaceBitmap* bitmap,
1107 const OatFile* app_oat_file,
1108 std::string* error_msg) {
1109 DCHECK(error_msg != nullptr);
1110 if (!image_header.IsPic()) {
1111 if (image_header.GetImageBegin() == target_base) {
1112 return true;
1113 }
1114 *error_msg = StringPrintf("Cannot relocate non-pic image for oat file %s",
1115 (app_oat_file != nullptr) ? app_oat_file->GetLocation().c_str() : "");
1116 return false;
1117 }
1118 // Set up sections.
1119 uint32_t boot_image_begin = 0;
1120 uint32_t boot_image_end = 0;
1121 uint32_t boot_oat_begin = 0;
1122 uint32_t boot_oat_end = 0;
1123 const PointerSize pointer_size = image_header.GetPointerSize();
1124 gc::Heap* const heap = Runtime::Current()->GetHeap();
1125 heap->GetBootImagesSize(&boot_image_begin, &boot_image_end, &boot_oat_begin, &boot_oat_end);
1126 if (boot_image_begin == boot_image_end) {
1127 *error_msg = "Can not relocate app image without boot image space";
1128 return false;
1129 }
1130 if (boot_oat_begin == boot_oat_end) {
1131 *error_msg = "Can not relocate app image without boot oat file";
1132 return false;
1133 }
1134 const uint32_t boot_image_size = boot_image_end - boot_image_begin;
1135 const uint32_t boot_oat_size = boot_oat_end - boot_oat_begin;
1136 const uint32_t image_header_boot_image_size = image_header.GetBootImageSize();
1137 const uint32_t image_header_boot_oat_size = image_header.GetBootOatSize();
1138 if (boot_image_size != image_header_boot_image_size) {
1139 *error_msg = StringPrintf("Boot image size %" PRIu64 " does not match expected size %"
1140 PRIu64,
1141 static_cast<uint64_t>(boot_image_size),
1142 static_cast<uint64_t>(image_header_boot_image_size));
1143 return false;
1144 }
1145 if (boot_oat_size != image_header_boot_oat_size) {
1146 *error_msg = StringPrintf("Boot oat size %" PRIu64 " does not match expected size %"
1147 PRIu64,
1148 static_cast<uint64_t>(boot_oat_size),
1149 static_cast<uint64_t>(image_header_boot_oat_size));
1150 return false;
1151 }
1152 TimingLogger logger(__FUNCTION__, true, false);
1153 RelocationRange boot_image(image_header.GetBootImageBegin(),
1154 boot_image_begin,
1155 boot_image_size);
1156 RelocationRange boot_oat(image_header.GetBootOatBegin(),
1157 boot_oat_begin,
1158 boot_oat_size);
1159 RelocationRange app_image(reinterpret_cast<uintptr_t>(image_header.GetImageBegin()),
1160 reinterpret_cast<uintptr_t>(target_base),
1161 image_header.GetImageSize());
1162 // Use the oat data section since this is where the OatFile::Begin is.
1163 RelocationRange app_oat(reinterpret_cast<uintptr_t>(image_header.GetOatDataBegin()),
1164 // Not necessarily in low 4GB.
1165 reinterpret_cast<uintptr_t>(app_oat_file->Begin()),
1166 image_header.GetOatDataEnd() - image_header.GetOatDataBegin());
1167 VLOG(image) << "App image " << app_image;
1168 VLOG(image) << "App oat " << app_oat;
1169 VLOG(image) << "Boot image " << boot_image;
1170 VLOG(image) << "Boot oat " << boot_oat;
1171 // True if we need to fixup any heap pointers, otherwise only code pointers.
1172 const bool fixup_image = boot_image.Delta() != 0 || app_image.Delta() != 0;
1173 const bool fixup_code = boot_oat.Delta() != 0 || app_oat.Delta() != 0;
1174 if (!fixup_image && !fixup_code) {
1175 // Nothing to fix up.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001176 return true;
1177 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07001178 ScopedDebugDisallowReadBarriers sddrb(Thread::Current());
1179 // Need to update the image to be at the target base.
1180 const ImageSection& objects_section = image_header.GetImageSection(ImageHeader::kSectionObjects);
1181 uintptr_t objects_begin = reinterpret_cast<uintptr_t>(target_base + objects_section.Offset());
1182 uintptr_t objects_end = reinterpret_cast<uintptr_t>(target_base + objects_section.End());
1183 FixupObjectAdapter fixup_adapter(boot_image, boot_oat, app_image, app_oat);
1184 if (fixup_image) {
1185 // Two pass approach, fix up all classes first, then fix up non class-objects.
1186 // The visited bitmap is used to ensure that pointer arrays are not forwarded twice.
1187 std::unique_ptr<gc::accounting::ContinuousSpaceBitmap> visited_bitmap(
1188 gc::accounting::ContinuousSpaceBitmap::Create("Relocate bitmap",
1189 target_base,
1190 image_header.GetImageSize()));
1191 FixupObjectVisitor fixup_object_visitor(visited_bitmap.get(),
1192 pointer_size,
1193 boot_image,
1194 boot_oat,
1195 app_image,
1196 app_oat);
1197 TimingLogger::ScopedTiming timing("Fixup classes", &logger);
1198 // Fixup objects may read fields in the boot image, use the mutator lock here for sanity. Though
1199 // its probably not required.
1200 ScopedObjectAccess soa(Thread::Current());
1201 timing.NewTiming("Fixup objects");
1202 bitmap->VisitMarkedRange(objects_begin, objects_end, fixup_object_visitor);
1203 // Fixup image roots.
1204 CHECK(app_image.InSource(reinterpret_cast<uintptr_t>(
1205 image_header.GetImageRoots<kWithoutReadBarrier>())));
1206 image_header.RelocateImageObjects(app_image.Delta());
1207 CHECK_EQ(image_header.GetImageBegin(), target_base);
1208 // Fix up dex cache DexFile pointers.
1209 auto* dex_caches = image_header.GetImageRoot<kWithoutReadBarrier>(ImageHeader::kDexCaches)->
1210 AsObjectArray<mirror::DexCache, kVerifyNone, kWithoutReadBarrier>();
1211 for (int32_t i = 0, count = dex_caches->GetLength(); i < count; ++i) {
1212 mirror::DexCache* dex_cache = dex_caches->Get<kVerifyNone, kWithoutReadBarrier>(i);
1213 // Fix up dex cache pointers.
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07001214 mirror::StringDexCacheType* strings = dex_cache->GetStrings();
Andreas Gampea463b6a2016-08-12 21:53:32 -07001215 if (strings != nullptr) {
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07001216 mirror::StringDexCacheType* new_strings = fixup_adapter.ForwardObject(strings);
Andreas Gampea463b6a2016-08-12 21:53:32 -07001217 if (strings != new_strings) {
1218 dex_cache->SetStrings(new_strings);
1219 }
1220 dex_cache->FixupStrings<kWithoutReadBarrier>(new_strings, fixup_adapter);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001221 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07001222 GcRoot<mirror::Class>* types = dex_cache->GetResolvedTypes();
1223 if (types != nullptr) {
1224 GcRoot<mirror::Class>* new_types = fixup_adapter.ForwardObject(types);
1225 if (types != new_types) {
1226 dex_cache->SetResolvedTypes(new_types);
1227 }
1228 dex_cache->FixupResolvedTypes<kWithoutReadBarrier>(new_types, fixup_adapter);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001229 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07001230 ArtMethod** methods = dex_cache->GetResolvedMethods();
1231 if (methods != nullptr) {
1232 ArtMethod** new_methods = fixup_adapter.ForwardObject(methods);
1233 if (methods != new_methods) {
1234 dex_cache->SetResolvedMethods(new_methods);
1235 }
1236 for (size_t j = 0, num = dex_cache->NumResolvedMethods(); j != num; ++j) {
1237 ArtMethod* orig = mirror::DexCache::GetElementPtrSize(new_methods, j, pointer_size);
1238 ArtMethod* copy = fixup_adapter.ForwardObject(orig);
1239 if (orig != copy) {
1240 mirror::DexCache::SetElementPtrSize(new_methods, j, copy, pointer_size);
1241 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001242 }
1243 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07001244 ArtField** fields = dex_cache->GetResolvedFields();
1245 if (fields != nullptr) {
1246 ArtField** new_fields = fixup_adapter.ForwardObject(fields);
1247 if (fields != new_fields) {
1248 dex_cache->SetResolvedFields(new_fields);
1249 }
1250 for (size_t j = 0, num = dex_cache->NumResolvedFields(); j != num; ++j) {
1251 ArtField* orig = mirror::DexCache::GetElementPtrSize(new_fields, j, pointer_size);
1252 ArtField* copy = fixup_adapter.ForwardObject(orig);
1253 if (orig != copy) {
1254 mirror::DexCache::SetElementPtrSize(new_fields, j, copy, pointer_size);
1255 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001256 }
1257 }
Narayan Kamath7fe56582016-10-14 18:49:12 +01001258
1259 mirror::MethodTypeDexCacheType* method_types = dex_cache->GetResolvedMethodTypes();
1260 if (method_types != nullptr) {
1261 mirror::MethodTypeDexCacheType* new_method_types =
1262 fixup_adapter.ForwardObject(method_types);
1263 if (method_types != new_method_types) {
1264 dex_cache->SetResolvedMethodTypes(new_method_types);
1265 }
1266 dex_cache->FixupResolvedMethodTypes<kWithoutReadBarrier>(new_method_types, fixup_adapter);
1267 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001268 }
1269 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001270 {
1271 // Only touches objects in the app image, no need for mutator lock.
Andreas Gampea463b6a2016-08-12 21:53:32 -07001272 TimingLogger::ScopedTiming timing("Fixup methods", &logger);
1273 FixupArtMethodVisitor method_visitor(fixup_image,
1274 pointer_size,
1275 boot_image,
1276 boot_oat,
1277 app_image,
1278 app_oat);
1279 image_header.VisitPackedArtMethods(&method_visitor, target_base, pointer_size);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001280 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07001281 if (fixup_image) {
1282 {
1283 // Only touches objects in the app image, no need for mutator lock.
1284 TimingLogger::ScopedTiming timing("Fixup fields", &logger);
1285 FixupArtFieldVisitor field_visitor(boot_image, boot_oat, app_image, app_oat);
1286 image_header.VisitPackedArtFields(&field_visitor, target_base);
1287 }
1288 {
1289 TimingLogger::ScopedTiming timing("Fixup imt", &logger);
1290 image_header.VisitPackedImTables(fixup_adapter, target_base, pointer_size);
1291 }
1292 {
1293 TimingLogger::ScopedTiming timing("Fixup conflict tables", &logger);
1294 image_header.VisitPackedImtConflictTables(fixup_adapter, target_base, pointer_size);
1295 }
1296 // In the app image case, the image methods are actually in the boot image.
1297 image_header.RelocateImageMethods(boot_image.Delta());
1298 const auto& class_table_section = image_header.GetImageSection(ImageHeader::kSectionClassTable);
1299 if (class_table_section.Size() > 0u) {
1300 // Note that we require that ReadFromMemory does not make an internal copy of the elements.
1301 // This also relies on visit roots not doing any verification which could fail after we update
1302 // the roots to be the image addresses.
1303 ScopedObjectAccess soa(Thread::Current());
1304 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
1305 ClassTable temp_table;
1306 temp_table.ReadFromMemory(target_base + class_table_section.Offset());
1307 FixupRootVisitor root_visitor(boot_image, boot_oat, app_image, app_oat);
1308 temp_table.VisitRoots(root_visitor);
1309 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001310 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07001311 if (VLOG_IS_ON(image)) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07001312 logger.Dump(LOG_STREAM(INFO));
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001313 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07001314 return true;
Andreas Gampe7fa55782016-06-15 17:45:01 -07001315 }
1316
Andreas Gampea463b6a2016-08-12 21:53:32 -07001317 static std::unique_ptr<OatFile> OpenOatFile(const ImageSpace& image,
1318 const char* image_path,
1319 std::string* error_msg) {
1320 const ImageHeader& image_header = image.GetImageHeader();
1321 std::string oat_filename = ImageHeader::GetOatLocationFromImageLocation(image_path);
Andreas Gampe7fa55782016-06-15 17:45:01 -07001322
Andreas Gampea463b6a2016-08-12 21:53:32 -07001323 CHECK(image_header.GetOatDataBegin() != nullptr);
1324
1325 std::unique_ptr<OatFile> oat_file(OatFile::Open(oat_filename,
1326 oat_filename,
1327 image_header.GetOatDataBegin(),
1328 image_header.GetOatFileBegin(),
1329 !Runtime::Current()->IsAotCompiler(),
1330 /*low_4gb*/false,
1331 nullptr,
1332 error_msg));
1333 if (oat_file == nullptr) {
1334 *error_msg = StringPrintf("Failed to open oat file '%s' referenced from image %s: %s",
1335 oat_filename.c_str(),
1336 image.GetName(),
1337 error_msg->c_str());
Andreas Gampe7fa55782016-06-15 17:45:01 -07001338 return nullptr;
1339 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07001340 uint32_t oat_checksum = oat_file->GetOatHeader().GetChecksum();
1341 uint32_t image_oat_checksum = image_header.GetOatChecksum();
Mathieu Chartier9ff84602016-01-29 12:22:17 -08001342 if (oat_checksum != image_oat_checksum) {
Andreas Gampea463b6a2016-08-12 21:53:32 -07001343 *error_msg = StringPrintf("Failed to match oat file checksum 0x%x to expected oat checksum 0x%x"
1344 " in image %s",
Mathieu Chartier9ff84602016-01-29 12:22:17 -08001345 oat_checksum,
1346 image_oat_checksum,
Andreas Gampea463b6a2016-08-12 21:53:32 -07001347 image.GetName());
Mathieu Chartier9ff84602016-01-29 12:22:17 -08001348 return nullptr;
1349 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07001350 int32_t image_patch_delta = image_header.GetPatchDelta();
1351 int32_t oat_patch_delta = oat_file->GetOatHeader().GetImagePatchDelta();
1352 if (oat_patch_delta != image_patch_delta && !image_header.CompilePic()) {
1353 // We should have already relocated by this point. Bail out.
1354 *error_msg = StringPrintf("Failed to match oat file patch delta %d to expected patch delta %d "
1355 "in image %s",
1356 oat_patch_delta,
1357 image_patch_delta,
1358 image.GetName());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001359 return nullptr;
1360 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07001361
1362 return oat_file;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001363 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07001364
1365 static bool ValidateOatFile(const ImageSpace& space,
1366 const OatFile& oat_file,
1367 std::string* error_msg) {
1368 for (const OatFile::OatDexFile* oat_dex_file : oat_file.GetOatDexFiles()) {
1369 const std::string& dex_file_location = oat_dex_file->GetDexFileLocation();
1370 uint32_t dex_file_location_checksum;
1371 if (!DexFile::GetChecksum(dex_file_location.c_str(), &dex_file_location_checksum, error_msg)) {
1372 *error_msg = StringPrintf("Failed to get checksum of dex file '%s' referenced by image %s: "
1373 "%s",
1374 dex_file_location.c_str(),
1375 space.GetName(),
1376 error_msg->c_str());
1377 return false;
1378 }
1379 if (dex_file_location_checksum != oat_dex_file->GetDexFileLocationChecksum()) {
1380 *error_msg = StringPrintf("ValidateOatFile found checksum mismatch between oat file '%s' and "
1381 "dex file '%s' (0x%x != 0x%x)",
1382 oat_file.GetLocation().c_str(),
1383 dex_file_location.c_str(),
1384 oat_dex_file->GetDexFileLocationChecksum(),
1385 dex_file_location_checksum);
1386 return false;
1387 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001388 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07001389 return true;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001390 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07001391};
Hiroshi Yamauchibd0fb612014-05-20 13:46:00 -07001392
Andreas Gampea463b6a2016-08-12 21:53:32 -07001393static constexpr uint64_t kLowSpaceValue = 50 * MB;
1394static constexpr uint64_t kTmpFsSentinelValue = 384 * MB;
1395
1396// Read the free space of the cache partition and make a decision whether to keep the generated
1397// image. This is to try to mitigate situations where the system might run out of space later.
1398static bool CheckSpace(const std::string& cache_filename, std::string* error_msg) {
1399 // Using statvfs vs statvfs64 because of b/18207376, and it is enough for all practical purposes.
1400 struct statvfs buf;
1401
1402 int res = TEMP_FAILURE_RETRY(statvfs(cache_filename.c_str(), &buf));
1403 if (res != 0) {
1404 // Could not stat. Conservatively tell the system to delete the image.
1405 *error_msg = "Could not stat the filesystem, assuming low-memory situation.";
1406 return false;
Nicolas Geoffray1bc977c2016-01-23 14:15:49 +00001407 }
Nicolas Geoffray1bc977c2016-01-23 14:15:49 +00001408
Andreas Gampea463b6a2016-08-12 21:53:32 -07001409 uint64_t fs_overall_size = buf.f_bsize * static_cast<uint64_t>(buf.f_blocks);
1410 // Zygote is privileged, but other things are not. Use bavail.
1411 uint64_t fs_free_size = buf.f_bsize * static_cast<uint64_t>(buf.f_bavail);
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001412
Andreas Gampea463b6a2016-08-12 21:53:32 -07001413 // Take the overall size as an indicator for a tmpfs, which is being used for the decryption
1414 // environment. We do not want to fail quickening the boot image there, as it is beneficial
1415 // for time-to-UI.
1416 if (fs_overall_size > kTmpFsSentinelValue) {
1417 if (fs_free_size < kLowSpaceValue) {
1418 *error_msg = StringPrintf("Low-memory situation: only %4.2f megabytes available, need at "
1419 "least %" PRIu64 ".",
1420 static_cast<double>(fs_free_size) / MB,
1421 kLowSpaceValue / MB);
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001422 return false;
1423 }
1424 }
1425 return true;
1426}
1427
Andreas Gampea463b6a2016-08-12 21:53:32 -07001428std::unique_ptr<ImageSpace> ImageSpace::CreateBootImage(const char* image_location,
1429 const InstructionSet image_isa,
1430 bool secondary_image,
1431 std::string* error_msg) {
1432 ScopedTrace trace(__FUNCTION__);
1433
1434 // Step 0: Extra zygote work.
1435
1436 // Step 0.a: If we're the zygote, mark boot.
1437 const bool is_zygote = Runtime::Current()->IsZygote();
Robert Sesekbfa1f8d2016-08-15 15:21:09 -04001438 if (is_zygote && !secondary_image && CanWriteToDalvikCache(image_isa)) {
Andreas Gampea463b6a2016-08-12 21:53:32 -07001439 MarkZygoteStart(image_isa, Runtime::Current()->GetZygoteMaxFailedBoots());
1440 }
1441
1442 // Step 0.b: If we're the zygote, check for free space, and prune the cache preemptively,
1443 // if necessary. While the runtime may be fine (it is pretty tolerant to
1444 // out-of-disk-space situations), other parts of the platform are not.
1445 //
1446 // The advantage of doing this proactively is that the later steps are simplified,
1447 // i.e., we do not need to code retries.
1448 std::string system_filename;
1449 bool has_system = false;
1450 std::string cache_filename;
1451 bool has_cache = false;
1452 bool dalvik_cache_exists = false;
1453 bool is_global_cache = true;
1454 std::string dalvik_cache;
1455 bool found_image = FindImageFilenameImpl(image_location,
1456 image_isa,
1457 &has_system,
1458 &system_filename,
1459 &dalvik_cache_exists,
1460 &dalvik_cache,
1461 &is_global_cache,
1462 &has_cache,
1463 &cache_filename);
1464
1465 if (is_zygote && dalvik_cache_exists) {
1466 DCHECK(!dalvik_cache.empty());
1467 std::string local_error_msg;
1468 if (!CheckSpace(dalvik_cache, &local_error_msg)) {
1469 LOG(WARNING) << local_error_msg << " Preemptively pruning the dalvik cache.";
1470 PruneDalvikCache(image_isa);
1471
1472 // Re-evaluate the image.
1473 found_image = FindImageFilenameImpl(image_location,
1474 image_isa,
1475 &has_system,
1476 &system_filename,
1477 &dalvik_cache_exists,
1478 &dalvik_cache,
1479 &is_global_cache,
1480 &has_cache,
1481 &cache_filename);
1482 }
1483 }
1484
1485 // Collect all the errors.
1486 std::vector<std::string> error_msgs;
1487
1488 // Step 1: Check if we have an existing and relocated image.
1489
1490 // Step 1.a: Have files in system and cache. Then they need to match.
1491 if (found_image && has_system && has_cache) {
1492 std::string local_error_msg;
1493 // Check that the files are matching.
1494 if (ChecksumsMatch(system_filename.c_str(), cache_filename.c_str(), &local_error_msg)) {
1495 std::unique_ptr<ImageSpace> relocated_space =
1496 ImageSpaceLoader::Load(image_location,
1497 cache_filename,
1498 is_zygote,
1499 is_global_cache,
Andreas Gampe44c8ed62016-08-19 16:43:00 -07001500 /* validate_oat_file */ false,
Andreas Gampea463b6a2016-08-12 21:53:32 -07001501 &local_error_msg);
1502 if (relocated_space != nullptr) {
1503 return relocated_space;
1504 }
1505 }
1506 error_msgs.push_back(local_error_msg);
1507 }
1508
1509 // Step 1.b: Only have a cache file.
1510 if (found_image && !has_system && has_cache) {
1511 std::string local_error_msg;
1512 std::unique_ptr<ImageSpace> cache_space =
1513 ImageSpaceLoader::Load(image_location,
1514 cache_filename,
1515 is_zygote,
1516 is_global_cache,
Andreas Gampe44c8ed62016-08-19 16:43:00 -07001517 /* validate_oat_file */ true,
Andreas Gampea463b6a2016-08-12 21:53:32 -07001518 &local_error_msg);
1519 if (cache_space != nullptr) {
1520 return cache_space;
1521 }
1522 error_msgs.push_back(local_error_msg);
1523 }
1524
1525 // Step 2: We have an existing image in /system.
1526
1527 // Step 2.a: We are not required to relocate it. Then we can use it directly.
1528 bool relocate = Runtime::Current()->ShouldRelocate();
1529
1530 if (found_image && has_system && !relocate) {
1531 std::string local_error_msg;
1532 std::unique_ptr<ImageSpace> system_space =
1533 ImageSpaceLoader::Load(image_location,
1534 system_filename,
1535 is_zygote,
1536 is_global_cache,
Andreas Gampe44c8ed62016-08-19 16:43:00 -07001537 /* validate_oat_file */ false,
Andreas Gampea463b6a2016-08-12 21:53:32 -07001538 &local_error_msg);
1539 if (system_space != nullptr) {
1540 return system_space;
1541 }
1542 error_msgs.push_back(local_error_msg);
1543 }
1544
1545 // Step 2.b: We require a relocated image. Then we must patch it. This step fails if this is a
1546 // secondary image.
1547 if (found_image && has_system && relocate) {
1548 std::string local_error_msg;
1549 if (!Runtime::Current()->IsImageDex2OatEnabled()) {
1550 local_error_msg = "Patching disabled.";
1551 } else if (secondary_image) {
1552 local_error_msg = "Cannot patch a secondary image.";
Robert Sesekbfa1f8d2016-08-15 15:21:09 -04001553 } else if (ImageCreationAllowed(is_global_cache, image_isa, &local_error_msg)) {
Andreas Gampea463b6a2016-08-12 21:53:32 -07001554 bool patch_success =
1555 RelocateImage(image_location, cache_filename.c_str(), image_isa, &local_error_msg);
1556 if (patch_success) {
1557 std::unique_ptr<ImageSpace> patched_space =
1558 ImageSpaceLoader::Load(image_location,
1559 cache_filename,
1560 is_zygote,
1561 is_global_cache,
Andreas Gampe44c8ed62016-08-19 16:43:00 -07001562 /* validate_oat_file */ false,
Andreas Gampea463b6a2016-08-12 21:53:32 -07001563 &local_error_msg);
1564 if (patched_space != nullptr) {
1565 return patched_space;
1566 }
1567 }
1568 }
1569 error_msgs.push_back(StringPrintf("Cannot relocate image %s to %s: %s",
1570 image_location,
1571 cache_filename.c_str(),
1572 local_error_msg.c_str()));
1573 }
1574
1575 // Step 3: We do not have an existing image in /system, so generate an image into the dalvik
1576 // cache. This step fails if this is a secondary image.
1577 if (!has_system) {
1578 std::string local_error_msg;
1579 if (!Runtime::Current()->IsImageDex2OatEnabled()) {
1580 local_error_msg = "Image compilation disabled.";
1581 } else if (secondary_image) {
1582 local_error_msg = "Cannot compile a secondary image.";
Robert Sesekbfa1f8d2016-08-15 15:21:09 -04001583 } else if (ImageCreationAllowed(is_global_cache, image_isa, &local_error_msg)) {
Andreas Gampea463b6a2016-08-12 21:53:32 -07001584 bool compilation_success = GenerateImage(cache_filename, image_isa, &local_error_msg);
1585 if (compilation_success) {
1586 std::unique_ptr<ImageSpace> compiled_space =
1587 ImageSpaceLoader::Load(image_location,
1588 cache_filename,
1589 is_zygote,
1590 is_global_cache,
Andreas Gampe44c8ed62016-08-19 16:43:00 -07001591 /* validate_oat_file */ false,
Andreas Gampea463b6a2016-08-12 21:53:32 -07001592 &local_error_msg);
1593 if (compiled_space != nullptr) {
1594 return compiled_space;
1595 }
1596 }
1597 }
1598 error_msgs.push_back(StringPrintf("Cannot compile image to %s: %s",
1599 cache_filename.c_str(),
1600 local_error_msg.c_str()));
1601 }
1602
1603 // We failed. Prune the cache the free up space, create a compound error message and return no
1604 // image.
1605 PruneDalvikCache(image_isa);
1606
1607 std::ostringstream oss;
1608 bool first = true;
Andreas Gampe4c481a42016-11-03 08:21:59 -07001609 for (const auto& msg : error_msgs) {
Andreas Gampea463b6a2016-08-12 21:53:32 -07001610 if (!first) {
1611 oss << "\n ";
1612 }
1613 oss << msg;
1614 }
1615 *error_msg = oss.str();
1616
1617 return nullptr;
1618}
1619
1620std::unique_ptr<ImageSpace> ImageSpace::CreateFromAppImage(const char* image,
1621 const OatFile* oat_file,
1622 std::string* error_msg) {
1623 return ImageSpaceLoader::Init(image,
1624 image,
1625 /*validate_oat_file*/false,
1626 oat_file,
1627 /*out*/error_msg);
1628}
1629
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001630const OatFile* ImageSpace::GetOatFile() const {
Andreas Gampe88da3b02015-06-12 20:38:49 -07001631 return oat_file_non_owned_;
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001632}
1633
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -07001634std::unique_ptr<const OatFile> ImageSpace::ReleaseOatFile() {
1635 CHECK(oat_file_ != nullptr);
1636 return std::move(oat_file_);
Ian Rogers1d54e732013-05-02 21:10:01 -07001637}
1638
Ian Rogers1d54e732013-05-02 21:10:01 -07001639void ImageSpace::Dump(std::ostream& os) const {
1640 os << GetType()
Mathieu Chartier590fee92013-09-13 13:46:47 -07001641 << " begin=" << reinterpret_cast<void*>(Begin())
Ian Rogers1d54e732013-05-02 21:10:01 -07001642 << ",end=" << reinterpret_cast<void*>(End())
1643 << ",size=" << PrettySize(Size())
1644 << ",name=\"" << GetName() << "\"]";
1645}
1646
Mathieu Chartier866d8742016-09-21 15:24:18 -07001647std::string ImageSpace::GetMultiImageBootClassPath(
1648 const std::vector<const char*>& dex_locations,
1649 const std::vector<const char*>& oat_filenames,
1650 const std::vector<const char*>& image_filenames) {
1651 DCHECK_GT(oat_filenames.size(), 1u);
1652 // If the image filename was adapted (e.g., for our tests), we need to change this here,
1653 // too, but need to strip all path components (they will be re-established when loading).
1654 std::ostringstream bootcp_oss;
1655 bool first_bootcp = true;
1656 for (size_t i = 0; i < dex_locations.size(); ++i) {
1657 if (!first_bootcp) {
1658 bootcp_oss << ":";
1659 }
1660
1661 std::string dex_loc = dex_locations[i];
1662 std::string image_filename = image_filenames[i];
1663
1664 // Use the dex_loc path, but the image_filename name (without path elements).
1665 size_t dex_last_slash = dex_loc.rfind('/');
1666
1667 // npos is max(size_t). That makes this a bit ugly.
1668 size_t image_last_slash = image_filename.rfind('/');
1669 size_t image_last_at = image_filename.rfind('@');
1670 size_t image_last_sep = (image_last_slash == std::string::npos)
1671 ? image_last_at
1672 : (image_last_at == std::string::npos)
1673 ? std::string::npos
1674 : std::max(image_last_slash, image_last_at);
1675 // Note: whenever image_last_sep == npos, +1 overflow means using the full string.
1676
1677 if (dex_last_slash == std::string::npos) {
1678 dex_loc = image_filename.substr(image_last_sep + 1);
1679 } else {
1680 dex_loc = dex_loc.substr(0, dex_last_slash + 1) +
1681 image_filename.substr(image_last_sep + 1);
1682 }
1683
1684 // Image filenames already end with .art, no need to replace.
1685
1686 bootcp_oss << dex_loc;
1687 first_bootcp = false;
1688 }
1689 return bootcp_oss.str();
1690}
1691
1692void ImageSpace::ExtractMultiImageLocations(const std::string& input_image_file_name,
1693 const std::string& boot_classpath,
1694 std::vector<std::string>* image_file_names) {
Andreas Gampe8994a042015-12-30 19:03:17 +00001695 DCHECK(image_file_names != nullptr);
1696
1697 std::vector<std::string> images;
1698 Split(boot_classpath, ':', &images);
1699
1700 // Add the rest into the list. We have to adjust locations, possibly:
1701 //
1702 // For example, image_file_name is /a/b/c/d/e.art
1703 // images[0] is f/c/d/e.art
1704 // ----------------------------------------------
1705 // images[1] is g/h/i/j.art -> /a/b/h/i/j.art
Mathieu Chartier8b8f6d62016-03-08 16:50:20 -08001706 const std::string& first_image = images[0];
1707 // Length of common suffix.
1708 size_t common = 0;
1709 while (common < input_image_file_name.size() &&
1710 common < first_image.size() &&
1711 *(input_image_file_name.end() - common - 1) == *(first_image.end() - common - 1)) {
1712 ++common;
Andreas Gampe8994a042015-12-30 19:03:17 +00001713 }
Mathieu Chartier8b8f6d62016-03-08 16:50:20 -08001714 // We want to replace the prefix of the input image with the prefix of the boot class path.
1715 // This handles the case where the image file contains @ separators.
1716 // Example image_file_name is oats/system@framework@boot.art
1717 // images[0] is .../arm/boot.art
1718 // means that the image name prefix will be oats/system@framework@
1719 // so that the other images are openable.
1720 const size_t old_prefix_length = first_image.size() - common;
1721 const std::string new_prefix = input_image_file_name.substr(
1722 0,
1723 input_image_file_name.size() - common);
Andreas Gampe8994a042015-12-30 19:03:17 +00001724
1725 // Apply pattern to images[1] .. images[n].
1726 for (size_t i = 1; i < images.size(); ++i) {
Mathieu Chartier8b8f6d62016-03-08 16:50:20 -08001727 const std::string& image = images[i];
1728 CHECK_GT(image.length(), old_prefix_length);
1729 std::string suffix = image.substr(old_prefix_length);
1730 image_file_names->push_back(new_prefix + suffix);
Andreas Gampe8994a042015-12-30 19:03:17 +00001731 }
1732}
1733
Mathieu Chartierd5f3f322016-03-21 14:05:56 -07001734void ImageSpace::DumpSections(std::ostream& os) const {
1735 const uint8_t* base = Begin();
1736 const ImageHeader& header = GetImageHeader();
1737 for (size_t i = 0; i < ImageHeader::kSectionCount; ++i) {
1738 auto section_type = static_cast<ImageHeader::ImageSections>(i);
1739 const ImageSection& section = header.GetImageSection(section_type);
1740 os << section_type << " " << reinterpret_cast<const void*>(base + section.Offset())
1741 << "-" << reinterpret_cast<const void*>(base + section.End()) << "\n";
1742 }
1743}
1744
Ian Rogers1d54e732013-05-02 21:10:01 -07001745} // namespace space
1746} // namespace gc
1747} // namespace art