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