blob: 4505c249feac3502c600d589862f8f4cf64ffef0 [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
Andreas Gampe3c13a792014-09-18 20:56:04 -0700366static bool ImageCreationAllowed(bool is_global_cache, std::string* error_msg) {
367 // Anyone can write into a "local" cache.
368 if (!is_global_cache) {
369 return true;
370 }
371
372 // Only the zygote is allowed to create the global boot image.
373 if (Runtime::Current()->IsZygote()) {
374 return true;
375 }
376
377 *error_msg = "Only the zygote can create the global boot image.";
378 return false;
379}
380
Mathieu Chartier31e89252013-08-28 11:29:12 -0700381void ImageSpace::VerifyImageAllocations() {
Ian Rogers13735952014-10-08 12:43:28 -0700382 uint8_t* current = Begin() + RoundUp(sizeof(ImageHeader), kObjectAlignment);
Mathieu Chartier31e89252013-08-28 11:29:12 -0700383 while (current < End()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700384 CHECK_ALIGNED(current, kObjectAlignment);
385 auto* obj = reinterpret_cast<mirror::Object*>(current);
Mathieu Chartier31e89252013-08-28 11:29:12 -0700386 CHECK(obj->GetClass() != nullptr) << "Image object at address " << obj << " has null class";
Mathieu Chartierc7853442015-03-27 14:35:38 -0700387 CHECK(live_bitmap_->Test(obj)) << PrettyTypeOf(obj);
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -0700388 if (kUseBakerOrBrooksReadBarrier) {
389 obj->AssertReadBarrierPointer();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800390 }
Mathieu Chartier31e89252013-08-28 11:29:12 -0700391 current += RoundUp(obj->SizeOf(), kObjectAlignment);
392 }
393}
394
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800395// Helper class for relocating from one range of memory to another.
396class RelocationRange {
397 public:
398 RelocationRange() = default;
399 RelocationRange(const RelocationRange&) = default;
400 RelocationRange(uintptr_t source, uintptr_t dest, uintptr_t length)
401 : source_(source),
402 dest_(dest),
403 length_(length) {}
404
Mathieu Chartier91edc622016-02-16 17:16:01 -0800405 bool InSource(uintptr_t address) const {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800406 return address - source_ < length_;
407 }
408
Mathieu Chartier91edc622016-02-16 17:16:01 -0800409 bool InDest(uintptr_t address) const {
410 return address - dest_ < length_;
411 }
412
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800413 // Translate a source address to the destination space.
414 uintptr_t ToDest(uintptr_t address) const {
Mathieu Chartier91edc622016-02-16 17:16:01 -0800415 DCHECK(InSource(address));
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800416 return address + Delta();
417 }
418
419 // Returns the delta between the dest from the source.
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800420 uintptr_t Delta() const {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800421 return dest_ - source_;
422 }
423
424 uintptr_t Source() const {
425 return source_;
426 }
427
428 uintptr_t Dest() const {
429 return dest_;
430 }
431
432 uintptr_t Length() const {
433 return length_;
434 }
435
436 private:
437 const uintptr_t source_;
438 const uintptr_t dest_;
439 const uintptr_t length_;
440};
441
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800442std::ostream& operator<<(std::ostream& os, const RelocationRange& reloc) {
443 return os << "(" << reinterpret_cast<const void*>(reloc.Source()) << "-"
444 << reinterpret_cast<const void*>(reloc.Source() + reloc.Length()) << ")->("
445 << reinterpret_cast<const void*>(reloc.Dest()) << "-"
446 << reinterpret_cast<const void*>(reloc.Dest() + reloc.Length()) << ")";
447}
448
Andreas Gampea463b6a2016-08-12 21:53:32 -0700449// Helper class encapsulating loading, so we can access private ImageSpace members (this is a
450// friend class), but not declare functions in the header.
451class ImageSpaceLoader {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800452 public:
Andreas Gampea463b6a2016-08-12 21:53:32 -0700453 static std::unique_ptr<ImageSpace> Load(const char* image_location,
454 const std::string& image_filename,
455 bool is_zygote,
456 bool is_global_cache,
457 bool is_system,
458 bool relocated_version_used,
459 std::string* error_msg)
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800460 SHARED_REQUIRES(Locks::mutator_lock_) {
Andreas Gampea463b6a2016-08-12 21:53:32 -0700461 // Note that we must not use the file descriptor associated with
462 // ScopedFlock::GetFile to Init the image file. We want the file
463 // descriptor (and the associated exclusive lock) to be released when
464 // we leave Create.
465 ScopedFlock image_lock;
466 // Should this be a RDWR lock? This is only a defensive measure, as at
467 // this point the image should exist.
468 // However, only the zygote can write into the global dalvik-cache, so
469 // restrict to zygote processes, or any process that isn't using
470 // /data/dalvik-cache (which we assume to be allowed to write there).
471 const bool rw_lock = is_zygote || !is_global_cache;
472 image_lock.Init(image_filename.c_str(),
473 rw_lock ? (O_CREAT | O_RDWR) : O_RDONLY /* flags */,
474 true /* block */,
475 error_msg);
476 VLOG(startup) << "Using image file " << image_filename.c_str() << " for image location "
477 << image_location;
478 // If we are in /system we can assume the image is good. We can also
479 // assume this if we are using a relocated image (i.e. image checksum
480 // matches) since this is only different by the offset. We need this to
481 // make sure that host tests continue to work.
482 // Since we are the boot image, pass null since we load the oat file from the boot image oat
483 // file name.
484 return Init(image_filename.c_str(),
485 image_location,
486 !(is_system || relocated_version_used),
487 /* oat_file */nullptr,
488 error_msg);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800489 }
490
Andreas Gampea463b6a2016-08-12 21:53:32 -0700491 static std::unique_ptr<ImageSpace> Init(const char* image_filename,
492 const char* image_location,
493 bool validate_oat_file,
494 const OatFile* oat_file,
495 std::string* error_msg)
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800496 SHARED_REQUIRES(Locks::mutator_lock_) {
Andreas Gampea463b6a2016-08-12 21:53:32 -0700497 CHECK(image_filename != nullptr);
498 CHECK(image_location != nullptr);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800499
Andreas Gampea463b6a2016-08-12 21:53:32 -0700500 TimingLogger logger(__PRETTY_FUNCTION__, true, VLOG_IS_ON(image));
501 VLOG(image) << "ImageSpace::Init entering image_filename=" << image_filename;
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800502
Andreas Gampea463b6a2016-08-12 21:53:32 -0700503 std::unique_ptr<File> file;
Mathieu Chartier92ec5942016-04-11 12:03:48 -0700504 {
Andreas Gampea463b6a2016-08-12 21:53:32 -0700505 TimingLogger::ScopedTiming timing("OpenImageFile", &logger);
506 file.reset(OS::OpenFileForReading(image_filename));
507 if (file == nullptr) {
508 *error_msg = StringPrintf("Failed to open '%s'", image_filename);
509 return nullptr;
Mathieu Chartier92ec5942016-04-11 12:03:48 -0700510 }
Andreas Gampea463b6a2016-08-12 21:53:32 -0700511 }
512 ImageHeader temp_image_header;
513 ImageHeader* image_header = &temp_image_header;
514 {
515 TimingLogger::ScopedTiming timing("ReadImageHeader", &logger);
516 bool success = file->ReadFully(image_header, sizeof(*image_header));
517 if (!success || !image_header->IsValid()) {
518 *error_msg = StringPrintf("Invalid image header in '%s'", image_filename);
519 return nullptr;
520 }
521 }
522 // Check that the file is larger or equal to the header size + data size.
523 const uint64_t image_file_size = static_cast<uint64_t>(file->GetLength());
524 if (image_file_size < sizeof(ImageHeader) + image_header->GetDataSize()) {
525 *error_msg = StringPrintf("Image file truncated: %" PRIu64 " vs. %" PRIu64 ".",
526 image_file_size,
527 sizeof(ImageHeader) + image_header->GetDataSize());
528 return nullptr;
529 }
530
531 if (oat_file != nullptr) {
532 // If we have an oat file, check the oat file checksum. The oat file is only non-null for the
533 // app image case. Otherwise, we open the oat file after the image and check the checksum there.
534 const uint32_t oat_checksum = oat_file->GetOatHeader().GetChecksum();
535 const uint32_t image_oat_checksum = image_header->GetOatChecksum();
536 if (oat_checksum != image_oat_checksum) {
537 *error_msg = StringPrintf("Oat checksum 0x%x does not match the image one 0x%x in image %s",
538 oat_checksum,
539 image_oat_checksum,
540 image_filename);
541 return nullptr;
Mathieu Chartier92ec5942016-04-11 12:03:48 -0700542 }
543 }
544
Andreas Gampea463b6a2016-08-12 21:53:32 -0700545 if (VLOG_IS_ON(startup)) {
546 LOG(INFO) << "Dumping image sections";
547 for (size_t i = 0; i < ImageHeader::kSectionCount; ++i) {
548 const auto section_idx = static_cast<ImageHeader::ImageSections>(i);
549 auto& section = image_header->GetImageSection(section_idx);
550 LOG(INFO) << section_idx << " start="
551 << reinterpret_cast<void*>(image_header->GetImageBegin() + section.Offset()) << " "
552 << section;
Mathieu Chartier92ec5942016-04-11 12:03:48 -0700553 }
Andreas Gampea463b6a2016-08-12 21:53:32 -0700554 }
555
556 const auto& bitmap_section = image_header->GetImageSection(ImageHeader::kSectionImageBitmap);
557 // The location we want to map from is the first aligned page after the end of the stored
558 // (possibly compressed) data.
559 const size_t image_bitmap_offset = RoundUp(sizeof(ImageHeader) + image_header->GetDataSize(),
560 kPageSize);
561 const size_t end_of_bitmap = image_bitmap_offset + bitmap_section.Size();
562 if (end_of_bitmap != image_file_size) {
563 *error_msg = StringPrintf(
564 "Image file size does not equal end of bitmap: size=%" PRIu64 " vs. %zu.", image_file_size,
565 end_of_bitmap);
566 return nullptr;
567 }
568
569 std::unique_ptr<MemMap> map;
570 // GetImageBegin is the preferred address to map the image. If we manage to map the
571 // image at the image begin, the amount of fixup work required is minimized.
572 map.reset(LoadImageFile(image_filename,
573 image_location,
574 *image_header,
575 image_header->GetImageBegin(),
576 file->Fd(),
577 logger,
578 error_msg));
579 // If the header specifies PIC mode, we can also map at a random low_4gb address since we can
580 // relocate in-place.
581 if (map == nullptr && image_header->IsPic()) {
582 map.reset(LoadImageFile(image_filename,
583 image_location,
584 *image_header,
585 /* address */ nullptr,
586 file->Fd(),
587 logger,
588 error_msg));
589 }
590 // Were we able to load something and continue?
591 if (map == nullptr) {
592 DCHECK(!error_msg->empty());
593 return nullptr;
594 }
595 DCHECK_EQ(0, memcmp(image_header, map->Begin(), sizeof(ImageHeader)));
596
597 std::unique_ptr<MemMap> image_bitmap_map(MemMap::MapFileAtAddress(nullptr,
598 bitmap_section.Size(),
599 PROT_READ, MAP_PRIVATE,
600 file->Fd(),
601 image_bitmap_offset,
602 /*low_4gb*/false,
603 /*reuse*/false,
604 image_filename,
605 error_msg));
606 if (image_bitmap_map == nullptr) {
607 *error_msg = StringPrintf("Failed to map image bitmap: %s", error_msg->c_str());
608 return nullptr;
609 }
610 // Loaded the map, use the image header from the file now in case we patch it with
611 // RelocateInPlace.
612 image_header = reinterpret_cast<ImageHeader*>(map->Begin());
613 const uint32_t bitmap_index = ImageSpace::bitmap_index_.FetchAndAddSequentiallyConsistent(1);
614 std::string bitmap_name(StringPrintf("imagespace %s live-bitmap %u",
615 image_filename,
616 bitmap_index));
617 // Bitmap only needs to cover until the end of the mirror objects section.
618 const ImageSection& image_objects = image_header->GetImageSection(ImageHeader::kSectionObjects);
619 // We only want the mirror object, not the ArtFields and ArtMethods.
620 uint8_t* const image_end = map->Begin() + image_objects.End();
621 std::unique_ptr<accounting::ContinuousSpaceBitmap> bitmap;
622 {
623 TimingLogger::ScopedTiming timing("CreateImageBitmap", &logger);
624 bitmap.reset(
625 accounting::ContinuousSpaceBitmap::CreateFromMemMap(
626 bitmap_name,
627 image_bitmap_map.release(),
628 reinterpret_cast<uint8_t*>(map->Begin()),
629 image_objects.End()));
630 if (bitmap == nullptr) {
631 *error_msg = StringPrintf("Could not create bitmap '%s'", bitmap_name.c_str());
632 return nullptr;
633 }
634 }
635 {
636 TimingLogger::ScopedTiming timing("RelocateImage", &logger);
637 if (!RelocateInPlace(*image_header,
638 map->Begin(),
639 bitmap.get(),
640 oat_file,
641 error_msg)) {
642 return nullptr;
643 }
644 }
645 // We only want the mirror object, not the ArtFields and ArtMethods.
646 std::unique_ptr<ImageSpace> space(new ImageSpace(image_filename,
647 image_location,
648 map.release(),
649 bitmap.release(),
650 image_end));
651
652 // VerifyImageAllocations() will be called later in Runtime::Init()
653 // as some class roots like ArtMethod::java_lang_reflect_ArtMethod_
654 // and ArtField::java_lang_reflect_ArtField_, which are used from
655 // Object::SizeOf() which VerifyImageAllocations() calls, are not
656 // set yet at this point.
657 if (oat_file == nullptr) {
658 TimingLogger::ScopedTiming timing("OpenOatFile", &logger);
659 space->oat_file_ = OpenOatFile(*space, image_filename, error_msg);
660 if (space->oat_file_ == nullptr) {
661 DCHECK(!error_msg->empty());
662 return nullptr;
663 }
664 space->oat_file_non_owned_ = space->oat_file_.get();
665 } else {
666 space->oat_file_non_owned_ = oat_file;
667 }
668
669 if (validate_oat_file) {
670 TimingLogger::ScopedTiming timing("ValidateOatFile", &logger);
671 CHECK(space->oat_file_ != nullptr);
672 if (!ValidateOatFile(*space, *space->oat_file_, error_msg)) {
673 DCHECK(!error_msg->empty());
674 return nullptr;
675 }
676 }
677
678 Runtime* runtime = Runtime::Current();
679
680 // If oat_file is null, then it is the boot image space. Use oat_file_non_owned_ from the space
681 // to set the runtime methods.
682 CHECK_EQ(oat_file != nullptr, image_header->IsAppImage());
683 if (image_header->IsAppImage()) {
684 CHECK_EQ(runtime->GetResolutionMethod(),
685 image_header->GetImageMethod(ImageHeader::kResolutionMethod));
686 CHECK_EQ(runtime->GetImtConflictMethod(),
687 image_header->GetImageMethod(ImageHeader::kImtConflictMethod));
688 CHECK_EQ(runtime->GetImtUnimplementedMethod(),
689 image_header->GetImageMethod(ImageHeader::kImtUnimplementedMethod));
690 CHECK_EQ(runtime->GetCalleeSaveMethod(Runtime::kSaveAllCalleeSaves),
691 image_header->GetImageMethod(ImageHeader::kSaveAllCalleeSavesMethod));
692 CHECK_EQ(runtime->GetCalleeSaveMethod(Runtime::kSaveRefsOnly),
693 image_header->GetImageMethod(ImageHeader::kSaveRefsOnlyMethod));
694 CHECK_EQ(runtime->GetCalleeSaveMethod(Runtime::kSaveRefsAndArgs),
695 image_header->GetImageMethod(ImageHeader::kSaveRefsAndArgsMethod));
696 CHECK_EQ(runtime->GetCalleeSaveMethod(Runtime::kSaveEverything),
697 image_header->GetImageMethod(ImageHeader::kSaveEverythingMethod));
698 } else if (!runtime->HasResolutionMethod()) {
699 runtime->SetInstructionSet(space->oat_file_non_owned_->GetOatHeader().GetInstructionSet());
700 runtime->SetResolutionMethod(image_header->GetImageMethod(ImageHeader::kResolutionMethod));
701 runtime->SetImtConflictMethod(image_header->GetImageMethod(ImageHeader::kImtConflictMethod));
702 runtime->SetImtUnimplementedMethod(
703 image_header->GetImageMethod(ImageHeader::kImtUnimplementedMethod));
704 runtime->SetCalleeSaveMethod(
705 image_header->GetImageMethod(ImageHeader::kSaveAllCalleeSavesMethod),
706 Runtime::kSaveAllCalleeSaves);
707 runtime->SetCalleeSaveMethod(
708 image_header->GetImageMethod(ImageHeader::kSaveRefsOnlyMethod), Runtime::kSaveRefsOnly);
709 runtime->SetCalleeSaveMethod(
710 image_header->GetImageMethod(ImageHeader::kSaveRefsAndArgsMethod),
711 Runtime::kSaveRefsAndArgs);
712 runtime->SetCalleeSaveMethod(
713 image_header->GetImageMethod(ImageHeader::kSaveEverythingMethod), Runtime::kSaveEverything);
714 }
715
716 VLOG(image) << "ImageSpace::Init exiting " << *space.get();
717 if (VLOG_IS_ON(image)) {
718 logger.Dump(LOG(INFO));
719 }
720 return space;
721 }
722
723 private:
724 static MemMap* LoadImageFile(const char* image_filename,
725 const char* image_location,
726 const ImageHeader& image_header,
727 uint8_t* address,
728 int fd,
729 TimingLogger& logger,
730 std::string* error_msg) {
731 TimingLogger::ScopedTiming timing("MapImageFile", &logger);
732 const ImageHeader::StorageMode storage_mode = image_header.GetStorageMode();
733 if (storage_mode == ImageHeader::kStorageModeUncompressed) {
734 return MemMap::MapFileAtAddress(address,
735 image_header.GetImageSize(),
736 PROT_READ | PROT_WRITE,
737 MAP_PRIVATE,
738 fd,
739 0,
740 /*low_4gb*/true,
741 /*reuse*/false,
742 image_filename,
743 error_msg);
744 }
745
746 if (storage_mode != ImageHeader::kStorageModeLZ4 &&
747 storage_mode != ImageHeader::kStorageModeLZ4HC) {
748 *error_msg = StringPrintf("Invalid storage mode in image header %d",
749 static_cast<int>(storage_mode));
750 return nullptr;
751 }
752
753 // Reserve output and decompress into it.
754 std::unique_ptr<MemMap> map(MemMap::MapAnonymous(image_location,
755 address,
756 image_header.GetImageSize(),
757 PROT_READ | PROT_WRITE,
758 /*low_4gb*/true,
759 /*reuse*/false,
760 error_msg));
761 if (map != nullptr) {
762 const size_t stored_size = image_header.GetDataSize();
763 const size_t decompress_offset = sizeof(ImageHeader); // Skip the header.
764 std::unique_ptr<MemMap> temp_map(MemMap::MapFile(sizeof(ImageHeader) + stored_size,
765 PROT_READ,
766 MAP_PRIVATE,
767 fd,
768 /*offset*/0,
769 /*low_4gb*/false,
770 image_filename,
771 error_msg));
772 if (temp_map == nullptr) {
773 DCHECK(!error_msg->empty());
774 return nullptr;
775 }
776 memcpy(map->Begin(), &image_header, sizeof(ImageHeader));
777 const uint64_t start = NanoTime();
778 // LZ4HC and LZ4 have same internal format, both use LZ4_decompress.
779 TimingLogger::ScopedTiming timing2("LZ4 decompress image", &logger);
780 const size_t decompressed_size = LZ4_decompress_safe(
781 reinterpret_cast<char*>(temp_map->Begin()) + sizeof(ImageHeader),
782 reinterpret_cast<char*>(map->Begin()) + decompress_offset,
783 stored_size,
784 map->Size() - decompress_offset);
785 VLOG(image) << "Decompressing image took " << PrettyDuration(NanoTime() - start);
786 if (decompressed_size + sizeof(ImageHeader) != image_header.GetImageSize()) {
787 *error_msg = StringPrintf(
788 "Decompressed size does not match expected image size %zu vs %zu",
789 decompressed_size + sizeof(ImageHeader),
790 image_header.GetImageSize());
791 return nullptr;
792 }
793 }
794
795 return map.release();
796 }
797
798 class FixupVisitor : public ValueObject {
799 public:
800 FixupVisitor(const RelocationRange& boot_image,
801 const RelocationRange& boot_oat,
802 const RelocationRange& app_image,
803 const RelocationRange& app_oat)
804 : boot_image_(boot_image),
805 boot_oat_(boot_oat),
806 app_image_(app_image),
807 app_oat_(app_oat) {}
808
809 // Return the relocated address of a heap object.
810 template <typename T>
811 ALWAYS_INLINE T* ForwardObject(T* src) const {
812 const uintptr_t uint_src = reinterpret_cast<uintptr_t>(src);
813 if (boot_image_.InSource(uint_src)) {
814 return reinterpret_cast<T*>(boot_image_.ToDest(uint_src));
815 }
816 if (app_image_.InSource(uint_src)) {
817 return reinterpret_cast<T*>(app_image_.ToDest(uint_src));
818 }
819 // Since we are fixing up the app image, there should only be pointers to the app image and
820 // boot image.
821 DCHECK(src == nullptr) << reinterpret_cast<const void*>(src);
822 return src;
823 }
824
825 // Return the relocated address of a code pointer (contained by an oat file).
826 ALWAYS_INLINE const void* ForwardCode(const void* src) const {
827 const uintptr_t uint_src = reinterpret_cast<uintptr_t>(src);
828 if (boot_oat_.InSource(uint_src)) {
829 return reinterpret_cast<const void*>(boot_oat_.ToDest(uint_src));
830 }
831 if (app_oat_.InSource(uint_src)) {
832 return reinterpret_cast<const void*>(app_oat_.ToDest(uint_src));
833 }
834 DCHECK(src == nullptr) << src;
835 return src;
836 }
837
838 // Must be called on pointers that already have been relocated to the destination relocation.
839 ALWAYS_INLINE bool IsInAppImage(mirror::Object* object) const {
840 return app_image_.InDest(reinterpret_cast<uintptr_t>(object));
841 }
842
843 protected:
844 // Source section.
845 const RelocationRange boot_image_;
846 const RelocationRange boot_oat_;
847 const RelocationRange app_image_;
848 const RelocationRange app_oat_;
849 };
850
851 // Adapt for mirror::Class::FixupNativePointers.
852 class FixupObjectAdapter : public FixupVisitor {
853 public:
854 template<typename... Args>
855 explicit FixupObjectAdapter(Args... args) : FixupVisitor(args...) {}
856
857 template <typename T>
858 T* operator()(T* obj) const {
859 return ForwardObject(obj);
860 }
861 };
862
863 class FixupRootVisitor : public FixupVisitor {
864 public:
865 template<typename... Args>
866 explicit FixupRootVisitor(Args... args) : FixupVisitor(args...) {}
867
868 ALWAYS_INLINE void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
869 SHARED_REQUIRES(Locks::mutator_lock_) {
870 if (!root->IsNull()) {
871 VisitRoot(root);
872 }
873 }
874
875 ALWAYS_INLINE void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
876 SHARED_REQUIRES(Locks::mutator_lock_) {
877 mirror::Object* ref = root->AsMirrorPtr();
878 mirror::Object* new_ref = ForwardObject(ref);
879 if (ref != new_ref) {
880 root->Assign(new_ref);
881 }
882 }
883 };
884
885 class FixupObjectVisitor : public FixupVisitor {
886 public:
887 template<typename... Args>
888 explicit FixupObjectVisitor(gc::accounting::ContinuousSpaceBitmap* visited,
889 const PointerSize pointer_size,
890 Args... args)
891 : FixupVisitor(args...),
892 pointer_size_(pointer_size),
893 visited_(visited) {}
894
895 // Fix up separately since we also need to fix up method entrypoints.
896 ALWAYS_INLINE void VisitRootIfNonNull(
897 mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const {}
898
899 ALWAYS_INLINE void VisitRoot(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED)
900 const {}
901
902 ALWAYS_INLINE void operator()(mirror::Object* obj,
903 MemberOffset offset,
904 bool is_static ATTRIBUTE_UNUSED) const
905 NO_THREAD_SAFETY_ANALYSIS {
906 // There could be overlap between ranges, we must avoid visiting the same reference twice.
907 // Avoid the class field since we already fixed it up in FixupClassVisitor.
908 if (offset.Uint32Value() != mirror::Object::ClassOffset().Uint32Value()) {
909 // Space is not yet added to the heap, don't do a read barrier.
910 mirror::Object* ref = obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(
911 offset);
912 // Use SetFieldObjectWithoutWriteBarrier to avoid card marking since we are writing to the
913 // image.
914 obj->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(offset, ForwardObject(ref));
915 }
916 }
917
918 // Visit a pointer array and forward corresponding native data. Ignores pointer arrays in the
919 // boot image. Uses the bitmap to ensure the same array is not visited multiple times.
920 template <typename Visitor>
921 void UpdatePointerArrayContents(mirror::PointerArray* array, const Visitor& visitor) const
922 NO_THREAD_SAFETY_ANALYSIS {
923 DCHECK(array != nullptr);
924 DCHECK(visitor.IsInAppImage(array));
925 // The bit for the array contents is different than the bit for the array. Since we may have
926 // already visited the array as a long / int array from walking the bitmap without knowing it
927 // was a pointer array.
928 static_assert(kObjectAlignment == 8u, "array bit may be in another object");
929 mirror::Object* const contents_bit = reinterpret_cast<mirror::Object*>(
930 reinterpret_cast<uintptr_t>(array) + kObjectAlignment);
931 // If the bit is not set then the contents have not yet been updated.
932 if (!visited_->Test(contents_bit)) {
933 array->Fixup<kVerifyNone, kWithoutReadBarrier>(array, pointer_size_, visitor);
934 visited_->Set(contents_bit);
935 }
936 }
937
938 // java.lang.ref.Reference visitor.
939 void operator()(mirror::Class* klass ATTRIBUTE_UNUSED, mirror::Reference* ref) const
940 SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
941 mirror::Object* obj = ref->GetReferent<kWithoutReadBarrier>();
942 ref->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
943 mirror::Reference::ReferentOffset(),
944 ForwardObject(obj));
945 }
946
947 void operator()(mirror::Object* obj) const NO_THREAD_SAFETY_ANALYSIS {
948 if (visited_->Test(obj)) {
949 // Already visited.
950 return;
951 }
952 visited_->Set(obj);
953
954 // Handle class specially first since we need it to be updated to properly visit the rest of
955 // the instance fields.
956 {
957 mirror::Class* klass = obj->GetClass<kVerifyNone, kWithoutReadBarrier>();
958 DCHECK(klass != nullptr) << "Null class in image";
959 // No AsClass since our fields aren't quite fixed up yet.
960 mirror::Class* new_klass = down_cast<mirror::Class*>(ForwardObject(klass));
961 if (klass != new_klass) {
962 obj->SetClass<kVerifyNone>(new_klass);
963 }
964 if (new_klass != klass && IsInAppImage(new_klass)) {
965 // Make sure the klass contents are fixed up since we depend on it to walk the fields.
966 operator()(new_klass);
967 }
968 }
969
970 obj->VisitReferences</*visit native roots*/false, kVerifyNone, kWithoutReadBarrier>(
971 *this,
972 *this);
973 // Note that this code relies on no circular dependencies.
974 // We want to use our own class loader and not the one in the image.
975 if (obj->IsClass<kVerifyNone, kWithoutReadBarrier>()) {
976 mirror::Class* as_klass = obj->AsClass<kVerifyNone, kWithoutReadBarrier>();
977 FixupObjectAdapter visitor(boot_image_, boot_oat_, app_image_, app_oat_);
978 as_klass->FixupNativePointers<kVerifyNone, kWithoutReadBarrier>(as_klass,
979 pointer_size_,
980 visitor);
981 // Deal with the pointer arrays. Use the helper function since multiple classes can reference
982 // the same arrays.
983 mirror::PointerArray* const vtable = as_klass->GetVTable<kVerifyNone, kWithoutReadBarrier>();
984 if (vtable != nullptr && IsInAppImage(vtable)) {
985 operator()(vtable);
986 UpdatePointerArrayContents(vtable, visitor);
987 }
988 mirror::IfTable* iftable = as_klass->GetIfTable<kVerifyNone, kWithoutReadBarrier>();
989 // Ensure iftable arrays are fixed up since we need GetMethodArray to return the valid
990 // contents.
991 if (iftable != nullptr && IsInAppImage(iftable)) {
992 operator()(iftable);
993 for (int32_t i = 0, count = iftable->Count(); i < count; ++i) {
994 if (iftable->GetMethodArrayCount<kVerifyNone, kWithoutReadBarrier>(i) > 0) {
995 mirror::PointerArray* methods =
996 iftable->GetMethodArray<kVerifyNone, kWithoutReadBarrier>(i);
997 if (visitor.IsInAppImage(methods)) {
998 operator()(methods);
999 DCHECK(methods != nullptr);
1000 UpdatePointerArrayContents(methods, visitor);
1001 }
Mathieu Chartier92ec5942016-04-11 12:03:48 -07001002 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001003 }
1004 }
1005 }
1006 }
Mathieu Chartier91edc622016-02-16 17:16:01 -08001007
Andreas Gampea463b6a2016-08-12 21:53:32 -07001008 private:
1009 const PointerSize pointer_size_;
1010 gc::accounting::ContinuousSpaceBitmap* const visited_;
1011 };
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001012
Andreas Gampea463b6a2016-08-12 21:53:32 -07001013 class ForwardObjectAdapter {
1014 public:
1015 ALWAYS_INLINE explicit ForwardObjectAdapter(const FixupVisitor* visitor) : visitor_(visitor) {}
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001016
Andreas Gampea463b6a2016-08-12 21:53:32 -07001017 template <typename T>
1018 ALWAYS_INLINE T* operator()(T* src) const {
1019 return visitor_->ForwardObject(src);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001020 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001021
Andreas Gampea463b6a2016-08-12 21:53:32 -07001022 private:
1023 const FixupVisitor* const visitor_;
1024 };
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001025
Andreas Gampea463b6a2016-08-12 21:53:32 -07001026 class ForwardCodeAdapter {
1027 public:
1028 ALWAYS_INLINE explicit ForwardCodeAdapter(const FixupVisitor* visitor)
1029 : 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_->ForwardCode(src);
1034 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001035
Andreas Gampea463b6a2016-08-12 21:53:32 -07001036 private:
1037 const FixupVisitor* const visitor_;
1038 };
1039
1040 class FixupArtMethodVisitor : public FixupVisitor, public ArtMethodVisitor {
1041 public:
1042 template<typename... Args>
1043 explicit FixupArtMethodVisitor(bool fixup_heap_objects, PointerSize pointer_size, Args... args)
1044 : FixupVisitor(args...),
1045 fixup_heap_objects_(fixup_heap_objects),
1046 pointer_size_(pointer_size) {}
1047
1048 virtual void Visit(ArtMethod* method) NO_THREAD_SAFETY_ANALYSIS {
1049 // TODO: Separate visitor for runtime vs normal methods.
1050 if (UNLIKELY(method->IsRuntimeMethod())) {
1051 ImtConflictTable* table = method->GetImtConflictTable(pointer_size_);
1052 if (table != nullptr) {
1053 ImtConflictTable* new_table = ForwardObject(table);
1054 if (table != new_table) {
1055 method->SetImtConflictTable(new_table, pointer_size_);
1056 }
1057 }
1058 const void* old_code = method->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size_);
1059 const void* new_code = ForwardCode(old_code);
1060 if (old_code != new_code) {
1061 method->SetEntryPointFromQuickCompiledCodePtrSize(new_code, pointer_size_);
1062 }
1063 } else {
1064 if (fixup_heap_objects_) {
1065 method->UpdateObjectsForImageRelocation(ForwardObjectAdapter(this), pointer_size_);
1066 }
1067 method->UpdateEntrypoints<kWithoutReadBarrier>(ForwardCodeAdapter(this), pointer_size_);
1068 }
1069 }
1070
1071 private:
1072 const bool fixup_heap_objects_;
1073 const PointerSize pointer_size_;
1074 };
1075
1076 class FixupArtFieldVisitor : public FixupVisitor, public ArtFieldVisitor {
1077 public:
1078 template<typename... Args>
1079 explicit FixupArtFieldVisitor(Args... args) : FixupVisitor(args...) {}
1080
1081 virtual void Visit(ArtField* field) NO_THREAD_SAFETY_ANALYSIS {
1082 field->UpdateObjects(ForwardObjectAdapter(this));
1083 }
1084 };
1085
1086 // Relocate an image space mapped at target_base which possibly used to be at a different base
1087 // address. Only needs a single image space, not one for both source and destination.
1088 // In place means modifying a single ImageSpace in place rather than relocating from one ImageSpace
1089 // to another.
1090 static bool RelocateInPlace(ImageHeader& image_header,
1091 uint8_t* target_base,
1092 accounting::ContinuousSpaceBitmap* bitmap,
1093 const OatFile* app_oat_file,
1094 std::string* error_msg) {
1095 DCHECK(error_msg != nullptr);
1096 if (!image_header.IsPic()) {
1097 if (image_header.GetImageBegin() == target_base) {
1098 return true;
1099 }
1100 *error_msg = StringPrintf("Cannot relocate non-pic image for oat file %s",
1101 (app_oat_file != nullptr) ? app_oat_file->GetLocation().c_str() : "");
1102 return false;
1103 }
1104 // Set up sections.
1105 uint32_t boot_image_begin = 0;
1106 uint32_t boot_image_end = 0;
1107 uint32_t boot_oat_begin = 0;
1108 uint32_t boot_oat_end = 0;
1109 const PointerSize pointer_size = image_header.GetPointerSize();
1110 gc::Heap* const heap = Runtime::Current()->GetHeap();
1111 heap->GetBootImagesSize(&boot_image_begin, &boot_image_end, &boot_oat_begin, &boot_oat_end);
1112 if (boot_image_begin == boot_image_end) {
1113 *error_msg = "Can not relocate app image without boot image space";
1114 return false;
1115 }
1116 if (boot_oat_begin == boot_oat_end) {
1117 *error_msg = "Can not relocate app image without boot oat file";
1118 return false;
1119 }
1120 const uint32_t boot_image_size = boot_image_end - boot_image_begin;
1121 const uint32_t boot_oat_size = boot_oat_end - boot_oat_begin;
1122 const uint32_t image_header_boot_image_size = image_header.GetBootImageSize();
1123 const uint32_t image_header_boot_oat_size = image_header.GetBootOatSize();
1124 if (boot_image_size != image_header_boot_image_size) {
1125 *error_msg = StringPrintf("Boot image size %" PRIu64 " does not match expected size %"
1126 PRIu64,
1127 static_cast<uint64_t>(boot_image_size),
1128 static_cast<uint64_t>(image_header_boot_image_size));
1129 return false;
1130 }
1131 if (boot_oat_size != image_header_boot_oat_size) {
1132 *error_msg = StringPrintf("Boot oat size %" PRIu64 " does not match expected size %"
1133 PRIu64,
1134 static_cast<uint64_t>(boot_oat_size),
1135 static_cast<uint64_t>(image_header_boot_oat_size));
1136 return false;
1137 }
1138 TimingLogger logger(__FUNCTION__, true, false);
1139 RelocationRange boot_image(image_header.GetBootImageBegin(),
1140 boot_image_begin,
1141 boot_image_size);
1142 RelocationRange boot_oat(image_header.GetBootOatBegin(),
1143 boot_oat_begin,
1144 boot_oat_size);
1145 RelocationRange app_image(reinterpret_cast<uintptr_t>(image_header.GetImageBegin()),
1146 reinterpret_cast<uintptr_t>(target_base),
1147 image_header.GetImageSize());
1148 // Use the oat data section since this is where the OatFile::Begin is.
1149 RelocationRange app_oat(reinterpret_cast<uintptr_t>(image_header.GetOatDataBegin()),
1150 // Not necessarily in low 4GB.
1151 reinterpret_cast<uintptr_t>(app_oat_file->Begin()),
1152 image_header.GetOatDataEnd() - image_header.GetOatDataBegin());
1153 VLOG(image) << "App image " << app_image;
1154 VLOG(image) << "App oat " << app_oat;
1155 VLOG(image) << "Boot image " << boot_image;
1156 VLOG(image) << "Boot oat " << boot_oat;
1157 // True if we need to fixup any heap pointers, otherwise only code pointers.
1158 const bool fixup_image = boot_image.Delta() != 0 || app_image.Delta() != 0;
1159 const bool fixup_code = boot_oat.Delta() != 0 || app_oat.Delta() != 0;
1160 if (!fixup_image && !fixup_code) {
1161 // Nothing to fix up.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001162 return true;
1163 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07001164 ScopedDebugDisallowReadBarriers sddrb(Thread::Current());
1165 // Need to update the image to be at the target base.
1166 const ImageSection& objects_section = image_header.GetImageSection(ImageHeader::kSectionObjects);
1167 uintptr_t objects_begin = reinterpret_cast<uintptr_t>(target_base + objects_section.Offset());
1168 uintptr_t objects_end = reinterpret_cast<uintptr_t>(target_base + objects_section.End());
1169 FixupObjectAdapter fixup_adapter(boot_image, boot_oat, app_image, app_oat);
1170 if (fixup_image) {
1171 // Two pass approach, fix up all classes first, then fix up non class-objects.
1172 // The visited bitmap is used to ensure that pointer arrays are not forwarded twice.
1173 std::unique_ptr<gc::accounting::ContinuousSpaceBitmap> visited_bitmap(
1174 gc::accounting::ContinuousSpaceBitmap::Create("Relocate bitmap",
1175 target_base,
1176 image_header.GetImageSize()));
1177 FixupObjectVisitor fixup_object_visitor(visited_bitmap.get(),
1178 pointer_size,
1179 boot_image,
1180 boot_oat,
1181 app_image,
1182 app_oat);
1183 TimingLogger::ScopedTiming timing("Fixup classes", &logger);
1184 // Fixup objects may read fields in the boot image, use the mutator lock here for sanity. Though
1185 // its probably not required.
1186 ScopedObjectAccess soa(Thread::Current());
1187 timing.NewTiming("Fixup objects");
1188 bitmap->VisitMarkedRange(objects_begin, objects_end, fixup_object_visitor);
1189 // Fixup image roots.
1190 CHECK(app_image.InSource(reinterpret_cast<uintptr_t>(
1191 image_header.GetImageRoots<kWithoutReadBarrier>())));
1192 image_header.RelocateImageObjects(app_image.Delta());
1193 CHECK_EQ(image_header.GetImageBegin(), target_base);
1194 // Fix up dex cache DexFile pointers.
1195 auto* dex_caches = image_header.GetImageRoot<kWithoutReadBarrier>(ImageHeader::kDexCaches)->
1196 AsObjectArray<mirror::DexCache, kVerifyNone, kWithoutReadBarrier>();
1197 for (int32_t i = 0, count = dex_caches->GetLength(); i < count; ++i) {
1198 mirror::DexCache* dex_cache = dex_caches->Get<kVerifyNone, kWithoutReadBarrier>(i);
1199 // Fix up dex cache pointers.
1200 GcRoot<mirror::String>* strings = dex_cache->GetStrings();
1201 if (strings != nullptr) {
1202 GcRoot<mirror::String>* new_strings = fixup_adapter.ForwardObject(strings);
1203 if (strings != new_strings) {
1204 dex_cache->SetStrings(new_strings);
1205 }
1206 dex_cache->FixupStrings<kWithoutReadBarrier>(new_strings, fixup_adapter);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001207 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07001208 GcRoot<mirror::Class>* types = dex_cache->GetResolvedTypes();
1209 if (types != nullptr) {
1210 GcRoot<mirror::Class>* new_types = fixup_adapter.ForwardObject(types);
1211 if (types != new_types) {
1212 dex_cache->SetResolvedTypes(new_types);
1213 }
1214 dex_cache->FixupResolvedTypes<kWithoutReadBarrier>(new_types, fixup_adapter);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001215 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07001216 ArtMethod** methods = dex_cache->GetResolvedMethods();
1217 if (methods != nullptr) {
1218 ArtMethod** new_methods = fixup_adapter.ForwardObject(methods);
1219 if (methods != new_methods) {
1220 dex_cache->SetResolvedMethods(new_methods);
1221 }
1222 for (size_t j = 0, num = dex_cache->NumResolvedMethods(); j != num; ++j) {
1223 ArtMethod* orig = mirror::DexCache::GetElementPtrSize(new_methods, j, pointer_size);
1224 ArtMethod* copy = fixup_adapter.ForwardObject(orig);
1225 if (orig != copy) {
1226 mirror::DexCache::SetElementPtrSize(new_methods, j, copy, pointer_size);
1227 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001228 }
1229 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07001230 ArtField** fields = dex_cache->GetResolvedFields();
1231 if (fields != nullptr) {
1232 ArtField** new_fields = fixup_adapter.ForwardObject(fields);
1233 if (fields != new_fields) {
1234 dex_cache->SetResolvedFields(new_fields);
1235 }
1236 for (size_t j = 0, num = dex_cache->NumResolvedFields(); j != num; ++j) {
1237 ArtField* orig = mirror::DexCache::GetElementPtrSize(new_fields, j, pointer_size);
1238 ArtField* copy = fixup_adapter.ForwardObject(orig);
1239 if (orig != copy) {
1240 mirror::DexCache::SetElementPtrSize(new_fields, j, copy, pointer_size);
1241 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001242 }
1243 }
1244 }
1245 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001246 {
1247 // Only touches objects in the app image, no need for mutator lock.
Andreas Gampea463b6a2016-08-12 21:53:32 -07001248 TimingLogger::ScopedTiming timing("Fixup methods", &logger);
1249 FixupArtMethodVisitor method_visitor(fixup_image,
1250 pointer_size,
1251 boot_image,
1252 boot_oat,
1253 app_image,
1254 app_oat);
1255 image_header.VisitPackedArtMethods(&method_visitor, target_base, pointer_size);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001256 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07001257 if (fixup_image) {
1258 {
1259 // Only touches objects in the app image, no need for mutator lock.
1260 TimingLogger::ScopedTiming timing("Fixup fields", &logger);
1261 FixupArtFieldVisitor field_visitor(boot_image, boot_oat, app_image, app_oat);
1262 image_header.VisitPackedArtFields(&field_visitor, target_base);
1263 }
1264 {
1265 TimingLogger::ScopedTiming timing("Fixup imt", &logger);
1266 image_header.VisitPackedImTables(fixup_adapter, target_base, pointer_size);
1267 }
1268 {
1269 TimingLogger::ScopedTiming timing("Fixup conflict tables", &logger);
1270 image_header.VisitPackedImtConflictTables(fixup_adapter, target_base, pointer_size);
1271 }
1272 // In the app image case, the image methods are actually in the boot image.
1273 image_header.RelocateImageMethods(boot_image.Delta());
1274 const auto& class_table_section = image_header.GetImageSection(ImageHeader::kSectionClassTable);
1275 if (class_table_section.Size() > 0u) {
1276 // Note that we require that ReadFromMemory does not make an internal copy of the elements.
1277 // This also relies on visit roots not doing any verification which could fail after we update
1278 // the roots to be the image addresses.
1279 ScopedObjectAccess soa(Thread::Current());
1280 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
1281 ClassTable temp_table;
1282 temp_table.ReadFromMemory(target_base + class_table_section.Offset());
1283 FixupRootVisitor root_visitor(boot_image, boot_oat, app_image, app_oat);
1284 temp_table.VisitRoots(root_visitor);
1285 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001286 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07001287 if (VLOG_IS_ON(image)) {
1288 logger.Dump(LOG(INFO));
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001289 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07001290 return true;
Andreas Gampe7fa55782016-06-15 17:45:01 -07001291 }
1292
Andreas Gampea463b6a2016-08-12 21:53:32 -07001293 static std::unique_ptr<OatFile> OpenOatFile(const ImageSpace& image,
1294 const char* image_path,
1295 std::string* error_msg) {
1296 const ImageHeader& image_header = image.GetImageHeader();
1297 std::string oat_filename = ImageHeader::GetOatLocationFromImageLocation(image_path);
Andreas Gampe7fa55782016-06-15 17:45:01 -07001298
Andreas Gampea463b6a2016-08-12 21:53:32 -07001299 CHECK(image_header.GetOatDataBegin() != nullptr);
1300
1301 std::unique_ptr<OatFile> oat_file(OatFile::Open(oat_filename,
1302 oat_filename,
1303 image_header.GetOatDataBegin(),
1304 image_header.GetOatFileBegin(),
1305 !Runtime::Current()->IsAotCompiler(),
1306 /*low_4gb*/false,
1307 nullptr,
1308 error_msg));
1309 if (oat_file == nullptr) {
1310 *error_msg = StringPrintf("Failed to open oat file '%s' referenced from image %s: %s",
1311 oat_filename.c_str(),
1312 image.GetName(),
1313 error_msg->c_str());
Andreas Gampe7fa55782016-06-15 17:45:01 -07001314 return nullptr;
1315 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07001316 uint32_t oat_checksum = oat_file->GetOatHeader().GetChecksum();
1317 uint32_t image_oat_checksum = image_header.GetOatChecksum();
Mathieu Chartier9ff84602016-01-29 12:22:17 -08001318 if (oat_checksum != image_oat_checksum) {
Andreas Gampea463b6a2016-08-12 21:53:32 -07001319 *error_msg = StringPrintf("Failed to match oat file checksum 0x%x to expected oat checksum 0x%x"
1320 " in image %s",
Mathieu Chartier9ff84602016-01-29 12:22:17 -08001321 oat_checksum,
1322 image_oat_checksum,
Andreas Gampea463b6a2016-08-12 21:53:32 -07001323 image.GetName());
Mathieu Chartier9ff84602016-01-29 12:22:17 -08001324 return nullptr;
1325 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07001326 int32_t image_patch_delta = image_header.GetPatchDelta();
1327 int32_t oat_patch_delta = oat_file->GetOatHeader().GetImagePatchDelta();
1328 if (oat_patch_delta != image_patch_delta && !image_header.CompilePic()) {
1329 // We should have already relocated by this point. Bail out.
1330 *error_msg = StringPrintf("Failed to match oat file patch delta %d to expected patch delta %d "
1331 "in image %s",
1332 oat_patch_delta,
1333 image_patch_delta,
1334 image.GetName());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001335 return nullptr;
1336 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07001337
1338 return oat_file;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001339 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07001340
1341 static bool ValidateOatFile(const ImageSpace& space,
1342 const OatFile& oat_file,
1343 std::string* error_msg) {
1344 for (const OatFile::OatDexFile* oat_dex_file : oat_file.GetOatDexFiles()) {
1345 const std::string& dex_file_location = oat_dex_file->GetDexFileLocation();
1346 uint32_t dex_file_location_checksum;
1347 if (!DexFile::GetChecksum(dex_file_location.c_str(), &dex_file_location_checksum, error_msg)) {
1348 *error_msg = StringPrintf("Failed to get checksum of dex file '%s' referenced by image %s: "
1349 "%s",
1350 dex_file_location.c_str(),
1351 space.GetName(),
1352 error_msg->c_str());
1353 return false;
1354 }
1355 if (dex_file_location_checksum != oat_dex_file->GetDexFileLocationChecksum()) {
1356 *error_msg = StringPrintf("ValidateOatFile found checksum mismatch between oat file '%s' and "
1357 "dex file '%s' (0x%x != 0x%x)",
1358 oat_file.GetLocation().c_str(),
1359 dex_file_location.c_str(),
1360 oat_dex_file->GetDexFileLocationChecksum(),
1361 dex_file_location_checksum);
1362 return false;
1363 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001364 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07001365 return true;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001366 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07001367};
Hiroshi Yamauchibd0fb612014-05-20 13:46:00 -07001368
Andreas Gampea463b6a2016-08-12 21:53:32 -07001369static constexpr uint64_t kLowSpaceValue = 50 * MB;
1370static constexpr uint64_t kTmpFsSentinelValue = 384 * MB;
1371
1372// Read the free space of the cache partition and make a decision whether to keep the generated
1373// image. This is to try to mitigate situations where the system might run out of space later.
1374static bool CheckSpace(const std::string& cache_filename, std::string* error_msg) {
1375 // Using statvfs vs statvfs64 because of b/18207376, and it is enough for all practical purposes.
1376 struct statvfs buf;
1377
1378 int res = TEMP_FAILURE_RETRY(statvfs(cache_filename.c_str(), &buf));
1379 if (res != 0) {
1380 // Could not stat. Conservatively tell the system to delete the image.
1381 *error_msg = "Could not stat the filesystem, assuming low-memory situation.";
1382 return false;
Nicolas Geoffray1bc977c2016-01-23 14:15:49 +00001383 }
Nicolas Geoffray1bc977c2016-01-23 14:15:49 +00001384
Andreas Gampea463b6a2016-08-12 21:53:32 -07001385 uint64_t fs_overall_size = buf.f_bsize * static_cast<uint64_t>(buf.f_blocks);
1386 // Zygote is privileged, but other things are not. Use bavail.
1387 uint64_t fs_free_size = buf.f_bsize * static_cast<uint64_t>(buf.f_bavail);
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001388
Andreas Gampea463b6a2016-08-12 21:53:32 -07001389 // Take the overall size as an indicator for a tmpfs, which is being used for the decryption
1390 // environment. We do not want to fail quickening the boot image there, as it is beneficial
1391 // for time-to-UI.
1392 if (fs_overall_size > kTmpFsSentinelValue) {
1393 if (fs_free_size < kLowSpaceValue) {
1394 *error_msg = StringPrintf("Low-memory situation: only %4.2f megabytes available, need at "
1395 "least %" PRIu64 ".",
1396 static_cast<double>(fs_free_size) / MB,
1397 kLowSpaceValue / MB);
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001398 return false;
1399 }
1400 }
1401 return true;
1402}
1403
Andreas Gampea463b6a2016-08-12 21:53:32 -07001404std::unique_ptr<ImageSpace> ImageSpace::CreateBootImage(const char* image_location,
1405 const InstructionSet image_isa,
1406 bool secondary_image,
1407 std::string* error_msg) {
1408 ScopedTrace trace(__FUNCTION__);
1409
1410 // Step 0: Extra zygote work.
1411
1412 // Step 0.a: If we're the zygote, mark boot.
1413 const bool is_zygote = Runtime::Current()->IsZygote();
1414 if (is_zygote && !secondary_image) {
1415 MarkZygoteStart(image_isa, Runtime::Current()->GetZygoteMaxFailedBoots());
1416 }
1417
1418 // Step 0.b: If we're the zygote, check for free space, and prune the cache preemptively,
1419 // if necessary. While the runtime may be fine (it is pretty tolerant to
1420 // out-of-disk-space situations), other parts of the platform are not.
1421 //
1422 // The advantage of doing this proactively is that the later steps are simplified,
1423 // i.e., we do not need to code retries.
1424 std::string system_filename;
1425 bool has_system = false;
1426 std::string cache_filename;
1427 bool has_cache = false;
1428 bool dalvik_cache_exists = false;
1429 bool is_global_cache = true;
1430 std::string dalvik_cache;
1431 bool found_image = FindImageFilenameImpl(image_location,
1432 image_isa,
1433 &has_system,
1434 &system_filename,
1435 &dalvik_cache_exists,
1436 &dalvik_cache,
1437 &is_global_cache,
1438 &has_cache,
1439 &cache_filename);
1440
1441 if (is_zygote && dalvik_cache_exists) {
1442 DCHECK(!dalvik_cache.empty());
1443 std::string local_error_msg;
1444 if (!CheckSpace(dalvik_cache, &local_error_msg)) {
1445 LOG(WARNING) << local_error_msg << " Preemptively pruning the dalvik cache.";
1446 PruneDalvikCache(image_isa);
1447
1448 // Re-evaluate the image.
1449 found_image = FindImageFilenameImpl(image_location,
1450 image_isa,
1451 &has_system,
1452 &system_filename,
1453 &dalvik_cache_exists,
1454 &dalvik_cache,
1455 &is_global_cache,
1456 &has_cache,
1457 &cache_filename);
1458 }
1459 }
1460
1461 // Collect all the errors.
1462 std::vector<std::string> error_msgs;
1463
1464 // Step 1: Check if we have an existing and relocated image.
1465
1466 // Step 1.a: Have files in system and cache. Then they need to match.
1467 if (found_image && has_system && has_cache) {
1468 std::string local_error_msg;
1469 // Check that the files are matching.
1470 if (ChecksumsMatch(system_filename.c_str(), cache_filename.c_str(), &local_error_msg)) {
1471 std::unique_ptr<ImageSpace> relocated_space =
1472 ImageSpaceLoader::Load(image_location,
1473 cache_filename,
1474 is_zygote,
1475 is_global_cache,
1476 /* is_system */ false,
1477 /* relocated_version_used */ true,
1478 &local_error_msg);
1479 if (relocated_space != nullptr) {
1480 return relocated_space;
1481 }
1482 }
1483 error_msgs.push_back(local_error_msg);
1484 }
1485
1486 // Step 1.b: Only have a cache file.
1487 if (found_image && !has_system && has_cache) {
1488 std::string local_error_msg;
1489 std::unique_ptr<ImageSpace> cache_space =
1490 ImageSpaceLoader::Load(image_location,
1491 cache_filename,
1492 is_zygote,
1493 is_global_cache,
1494 /* is_system */ false,
1495 /* relocated_version_used */ true,
1496 &local_error_msg);
1497 if (cache_space != nullptr) {
1498 return cache_space;
1499 }
1500 error_msgs.push_back(local_error_msg);
1501 }
1502
1503 // Step 2: We have an existing image in /system.
1504
1505 // Step 2.a: We are not required to relocate it. Then we can use it directly.
1506 bool relocate = Runtime::Current()->ShouldRelocate();
1507
1508 if (found_image && has_system && !relocate) {
1509 std::string local_error_msg;
1510 std::unique_ptr<ImageSpace> system_space =
1511 ImageSpaceLoader::Load(image_location,
1512 system_filename,
1513 is_zygote,
1514 is_global_cache,
1515 /* is_system */ true,
1516 /* relocated_version_used */ false,
1517 &local_error_msg);
1518 if (system_space != nullptr) {
1519 return system_space;
1520 }
1521 error_msgs.push_back(local_error_msg);
1522 }
1523
1524 // Step 2.b: We require a relocated image. Then we must patch it. This step fails if this is a
1525 // secondary image.
1526 if (found_image && has_system && relocate) {
1527 std::string local_error_msg;
1528 if (!Runtime::Current()->IsImageDex2OatEnabled()) {
1529 local_error_msg = "Patching disabled.";
1530 } else if (secondary_image) {
1531 local_error_msg = "Cannot patch a secondary image.";
1532 } else if (ImageCreationAllowed(is_global_cache, &local_error_msg)) {
1533 bool patch_success =
1534 RelocateImage(image_location, cache_filename.c_str(), image_isa, &local_error_msg);
1535 if (patch_success) {
1536 std::unique_ptr<ImageSpace> patched_space =
1537 ImageSpaceLoader::Load(image_location,
1538 cache_filename,
1539 is_zygote,
1540 is_global_cache,
1541 /* is_system */ false,
1542 /* relocated_version_used */ true,
1543 &local_error_msg);
1544 if (patched_space != nullptr) {
1545 return patched_space;
1546 }
1547 }
1548 }
1549 error_msgs.push_back(StringPrintf("Cannot relocate image %s to %s: %s",
1550 image_location,
1551 cache_filename.c_str(),
1552 local_error_msg.c_str()));
1553 }
1554
1555 // Step 3: We do not have an existing image in /system, so generate an image into the dalvik
1556 // cache. This step fails if this is a secondary image.
1557 if (!has_system) {
1558 std::string local_error_msg;
1559 if (!Runtime::Current()->IsImageDex2OatEnabled()) {
1560 local_error_msg = "Image compilation disabled.";
1561 } else if (secondary_image) {
1562 local_error_msg = "Cannot compile a secondary image.";
1563 } else if (ImageCreationAllowed(is_global_cache, &local_error_msg)) {
1564 bool compilation_success = GenerateImage(cache_filename, image_isa, &local_error_msg);
1565 if (compilation_success) {
1566 std::unique_ptr<ImageSpace> compiled_space =
1567 ImageSpaceLoader::Load(image_location,
1568 cache_filename,
1569 is_zygote,
1570 is_global_cache,
1571 /* is_system */ false,
1572 /* relocated_version_used */ true,
1573 &local_error_msg);
1574 if (compiled_space != nullptr) {
1575 return compiled_space;
1576 }
1577 }
1578 }
1579 error_msgs.push_back(StringPrintf("Cannot compile image to %s: %s",
1580 cache_filename.c_str(),
1581 local_error_msg.c_str()));
1582 }
1583
1584 // We failed. Prune the cache the free up space, create a compound error message and return no
1585 // image.
1586 PruneDalvikCache(image_isa);
1587
1588 std::ostringstream oss;
1589 bool first = true;
1590 for (auto msg : error_msgs) {
1591 if (!first) {
1592 oss << "\n ";
1593 }
1594 oss << msg;
1595 }
1596 *error_msg = oss.str();
1597
1598 return nullptr;
1599}
1600
1601std::unique_ptr<ImageSpace> ImageSpace::CreateFromAppImage(const char* image,
1602 const OatFile* oat_file,
1603 std::string* error_msg) {
1604 return ImageSpaceLoader::Init(image,
1605 image,
1606 /*validate_oat_file*/false,
1607 oat_file,
1608 /*out*/error_msg);
1609}
1610
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001611const OatFile* ImageSpace::GetOatFile() const {
Andreas Gampe88da3b02015-06-12 20:38:49 -07001612 return oat_file_non_owned_;
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001613}
1614
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -07001615std::unique_ptr<const OatFile> ImageSpace::ReleaseOatFile() {
1616 CHECK(oat_file_ != nullptr);
1617 return std::move(oat_file_);
Ian Rogers1d54e732013-05-02 21:10:01 -07001618}
1619
Ian Rogers1d54e732013-05-02 21:10:01 -07001620void ImageSpace::Dump(std::ostream& os) const {
1621 os << GetType()
Mathieu Chartier590fee92013-09-13 13:46:47 -07001622 << " begin=" << reinterpret_cast<void*>(Begin())
Ian Rogers1d54e732013-05-02 21:10:01 -07001623 << ",end=" << reinterpret_cast<void*>(End())
1624 << ",size=" << PrettySize(Size())
1625 << ",name=\"" << GetName() << "\"]";
1626}
1627
Andreas Gampe8994a042015-12-30 19:03:17 +00001628void ImageSpace::CreateMultiImageLocations(const std::string& input_image_file_name,
1629 const std::string& boot_classpath,
1630 std::vector<std::string>* image_file_names) {
1631 DCHECK(image_file_names != nullptr);
1632
1633 std::vector<std::string> images;
1634 Split(boot_classpath, ':', &images);
1635
1636 // Add the rest into the list. We have to adjust locations, possibly:
1637 //
1638 // For example, image_file_name is /a/b/c/d/e.art
1639 // images[0] is f/c/d/e.art
1640 // ----------------------------------------------
1641 // images[1] is g/h/i/j.art -> /a/b/h/i/j.art
Mathieu Chartier8b8f6d62016-03-08 16:50:20 -08001642 const std::string& first_image = images[0];
1643 // Length of common suffix.
1644 size_t common = 0;
1645 while (common < input_image_file_name.size() &&
1646 common < first_image.size() &&
1647 *(input_image_file_name.end() - common - 1) == *(first_image.end() - common - 1)) {
1648 ++common;
Andreas Gampe8994a042015-12-30 19:03:17 +00001649 }
Mathieu Chartier8b8f6d62016-03-08 16:50:20 -08001650 // We want to replace the prefix of the input image with the prefix of the boot class path.
1651 // This handles the case where the image file contains @ separators.
1652 // Example image_file_name is oats/system@framework@boot.art
1653 // images[0] is .../arm/boot.art
1654 // means that the image name prefix will be oats/system@framework@
1655 // so that the other images are openable.
1656 const size_t old_prefix_length = first_image.size() - common;
1657 const std::string new_prefix = input_image_file_name.substr(
1658 0,
1659 input_image_file_name.size() - common);
Andreas Gampe8994a042015-12-30 19:03:17 +00001660
1661 // Apply pattern to images[1] .. images[n].
1662 for (size_t i = 1; i < images.size(); ++i) {
Mathieu Chartier8b8f6d62016-03-08 16:50:20 -08001663 const std::string& image = images[i];
1664 CHECK_GT(image.length(), old_prefix_length);
1665 std::string suffix = image.substr(old_prefix_length);
1666 image_file_names->push_back(new_prefix + suffix);
Andreas Gampe8994a042015-12-30 19:03:17 +00001667 }
1668}
1669
Mathieu Chartierd5f3f322016-03-21 14:05:56 -07001670void ImageSpace::DumpSections(std::ostream& os) const {
1671 const uint8_t* base = Begin();
1672 const ImageHeader& header = GetImageHeader();
1673 for (size_t i = 0; i < ImageHeader::kSectionCount; ++i) {
1674 auto section_type = static_cast<ImageHeader::ImageSections>(i);
1675 const ImageSection& section = header.GetImageSection(section_type);
1676 os << section_type << " " << reinterpret_cast<const void*>(base + section.Offset())
1677 << "-" << reinterpret_cast<const void*>(base + section.End()) << "\n";
1678 }
1679}
1680
Ian Rogers1d54e732013-05-02 21:10:01 -07001681} // namespace space
1682} // namespace gc
1683} // namespace art