blob: 76f3692f41a1b05fc8c086c800bc9ab4a2f28779 [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
Andreas Gampe9186ced2016-12-12 14:28:21 -080025#include "android-base/strings.h"
26
Mathieu Chartiere401d142015-04-22 13:56:20 -070027#include "art_method.h"
Andreas Gampe542451c2016-07-26 09:02:02 -070028#include "base/enums.h"
Ian Rogersc7dd2952014-10-21 23:31:19 -070029#include "base/macros.h"
Brian Carlstrom56d947f2013-07-15 13:14:23 -070030#include "base/stl_util.h"
Narayan Kamathd1c606f2014-06-09 16:50:19 +010031#include "base/scoped_flock.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080032#include "base/systrace.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010033#include "base/time_utils.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070034#include "gc/accounting/space_bitmap-inl.h"
Mathieu Chartier4a26f172016-01-26 14:26:18 -080035#include "image-inl.h"
Andreas Gampebec63582015-11-20 19:26:51 -080036#include "image_space_fs.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070037#include "mirror/class-inl.h"
38#include "mirror/object-inl.h"
Brian Carlstrom56d947f2013-07-15 13:14:23 -070039#include "oat_file.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070040#include "os.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070041#include "space-inl.h"
42#include "utils.h"
43
44namespace art {
45namespace gc {
46namespace space {
47
Ian Rogersef7d42f2014-01-06 12:55:46 -080048Atomic<uint32_t> ImageSpace::bitmap_index_(0);
Ian Rogers1d54e732013-05-02 21:10:01 -070049
Jeff Haodcdc85b2015-12-04 14:06:18 -080050ImageSpace::ImageSpace(const std::string& image_filename,
51 const char* image_location,
52 MemMap* mem_map,
53 accounting::ContinuousSpaceBitmap* live_bitmap,
Mathieu Chartier2d124ec2016-01-05 18:03:15 -080054 uint8_t* end)
55 : MemMapSpace(image_filename,
56 mem_map,
57 mem_map->Begin(),
58 end,
59 end,
Narayan Kamath52f84882014-05-02 10:10:39 +010060 kGcRetentionPolicyNeverCollect),
Jeff Haodcdc85b2015-12-04 14:06:18 -080061 oat_file_non_owned_(nullptr),
Mathieu Chartier2d124ec2016-01-05 18:03:15 -080062 image_location_(image_location) {
Mathieu Chartier590fee92013-09-13 13:46:47 -070063 DCHECK(live_bitmap != nullptr);
Mathieu Chartier31e89252013-08-28 11:29:12 -070064 live_bitmap_.reset(live_bitmap);
Ian Rogers1d54e732013-05-02 21:10:01 -070065}
66
Alex Lightcf4bf382014-07-24 11:29:14 -070067static int32_t ChooseRelocationOffsetDelta(int32_t min_delta, int32_t max_delta) {
68 CHECK_ALIGNED(min_delta, kPageSize);
69 CHECK_ALIGNED(max_delta, kPageSize);
70 CHECK_LT(min_delta, max_delta);
71
Alex Light15324762015-11-19 11:03:10 -080072 int32_t r = GetRandomNumber<int32_t>(min_delta, max_delta);
Alex Lightcf4bf382014-07-24 11:29:14 -070073 if (r % 2 == 0) {
74 r = RoundUp(r, kPageSize);
75 } else {
76 r = RoundDown(r, kPageSize);
77 }
78 CHECK_LE(min_delta, r);
79 CHECK_GE(max_delta, r);
80 CHECK_ALIGNED(r, kPageSize);
81 return r;
82}
83
Andreas Gampea463b6a2016-08-12 21:53:32 -070084static int32_t ChooseRelocationOffsetDelta() {
85 return ChooseRelocationOffsetDelta(ART_BASE_ADDRESS_MIN_DELTA, ART_BASE_ADDRESS_MAX_DELTA);
86}
87
88static bool GenerateImage(const std::string& image_filename,
89 InstructionSet image_isa,
Alex Light25396132014-08-27 15:37:23 -070090 std::string* error_msg) {
Brian Carlstrom56d947f2013-07-15 13:14:23 -070091 const std::string boot_class_path_string(Runtime::Current()->GetBootClassPathString());
92 std::vector<std::string> boot_class_path;
Ian Rogers6f3dbba2014-10-14 17:41:57 -070093 Split(boot_class_path_string, ':', &boot_class_path);
Brian Carlstrom56d947f2013-07-15 13:14:23 -070094 if (boot_class_path.empty()) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -070095 *error_msg = "Failed to generate image because no boot class path specified";
96 return false;
Brian Carlstrom56d947f2013-07-15 13:14:23 -070097 }
Alex Light25396132014-08-27 15:37:23 -070098 // We should clean up so we are more likely to have room for the image.
99 if (Runtime::Current()->IsZygote()) {
Andreas Gampe3c13a792014-09-18 20:56:04 -0700100 LOG(INFO) << "Pruning dalvik-cache since we are generating an image and will need to recompile";
Narayan Kamath28bc9872014-11-07 17:46:28 +0000101 PruneDalvikCache(image_isa);
Alex Light25396132014-08-27 15:37:23 -0700102 }
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700103
Mathieu Chartier8bbc8c02013-07-31 16:27:01 -0700104 std::vector<std::string> arg_vector;
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700105
Tsu Chiang Chuang12e6d742014-05-22 10:22:25 -0700106 std::string dex2oat(Runtime::Current()->GetCompilerExecutable());
Mathieu Chartier08d7d442013-07-31 18:08:51 -0700107 arg_vector.push_back(dex2oat);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700108
109 std::string image_option_string("--image=");
Narayan Kamath52f84882014-05-02 10:10:39 +0100110 image_option_string += image_filename;
Mathieu Chartier8bbc8c02013-07-31 16:27:01 -0700111 arg_vector.push_back(image_option_string);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700112
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700113 for (size_t i = 0; i < boot_class_path.size(); i++) {
Mathieu Chartier8bbc8c02013-07-31 16:27:01 -0700114 arg_vector.push_back(std::string("--dex-file=") + boot_class_path[i]);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700115 }
116
117 std::string oat_file_option_string("--oat-file=");
Brian Carlstrom2f1e15c2014-10-27 16:27:06 -0700118 oat_file_option_string += ImageHeader::GetOatLocationFromImageLocation(image_filename);
Mathieu Chartier8bbc8c02013-07-31 16:27:01 -0700119 arg_vector.push_back(oat_file_option_string);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700120
Sebastien Hertz0de11332015-05-13 12:14:05 +0200121 // Note: we do not generate a fully debuggable boot image so we do not pass the
122 // compiler flag --debuggable here.
123
Igor Murashkinb1d8c312015-08-04 11:18:43 -0700124 Runtime::Current()->AddCurrentRuntimeFeaturesAsDex2OatArguments(&arg_vector);
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700125 CHECK_EQ(image_isa, kRuntimeISA)
126 << "We should always be generating an image for the current isa.";
Ian Rogers8afeb852014-04-02 14:55:49 -0700127
Andreas Gampea463b6a2016-08-12 21:53:32 -0700128 int32_t base_offset = ChooseRelocationOffsetDelta();
Alex Lightcf4bf382014-07-24 11:29:14 -0700129 LOG(INFO) << "Using an offset of 0x" << std::hex << base_offset << " from default "
130 << "art base address of 0x" << std::hex << ART_BASE_ADDRESS;
131 arg_vector.push_back(StringPrintf("--base=0x%x", ART_BASE_ADDRESS + base_offset));
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700132
Brian Carlstrom57309db2014-07-30 15:13:25 -0700133 if (!kIsTargetBuild) {
Mathieu Chartier8bbc8c02013-07-31 16:27:01 -0700134 arg_vector.push_back("--host");
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700135 }
136
Brian Carlstrom6449c622014-02-10 23:48:36 -0800137 const std::vector<std::string>& compiler_options = Runtime::Current()->GetImageCompilerOptions();
Brian Carlstrom2ec65202014-03-03 15:16:37 -0800138 for (size_t i = 0; i < compiler_options.size(); ++i) {
Brian Carlstrom6449c622014-02-10 23:48:36 -0800139 arg_vector.push_back(compiler_options[i].c_str());
140 }
141
Andreas Gampe9186ced2016-12-12 14:28:21 -0800142 std::string command_line(android::base::Join(arg_vector, ' '));
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700143 LOG(INFO) << "GenerateImage: " << command_line;
Brian Carlstrom6449c622014-02-10 23:48:36 -0800144 return Exec(arg_vector, error_msg);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700145}
146
Andreas Gampea463b6a2016-08-12 21:53:32 -0700147static bool FindImageFilenameImpl(const char* image_location,
148 const InstructionSet image_isa,
149 bool* has_system,
150 std::string* system_filename,
151 bool* dalvik_cache_exists,
152 std::string* dalvik_cache,
153 bool* is_global_cache,
154 bool* has_cache,
155 std::string* cache_filename) {
156 DCHECK(dalvik_cache != nullptr);
157
Alex Lighta59dd802014-07-02 16:28:08 -0700158 *has_system = false;
159 *has_cache = false;
Brian Carlstrom0e12bdc2014-05-14 17:44:28 -0700160 // image_location = /system/framework/boot.art
161 // system_image_location = /system/framework/<image_isa>/boot.art
162 std::string system_image_filename(GetSystemImageFilename(image_location, image_isa));
163 if (OS::FileExists(system_image_filename.c_str())) {
Alex Lighta59dd802014-07-02 16:28:08 -0700164 *system_filename = system_image_filename;
165 *has_system = true;
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700166 }
Narayan Kamath52f84882014-05-02 10:10:39 +0100167
Alex Lighta59dd802014-07-02 16:28:08 -0700168 bool have_android_data = false;
169 *dalvik_cache_exists = false;
Andreas Gampea463b6a2016-08-12 21:53:32 -0700170 GetDalvikCache(GetInstructionSetString(image_isa),
171 true,
172 dalvik_cache,
173 &have_android_data,
174 dalvik_cache_exists,
175 is_global_cache);
Narayan Kamath52f84882014-05-02 10:10:39 +0100176
Alex Lighta59dd802014-07-02 16:28:08 -0700177 if (have_android_data && *dalvik_cache_exists) {
178 // Always set output location even if it does not exist,
179 // so that the caller knows where to create the image.
180 //
181 // image_location = /system/framework/boot.art
182 // *image_filename = /data/dalvik-cache/<image_isa>/boot.art
183 std::string error_msg;
Andreas Gampea463b6a2016-08-12 21:53:32 -0700184 if (!GetDalvikCacheFilename(image_location,
185 dalvik_cache->c_str(),
186 cache_filename,
187 &error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -0700188 LOG(WARNING) << error_msg;
189 return *has_system;
190 }
191 *has_cache = OS::FileExists(cache_filename->c_str());
192 }
193 return *has_system || *has_cache;
194}
195
Andreas Gampea463b6a2016-08-12 21:53:32 -0700196bool ImageSpace::FindImageFilename(const char* image_location,
197 const InstructionSet image_isa,
198 std::string* system_filename,
199 bool* has_system,
200 std::string* cache_filename,
201 bool* dalvik_cache_exists,
202 bool* has_cache,
203 bool* is_global_cache) {
204 std::string dalvik_cache_unused;
205 return FindImageFilenameImpl(image_location,
206 image_isa,
207 has_system,
208 system_filename,
209 dalvik_cache_exists,
210 &dalvik_cache_unused,
211 is_global_cache,
212 has_cache,
213 cache_filename);
214}
215
Alex Lighta59dd802014-07-02 16:28:08 -0700216static bool ReadSpecificImageHeader(const char* filename, ImageHeader* image_header) {
217 std::unique_ptr<File> image_file(OS::OpenFileForReading(filename));
218 if (image_file.get() == nullptr) {
219 return false;
220 }
221 const bool success = image_file->ReadFully(image_header, sizeof(ImageHeader));
222 if (!success || !image_header->IsValid()) {
223 return false;
224 }
225 return true;
226}
227
Alex Light6e183f22014-07-18 14:57:04 -0700228// Relocate the image at image_location to dest_filename and relocate it by a random amount.
Andreas Gampea463b6a2016-08-12 21:53:32 -0700229static bool RelocateImage(const char* image_location,
230 const char* dest_filename,
231 InstructionSet isa,
232 std::string* error_msg) {
Alex Light25396132014-08-27 15:37:23 -0700233 // We should clean up so we are more likely to have room for the image.
234 if (Runtime::Current()->IsZygote()) {
235 LOG(INFO) << "Pruning dalvik-cache since we are relocating an image and will need to recompile";
Narayan Kamath28bc9872014-11-07 17:46:28 +0000236 PruneDalvikCache(isa);
Alex Light25396132014-08-27 15:37:23 -0700237 }
238
Alex Lighta59dd802014-07-02 16:28:08 -0700239 std::string patchoat(Runtime::Current()->GetPatchoatExecutable());
240
241 std::string input_image_location_arg("--input-image-location=");
242 input_image_location_arg += image_location;
243
244 std::string output_image_filename_arg("--output-image-file=");
245 output_image_filename_arg += dest_filename;
246
Alex Lighta59dd802014-07-02 16:28:08 -0700247 std::string instruction_set_arg("--instruction-set=");
248 instruction_set_arg += GetInstructionSetString(isa);
249
250 std::string base_offset_arg("--base-offset-delta=");
Andreas Gampea463b6a2016-08-12 21:53:32 -0700251 StringAppendF(&base_offset_arg, "%d", ChooseRelocationOffsetDelta());
Alex Lighta59dd802014-07-02 16:28:08 -0700252
253 std::vector<std::string> argv;
254 argv.push_back(patchoat);
255
256 argv.push_back(input_image_location_arg);
257 argv.push_back(output_image_filename_arg);
258
Alex Lighta59dd802014-07-02 16:28:08 -0700259 argv.push_back(instruction_set_arg);
260 argv.push_back(base_offset_arg);
261
Andreas Gampe9186ced2016-12-12 14:28:21 -0800262 std::string command_line(android::base::Join(argv, ' '));
Alex Lighta59dd802014-07-02 16:28:08 -0700263 LOG(INFO) << "RelocateImage: " << command_line;
264 return Exec(argv, error_msg);
265}
266
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700267static ImageHeader* ReadSpecificImageHeader(const char* filename, std::string* error_msg) {
Alex Lighta59dd802014-07-02 16:28:08 -0700268 std::unique_ptr<ImageHeader> hdr(new ImageHeader);
269 if (!ReadSpecificImageHeader(filename, hdr.get())) {
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700270 *error_msg = StringPrintf("Unable to read image header for %s", filename);
Alex Lighta59dd802014-07-02 16:28:08 -0700271 return nullptr;
272 }
273 return hdr.release();
Narayan Kamath52f84882014-05-02 10:10:39 +0100274}
275
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700276ImageHeader* ImageSpace::ReadImageHeader(const char* image_location,
277 const InstructionSet image_isa,
278 std::string* error_msg) {
Alex Lighta59dd802014-07-02 16:28:08 -0700279 std::string system_filename;
280 bool has_system = false;
281 std::string cache_filename;
282 bool has_cache = false;
283 bool dalvik_cache_exists = false;
Andreas Gampe3c13a792014-09-18 20:56:04 -0700284 bool is_global_cache = false;
Alex Lighta59dd802014-07-02 16:28:08 -0700285 if (FindImageFilename(image_location, image_isa, &system_filename, &has_system,
Andreas Gampe3c13a792014-09-18 20:56:04 -0700286 &cache_filename, &dalvik_cache_exists, &has_cache, &is_global_cache)) {
Alex Lighta59dd802014-07-02 16:28:08 -0700287 if (Runtime::Current()->ShouldRelocate()) {
288 if (has_system && has_cache) {
289 std::unique_ptr<ImageHeader> sys_hdr(new ImageHeader);
290 std::unique_ptr<ImageHeader> cache_hdr(new ImageHeader);
291 if (!ReadSpecificImageHeader(system_filename.c_str(), sys_hdr.get())) {
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700292 *error_msg = StringPrintf("Unable to read image header for %s at %s",
293 image_location, system_filename.c_str());
Alex Lighta59dd802014-07-02 16:28:08 -0700294 return nullptr;
295 }
296 if (!ReadSpecificImageHeader(cache_filename.c_str(), cache_hdr.get())) {
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700297 *error_msg = StringPrintf("Unable to read image header for %s at %s",
298 image_location, cache_filename.c_str());
Alex Lighta59dd802014-07-02 16:28:08 -0700299 return nullptr;
300 }
301 if (sys_hdr->GetOatChecksum() != cache_hdr->GetOatChecksum()) {
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700302 *error_msg = StringPrintf("Unable to find a relocated version of image file %s",
303 image_location);
Alex Lighta59dd802014-07-02 16:28:08 -0700304 return nullptr;
305 }
306 return cache_hdr.release();
307 } else if (!has_cache) {
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700308 *error_msg = StringPrintf("Unable to find a relocated version of image file %s",
309 image_location);
Alex Lighta59dd802014-07-02 16:28:08 -0700310 return nullptr;
311 } else if (!has_system && has_cache) {
312 // This can probably just use the cache one.
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700313 return ReadSpecificImageHeader(cache_filename.c_str(), error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -0700314 }
315 } else {
316 // We don't want to relocate, Just pick the appropriate one if we have it and return.
317 if (has_system && has_cache) {
318 // We want the cache if the checksum matches, otherwise the system.
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700319 std::unique_ptr<ImageHeader> system(ReadSpecificImageHeader(system_filename.c_str(),
320 error_msg));
321 std::unique_ptr<ImageHeader> cache(ReadSpecificImageHeader(cache_filename.c_str(),
322 error_msg));
Alex Lighta59dd802014-07-02 16:28:08 -0700323 if (system.get() == nullptr ||
324 (cache.get() != nullptr && cache->GetOatChecksum() == system->GetOatChecksum())) {
325 return cache.release();
326 } else {
327 return system.release();
328 }
329 } else if (has_system) {
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700330 return ReadSpecificImageHeader(system_filename.c_str(), error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -0700331 } else if (has_cache) {
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700332 return ReadSpecificImageHeader(cache_filename.c_str(), error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -0700333 }
Narayan Kamath52f84882014-05-02 10:10:39 +0100334 }
Narayan Kamath52f84882014-05-02 10:10:39 +0100335 }
336
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700337 *error_msg = StringPrintf("Unable to find image file for %s", image_location);
Narayan Kamath52f84882014-05-02 10:10:39 +0100338 return nullptr;
339}
340
Andreas Gampea463b6a2016-08-12 21:53:32 -0700341static bool ChecksumsMatch(const char* image_a, const char* image_b, std::string* error_msg) {
342 DCHECK(error_msg != nullptr);
343
Alex Lighta59dd802014-07-02 16:28:08 -0700344 ImageHeader hdr_a;
345 ImageHeader hdr_b;
Andreas Gampea463b6a2016-08-12 21:53:32 -0700346
347 if (!ReadSpecificImageHeader(image_a, &hdr_a)) {
348 *error_msg = StringPrintf("Cannot read header of %s", image_a);
349 return false;
350 }
351 if (!ReadSpecificImageHeader(image_b, &hdr_b)) {
352 *error_msg = StringPrintf("Cannot read header of %s", image_b);
353 return false;
354 }
355
356 if (hdr_a.GetOatChecksum() != hdr_b.GetOatChecksum()) {
357 *error_msg = StringPrintf("Checksum mismatch: %u(%s) vs %u(%s)",
358 hdr_a.GetOatChecksum(),
359 image_a,
360 hdr_b.GetOatChecksum(),
361 image_b);
362 return false;
363 }
364
365 return true;
Alex Lighta59dd802014-07-02 16:28:08 -0700366}
367
Robert Sesekbfa1f8d2016-08-15 15:21:09 -0400368static bool CanWriteToDalvikCache(const InstructionSet isa) {
369 const std::string dalvik_cache = GetDalvikCache(GetInstructionSetString(isa));
370 if (access(dalvik_cache.c_str(), O_RDWR) == 0) {
371 return true;
372 } else if (errno != EACCES) {
373 PLOG(WARNING) << "CanWriteToDalvikCache returned error other than EACCES";
374 }
375 return false;
376}
377
378static bool ImageCreationAllowed(bool is_global_cache,
379 const InstructionSet isa,
380 std::string* error_msg) {
Andreas Gampe3c13a792014-09-18 20:56:04 -0700381 // Anyone can write into a "local" cache.
382 if (!is_global_cache) {
383 return true;
384 }
385
Robert Sesekbfa1f8d2016-08-15 15:21:09 -0400386 // Only the zygote running as root is allowed to create the global boot image.
387 // If the zygote is running as non-root (and cannot write to the dalvik-cache),
388 // then image creation is not allowed..
Andreas Gampe3c13a792014-09-18 20:56:04 -0700389 if (Runtime::Current()->IsZygote()) {
Robert Sesekbfa1f8d2016-08-15 15:21:09 -0400390 return CanWriteToDalvikCache(isa);
Andreas Gampe3c13a792014-09-18 20:56:04 -0700391 }
392
393 *error_msg = "Only the zygote can create the global boot image.";
394 return false;
395}
396
Mathieu Chartier31e89252013-08-28 11:29:12 -0700397void ImageSpace::VerifyImageAllocations() {
Ian Rogers13735952014-10-08 12:43:28 -0700398 uint8_t* current = Begin() + RoundUp(sizeof(ImageHeader), kObjectAlignment);
Mathieu Chartier31e89252013-08-28 11:29:12 -0700399 while (current < End()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700400 CHECK_ALIGNED(current, kObjectAlignment);
401 auto* obj = reinterpret_cast<mirror::Object*>(current);
Mathieu Chartier31e89252013-08-28 11:29:12 -0700402 CHECK(obj->GetClass() != nullptr) << "Image object at address " << obj << " has null class";
David Sehr709b0702016-10-13 09:12:37 -0700403 CHECK(live_bitmap_->Test(obj)) << obj->PrettyTypeOf();
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700404 if (kUseBakerReadBarrier) {
405 obj->AssertReadBarrierState();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800406 }
Mathieu Chartier31e89252013-08-28 11:29:12 -0700407 current += RoundUp(obj->SizeOf(), kObjectAlignment);
408 }
409}
410
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800411// Helper class for relocating from one range of memory to another.
412class RelocationRange {
413 public:
414 RelocationRange() = default;
415 RelocationRange(const RelocationRange&) = default;
416 RelocationRange(uintptr_t source, uintptr_t dest, uintptr_t length)
417 : source_(source),
418 dest_(dest),
419 length_(length) {}
420
Mathieu Chartier91edc622016-02-16 17:16:01 -0800421 bool InSource(uintptr_t address) const {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800422 return address - source_ < length_;
423 }
424
Mathieu Chartier91edc622016-02-16 17:16:01 -0800425 bool InDest(uintptr_t address) const {
426 return address - dest_ < length_;
427 }
428
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800429 // Translate a source address to the destination space.
430 uintptr_t ToDest(uintptr_t address) const {
Mathieu Chartier91edc622016-02-16 17:16:01 -0800431 DCHECK(InSource(address));
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800432 return address + Delta();
433 }
434
435 // Returns the delta between the dest from the source.
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800436 uintptr_t Delta() const {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800437 return dest_ - source_;
438 }
439
440 uintptr_t Source() const {
441 return source_;
442 }
443
444 uintptr_t Dest() const {
445 return dest_;
446 }
447
448 uintptr_t Length() const {
449 return length_;
450 }
451
452 private:
453 const uintptr_t source_;
454 const uintptr_t dest_;
455 const uintptr_t length_;
456};
457
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800458std::ostream& operator<<(std::ostream& os, const RelocationRange& reloc) {
459 return os << "(" << reinterpret_cast<const void*>(reloc.Source()) << "-"
460 << reinterpret_cast<const void*>(reloc.Source() + reloc.Length()) << ")->("
461 << reinterpret_cast<const void*>(reloc.Dest()) << "-"
462 << reinterpret_cast<const void*>(reloc.Dest() + reloc.Length()) << ")";
463}
464
Andreas Gampea463b6a2016-08-12 21:53:32 -0700465// Helper class encapsulating loading, so we can access private ImageSpace members (this is a
466// friend class), but not declare functions in the header.
467class ImageSpaceLoader {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800468 public:
Andreas Gampea463b6a2016-08-12 21:53:32 -0700469 static std::unique_ptr<ImageSpace> Load(const char* image_location,
470 const std::string& image_filename,
471 bool is_zygote,
472 bool is_global_cache,
Andreas Gampe44c8ed62016-08-19 16:43:00 -0700473 bool validate_oat_file,
Andreas Gampea463b6a2016-08-12 21:53:32 -0700474 std::string* error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700475 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampea463b6a2016-08-12 21:53:32 -0700476 // Note that we must not use the file descriptor associated with
477 // ScopedFlock::GetFile to Init the image file. We want the file
478 // descriptor (and the associated exclusive lock) to be released when
479 // we leave Create.
480 ScopedFlock image_lock;
481 // Should this be a RDWR lock? This is only a defensive measure, as at
482 // this point the image should exist.
483 // However, only the zygote can write into the global dalvik-cache, so
484 // restrict to zygote processes, or any process that isn't using
485 // /data/dalvik-cache (which we assume to be allowed to write there).
486 const bool rw_lock = is_zygote || !is_global_cache;
487 image_lock.Init(image_filename.c_str(),
488 rw_lock ? (O_CREAT | O_RDWR) : O_RDONLY /* flags */,
489 true /* block */,
490 error_msg);
491 VLOG(startup) << "Using image file " << image_filename.c_str() << " for image location "
492 << image_location;
493 // If we are in /system we can assume the image is good. We can also
494 // assume this if we are using a relocated image (i.e. image checksum
495 // matches) since this is only different by the offset. We need this to
496 // make sure that host tests continue to work.
497 // Since we are the boot image, pass null since we load the oat file from the boot image oat
498 // file name.
499 return Init(image_filename.c_str(),
500 image_location,
Andreas Gampe44c8ed62016-08-19 16:43:00 -0700501 validate_oat_file,
Andreas Gampea463b6a2016-08-12 21:53:32 -0700502 /* oat_file */nullptr,
503 error_msg);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800504 }
505
Andreas Gampea463b6a2016-08-12 21:53:32 -0700506 static std::unique_ptr<ImageSpace> Init(const char* image_filename,
507 const char* image_location,
508 bool validate_oat_file,
509 const OatFile* oat_file,
510 std::string* error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700511 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampea463b6a2016-08-12 21:53:32 -0700512 CHECK(image_filename != nullptr);
513 CHECK(image_location != nullptr);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800514
Andreas Gampea463b6a2016-08-12 21:53:32 -0700515 TimingLogger logger(__PRETTY_FUNCTION__, true, VLOG_IS_ON(image));
516 VLOG(image) << "ImageSpace::Init entering image_filename=" << image_filename;
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800517
Andreas Gampea463b6a2016-08-12 21:53:32 -0700518 std::unique_ptr<File> file;
Mathieu Chartier92ec5942016-04-11 12:03:48 -0700519 {
Andreas Gampea463b6a2016-08-12 21:53:32 -0700520 TimingLogger::ScopedTiming timing("OpenImageFile", &logger);
521 file.reset(OS::OpenFileForReading(image_filename));
522 if (file == nullptr) {
523 *error_msg = StringPrintf("Failed to open '%s'", image_filename);
524 return nullptr;
Mathieu Chartier92ec5942016-04-11 12:03:48 -0700525 }
Andreas Gampea463b6a2016-08-12 21:53:32 -0700526 }
527 ImageHeader temp_image_header;
528 ImageHeader* image_header = &temp_image_header;
529 {
530 TimingLogger::ScopedTiming timing("ReadImageHeader", &logger);
531 bool success = file->ReadFully(image_header, sizeof(*image_header));
532 if (!success || !image_header->IsValid()) {
533 *error_msg = StringPrintf("Invalid image header in '%s'", image_filename);
534 return nullptr;
535 }
536 }
537 // Check that the file is larger or equal to the header size + data size.
538 const uint64_t image_file_size = static_cast<uint64_t>(file->GetLength());
539 if (image_file_size < sizeof(ImageHeader) + image_header->GetDataSize()) {
540 *error_msg = StringPrintf("Image file truncated: %" PRIu64 " vs. %" PRIu64 ".",
541 image_file_size,
542 sizeof(ImageHeader) + image_header->GetDataSize());
543 return nullptr;
544 }
545
546 if (oat_file != nullptr) {
547 // If we have an oat file, check the oat file checksum. The oat file is only non-null for the
548 // app image case. Otherwise, we open the oat file after the image and check the checksum there.
549 const uint32_t oat_checksum = oat_file->GetOatHeader().GetChecksum();
550 const uint32_t image_oat_checksum = image_header->GetOatChecksum();
551 if (oat_checksum != image_oat_checksum) {
552 *error_msg = StringPrintf("Oat checksum 0x%x does not match the image one 0x%x in image %s",
553 oat_checksum,
554 image_oat_checksum,
555 image_filename);
556 return nullptr;
Mathieu Chartier92ec5942016-04-11 12:03:48 -0700557 }
558 }
559
Andreas Gampea463b6a2016-08-12 21:53:32 -0700560 if (VLOG_IS_ON(startup)) {
561 LOG(INFO) << "Dumping image sections";
562 for (size_t i = 0; i < ImageHeader::kSectionCount; ++i) {
563 const auto section_idx = static_cast<ImageHeader::ImageSections>(i);
564 auto& section = image_header->GetImageSection(section_idx);
565 LOG(INFO) << section_idx << " start="
566 << reinterpret_cast<void*>(image_header->GetImageBegin() + section.Offset()) << " "
567 << section;
Mathieu Chartier92ec5942016-04-11 12:03:48 -0700568 }
Andreas Gampea463b6a2016-08-12 21:53:32 -0700569 }
570
571 const auto& bitmap_section = image_header->GetImageSection(ImageHeader::kSectionImageBitmap);
572 // The location we want to map from is the first aligned page after the end of the stored
573 // (possibly compressed) data.
574 const size_t image_bitmap_offset = RoundUp(sizeof(ImageHeader) + image_header->GetDataSize(),
575 kPageSize);
576 const size_t end_of_bitmap = image_bitmap_offset + bitmap_section.Size();
577 if (end_of_bitmap != image_file_size) {
578 *error_msg = StringPrintf(
579 "Image file size does not equal end of bitmap: size=%" PRIu64 " vs. %zu.", image_file_size,
580 end_of_bitmap);
581 return nullptr;
582 }
583
584 std::unique_ptr<MemMap> map;
585 // GetImageBegin is the preferred address to map the image. If we manage to map the
586 // image at the image begin, the amount of fixup work required is minimized.
587 map.reset(LoadImageFile(image_filename,
588 image_location,
589 *image_header,
590 image_header->GetImageBegin(),
591 file->Fd(),
592 logger,
593 error_msg));
594 // If the header specifies PIC mode, we can also map at a random low_4gb address since we can
595 // relocate in-place.
596 if (map == nullptr && image_header->IsPic()) {
597 map.reset(LoadImageFile(image_filename,
598 image_location,
599 *image_header,
600 /* address */ nullptr,
601 file->Fd(),
602 logger,
603 error_msg));
604 }
605 // Were we able to load something and continue?
606 if (map == nullptr) {
607 DCHECK(!error_msg->empty());
608 return nullptr;
609 }
610 DCHECK_EQ(0, memcmp(image_header, map->Begin(), sizeof(ImageHeader)));
611
612 std::unique_ptr<MemMap> image_bitmap_map(MemMap::MapFileAtAddress(nullptr,
613 bitmap_section.Size(),
614 PROT_READ, MAP_PRIVATE,
615 file->Fd(),
616 image_bitmap_offset,
617 /*low_4gb*/false,
618 /*reuse*/false,
619 image_filename,
620 error_msg));
621 if (image_bitmap_map == nullptr) {
622 *error_msg = StringPrintf("Failed to map image bitmap: %s", error_msg->c_str());
623 return nullptr;
624 }
625 // Loaded the map, use the image header from the file now in case we patch it with
626 // RelocateInPlace.
627 image_header = reinterpret_cast<ImageHeader*>(map->Begin());
628 const uint32_t bitmap_index = ImageSpace::bitmap_index_.FetchAndAddSequentiallyConsistent(1);
629 std::string bitmap_name(StringPrintf("imagespace %s live-bitmap %u",
630 image_filename,
631 bitmap_index));
632 // Bitmap only needs to cover until the end of the mirror objects section.
633 const ImageSection& image_objects = image_header->GetImageSection(ImageHeader::kSectionObjects);
634 // We only want the mirror object, not the ArtFields and ArtMethods.
635 uint8_t* const image_end = map->Begin() + image_objects.End();
636 std::unique_ptr<accounting::ContinuousSpaceBitmap> bitmap;
637 {
638 TimingLogger::ScopedTiming timing("CreateImageBitmap", &logger);
639 bitmap.reset(
640 accounting::ContinuousSpaceBitmap::CreateFromMemMap(
641 bitmap_name,
642 image_bitmap_map.release(),
643 reinterpret_cast<uint8_t*>(map->Begin()),
644 image_objects.End()));
645 if (bitmap == nullptr) {
646 *error_msg = StringPrintf("Could not create bitmap '%s'", bitmap_name.c_str());
647 return nullptr;
648 }
649 }
650 {
651 TimingLogger::ScopedTiming timing("RelocateImage", &logger);
652 if (!RelocateInPlace(*image_header,
653 map->Begin(),
654 bitmap.get(),
655 oat_file,
656 error_msg)) {
657 return nullptr;
658 }
659 }
660 // We only want the mirror object, not the ArtFields and ArtMethods.
661 std::unique_ptr<ImageSpace> space(new ImageSpace(image_filename,
662 image_location,
663 map.release(),
664 bitmap.release(),
665 image_end));
666
667 // VerifyImageAllocations() will be called later in Runtime::Init()
668 // as some class roots like ArtMethod::java_lang_reflect_ArtMethod_
669 // and ArtField::java_lang_reflect_ArtField_, which are used from
670 // Object::SizeOf() which VerifyImageAllocations() calls, are not
671 // set yet at this point.
672 if (oat_file == nullptr) {
673 TimingLogger::ScopedTiming timing("OpenOatFile", &logger);
674 space->oat_file_ = OpenOatFile(*space, image_filename, error_msg);
675 if (space->oat_file_ == nullptr) {
676 DCHECK(!error_msg->empty());
677 return nullptr;
678 }
679 space->oat_file_non_owned_ = space->oat_file_.get();
680 } else {
681 space->oat_file_non_owned_ = oat_file;
682 }
683
684 if (validate_oat_file) {
685 TimingLogger::ScopedTiming timing("ValidateOatFile", &logger);
686 CHECK(space->oat_file_ != nullptr);
687 if (!ValidateOatFile(*space, *space->oat_file_, error_msg)) {
688 DCHECK(!error_msg->empty());
689 return nullptr;
690 }
691 }
692
693 Runtime* runtime = Runtime::Current();
694
695 // If oat_file is null, then it is the boot image space. Use oat_file_non_owned_ from the space
696 // to set the runtime methods.
697 CHECK_EQ(oat_file != nullptr, image_header->IsAppImage());
698 if (image_header->IsAppImage()) {
699 CHECK_EQ(runtime->GetResolutionMethod(),
700 image_header->GetImageMethod(ImageHeader::kResolutionMethod));
701 CHECK_EQ(runtime->GetImtConflictMethod(),
702 image_header->GetImageMethod(ImageHeader::kImtConflictMethod));
703 CHECK_EQ(runtime->GetImtUnimplementedMethod(),
704 image_header->GetImageMethod(ImageHeader::kImtUnimplementedMethod));
705 CHECK_EQ(runtime->GetCalleeSaveMethod(Runtime::kSaveAllCalleeSaves),
706 image_header->GetImageMethod(ImageHeader::kSaveAllCalleeSavesMethod));
707 CHECK_EQ(runtime->GetCalleeSaveMethod(Runtime::kSaveRefsOnly),
708 image_header->GetImageMethod(ImageHeader::kSaveRefsOnlyMethod));
709 CHECK_EQ(runtime->GetCalleeSaveMethod(Runtime::kSaveRefsAndArgs),
710 image_header->GetImageMethod(ImageHeader::kSaveRefsAndArgsMethod));
711 CHECK_EQ(runtime->GetCalleeSaveMethod(Runtime::kSaveEverything),
712 image_header->GetImageMethod(ImageHeader::kSaveEverythingMethod));
713 } else if (!runtime->HasResolutionMethod()) {
714 runtime->SetInstructionSet(space->oat_file_non_owned_->GetOatHeader().GetInstructionSet());
715 runtime->SetResolutionMethod(image_header->GetImageMethod(ImageHeader::kResolutionMethod));
716 runtime->SetImtConflictMethod(image_header->GetImageMethod(ImageHeader::kImtConflictMethod));
717 runtime->SetImtUnimplementedMethod(
718 image_header->GetImageMethod(ImageHeader::kImtUnimplementedMethod));
719 runtime->SetCalleeSaveMethod(
720 image_header->GetImageMethod(ImageHeader::kSaveAllCalleeSavesMethod),
721 Runtime::kSaveAllCalleeSaves);
722 runtime->SetCalleeSaveMethod(
723 image_header->GetImageMethod(ImageHeader::kSaveRefsOnlyMethod), Runtime::kSaveRefsOnly);
724 runtime->SetCalleeSaveMethod(
725 image_header->GetImageMethod(ImageHeader::kSaveRefsAndArgsMethod),
726 Runtime::kSaveRefsAndArgs);
727 runtime->SetCalleeSaveMethod(
728 image_header->GetImageMethod(ImageHeader::kSaveEverythingMethod), Runtime::kSaveEverything);
729 }
730
731 VLOG(image) << "ImageSpace::Init exiting " << *space.get();
732 if (VLOG_IS_ON(image)) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700733 logger.Dump(LOG_STREAM(INFO));
Andreas Gampea463b6a2016-08-12 21:53:32 -0700734 }
735 return space;
736 }
737
738 private:
739 static MemMap* LoadImageFile(const char* image_filename,
740 const char* image_location,
741 const ImageHeader& image_header,
742 uint8_t* address,
743 int fd,
744 TimingLogger& logger,
745 std::string* error_msg) {
746 TimingLogger::ScopedTiming timing("MapImageFile", &logger);
747 const ImageHeader::StorageMode storage_mode = image_header.GetStorageMode();
748 if (storage_mode == ImageHeader::kStorageModeUncompressed) {
749 return MemMap::MapFileAtAddress(address,
750 image_header.GetImageSize(),
751 PROT_READ | PROT_WRITE,
752 MAP_PRIVATE,
753 fd,
754 0,
755 /*low_4gb*/true,
756 /*reuse*/false,
757 image_filename,
758 error_msg);
759 }
760
761 if (storage_mode != ImageHeader::kStorageModeLZ4 &&
762 storage_mode != ImageHeader::kStorageModeLZ4HC) {
763 *error_msg = StringPrintf("Invalid storage mode in image header %d",
764 static_cast<int>(storage_mode));
765 return nullptr;
766 }
767
768 // Reserve output and decompress into it.
769 std::unique_ptr<MemMap> map(MemMap::MapAnonymous(image_location,
770 address,
771 image_header.GetImageSize(),
772 PROT_READ | PROT_WRITE,
773 /*low_4gb*/true,
774 /*reuse*/false,
775 error_msg));
776 if (map != nullptr) {
777 const size_t stored_size = image_header.GetDataSize();
778 const size_t decompress_offset = sizeof(ImageHeader); // Skip the header.
779 std::unique_ptr<MemMap> temp_map(MemMap::MapFile(sizeof(ImageHeader) + stored_size,
780 PROT_READ,
781 MAP_PRIVATE,
782 fd,
783 /*offset*/0,
784 /*low_4gb*/false,
785 image_filename,
786 error_msg));
787 if (temp_map == nullptr) {
788 DCHECK(!error_msg->empty());
789 return nullptr;
790 }
791 memcpy(map->Begin(), &image_header, sizeof(ImageHeader));
792 const uint64_t start = NanoTime();
793 // LZ4HC and LZ4 have same internal format, both use LZ4_decompress.
794 TimingLogger::ScopedTiming timing2("LZ4 decompress image", &logger);
795 const size_t decompressed_size = LZ4_decompress_safe(
796 reinterpret_cast<char*>(temp_map->Begin()) + sizeof(ImageHeader),
797 reinterpret_cast<char*>(map->Begin()) + decompress_offset,
798 stored_size,
799 map->Size() - decompress_offset);
800 VLOG(image) << "Decompressing image took " << PrettyDuration(NanoTime() - start);
801 if (decompressed_size + sizeof(ImageHeader) != image_header.GetImageSize()) {
802 *error_msg = StringPrintf(
803 "Decompressed size does not match expected image size %zu vs %zu",
804 decompressed_size + sizeof(ImageHeader),
805 image_header.GetImageSize());
806 return nullptr;
807 }
808 }
809
810 return map.release();
811 }
812
813 class FixupVisitor : public ValueObject {
814 public:
815 FixupVisitor(const RelocationRange& boot_image,
816 const RelocationRange& boot_oat,
817 const RelocationRange& app_image,
818 const RelocationRange& app_oat)
819 : boot_image_(boot_image),
820 boot_oat_(boot_oat),
821 app_image_(app_image),
822 app_oat_(app_oat) {}
823
824 // Return the relocated address of a heap object.
825 template <typename T>
826 ALWAYS_INLINE T* ForwardObject(T* src) const {
827 const uintptr_t uint_src = reinterpret_cast<uintptr_t>(src);
828 if (boot_image_.InSource(uint_src)) {
829 return reinterpret_cast<T*>(boot_image_.ToDest(uint_src));
830 }
831 if (app_image_.InSource(uint_src)) {
832 return reinterpret_cast<T*>(app_image_.ToDest(uint_src));
833 }
834 // Since we are fixing up the app image, there should only be pointers to the app image and
835 // boot image.
836 DCHECK(src == nullptr) << reinterpret_cast<const void*>(src);
837 return src;
838 }
839
840 // Return the relocated address of a code pointer (contained by an oat file).
841 ALWAYS_INLINE const void* ForwardCode(const void* src) const {
842 const uintptr_t uint_src = reinterpret_cast<uintptr_t>(src);
843 if (boot_oat_.InSource(uint_src)) {
844 return reinterpret_cast<const void*>(boot_oat_.ToDest(uint_src));
845 }
846 if (app_oat_.InSource(uint_src)) {
847 return reinterpret_cast<const void*>(app_oat_.ToDest(uint_src));
848 }
849 DCHECK(src == nullptr) << src;
850 return src;
851 }
852
853 // Must be called on pointers that already have been relocated to the destination relocation.
854 ALWAYS_INLINE bool IsInAppImage(mirror::Object* object) const {
855 return app_image_.InDest(reinterpret_cast<uintptr_t>(object));
856 }
857
858 protected:
859 // Source section.
860 const RelocationRange boot_image_;
861 const RelocationRange boot_oat_;
862 const RelocationRange app_image_;
863 const RelocationRange app_oat_;
864 };
865
866 // Adapt for mirror::Class::FixupNativePointers.
867 class FixupObjectAdapter : public FixupVisitor {
868 public:
869 template<typename... Args>
870 explicit FixupObjectAdapter(Args... args) : FixupVisitor(args...) {}
871
872 template <typename T>
873 T* operator()(T* obj) const {
874 return ForwardObject(obj);
875 }
876 };
877
878 class FixupRootVisitor : public FixupVisitor {
879 public:
880 template<typename... Args>
881 explicit FixupRootVisitor(Args... args) : FixupVisitor(args...) {}
882
883 ALWAYS_INLINE void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700884 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampea463b6a2016-08-12 21:53:32 -0700885 if (!root->IsNull()) {
886 VisitRoot(root);
887 }
888 }
889
890 ALWAYS_INLINE void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700891 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampea463b6a2016-08-12 21:53:32 -0700892 mirror::Object* ref = root->AsMirrorPtr();
893 mirror::Object* new_ref = ForwardObject(ref);
894 if (ref != new_ref) {
895 root->Assign(new_ref);
896 }
897 }
898 };
899
900 class FixupObjectVisitor : public FixupVisitor {
901 public:
902 template<typename... Args>
903 explicit FixupObjectVisitor(gc::accounting::ContinuousSpaceBitmap* visited,
904 const PointerSize pointer_size,
905 Args... args)
906 : FixupVisitor(args...),
907 pointer_size_(pointer_size),
908 visited_(visited) {}
909
910 // Fix up separately since we also need to fix up method entrypoints.
911 ALWAYS_INLINE void VisitRootIfNonNull(
912 mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const {}
913
914 ALWAYS_INLINE void VisitRoot(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED)
915 const {}
916
Mathieu Chartier31e88222016-10-14 18:43:19 -0700917 ALWAYS_INLINE void operator()(ObjPtr<mirror::Object> obj,
Andreas Gampea463b6a2016-08-12 21:53:32 -0700918 MemberOffset offset,
919 bool is_static ATTRIBUTE_UNUSED) const
920 NO_THREAD_SAFETY_ANALYSIS {
921 // There could be overlap between ranges, we must avoid visiting the same reference twice.
922 // Avoid the class field since we already fixed it up in FixupClassVisitor.
923 if (offset.Uint32Value() != mirror::Object::ClassOffset().Uint32Value()) {
924 // Space is not yet added to the heap, don't do a read barrier.
925 mirror::Object* ref = obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(
926 offset);
927 // Use SetFieldObjectWithoutWriteBarrier to avoid card marking since we are writing to the
928 // image.
929 obj->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(offset, ForwardObject(ref));
930 }
931 }
932
933 // Visit a pointer array and forward corresponding native data. Ignores pointer arrays in the
934 // boot image. Uses the bitmap to ensure the same array is not visited multiple times.
935 template <typename Visitor>
936 void UpdatePointerArrayContents(mirror::PointerArray* array, const Visitor& visitor) const
937 NO_THREAD_SAFETY_ANALYSIS {
938 DCHECK(array != nullptr);
939 DCHECK(visitor.IsInAppImage(array));
940 // The bit for the array contents is different than the bit for the array. Since we may have
941 // already visited the array as a long / int array from walking the bitmap without knowing it
942 // was a pointer array.
943 static_assert(kObjectAlignment == 8u, "array bit may be in another object");
944 mirror::Object* const contents_bit = reinterpret_cast<mirror::Object*>(
945 reinterpret_cast<uintptr_t>(array) + kObjectAlignment);
946 // If the bit is not set then the contents have not yet been updated.
947 if (!visited_->Test(contents_bit)) {
948 array->Fixup<kVerifyNone, kWithoutReadBarrier>(array, pointer_size_, visitor);
949 visited_->Set(contents_bit);
950 }
951 }
952
953 // java.lang.ref.Reference visitor.
Mathieu Chartier31e88222016-10-14 18:43:19 -0700954 void operator()(ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
955 ObjPtr<mirror::Reference> ref) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700956 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Andreas Gampea463b6a2016-08-12 21:53:32 -0700957 mirror::Object* obj = ref->GetReferent<kWithoutReadBarrier>();
958 ref->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
959 mirror::Reference::ReferentOffset(),
960 ForwardObject(obj));
961 }
962
963 void operator()(mirror::Object* obj) const NO_THREAD_SAFETY_ANALYSIS {
964 if (visited_->Test(obj)) {
965 // Already visited.
966 return;
967 }
968 visited_->Set(obj);
969
970 // Handle class specially first since we need it to be updated to properly visit the rest of
971 // the instance fields.
972 {
973 mirror::Class* klass = obj->GetClass<kVerifyNone, kWithoutReadBarrier>();
974 DCHECK(klass != nullptr) << "Null class in image";
975 // No AsClass since our fields aren't quite fixed up yet.
976 mirror::Class* new_klass = down_cast<mirror::Class*>(ForwardObject(klass));
977 if (klass != new_klass) {
978 obj->SetClass<kVerifyNone>(new_klass);
979 }
980 if (new_klass != klass && IsInAppImage(new_klass)) {
981 // Make sure the klass contents are fixed up since we depend on it to walk the fields.
982 operator()(new_klass);
983 }
984 }
985
986 obj->VisitReferences</*visit native roots*/false, kVerifyNone, kWithoutReadBarrier>(
987 *this,
988 *this);
989 // Note that this code relies on no circular dependencies.
990 // We want to use our own class loader and not the one in the image.
991 if (obj->IsClass<kVerifyNone, kWithoutReadBarrier>()) {
992 mirror::Class* as_klass = obj->AsClass<kVerifyNone, kWithoutReadBarrier>();
993 FixupObjectAdapter visitor(boot_image_, boot_oat_, app_image_, app_oat_);
994 as_klass->FixupNativePointers<kVerifyNone, kWithoutReadBarrier>(as_klass,
995 pointer_size_,
996 visitor);
997 // Deal with the pointer arrays. Use the helper function since multiple classes can reference
998 // the same arrays.
999 mirror::PointerArray* const vtable = as_klass->GetVTable<kVerifyNone, kWithoutReadBarrier>();
1000 if (vtable != nullptr && IsInAppImage(vtable)) {
1001 operator()(vtable);
1002 UpdatePointerArrayContents(vtable, visitor);
1003 }
1004 mirror::IfTable* iftable = as_klass->GetIfTable<kVerifyNone, kWithoutReadBarrier>();
1005 // Ensure iftable arrays are fixed up since we need GetMethodArray to return the valid
1006 // contents.
Mathieu Chartier6beced42016-11-15 15:51:31 -08001007 if (IsInAppImage(iftable)) {
Andreas Gampea463b6a2016-08-12 21:53:32 -07001008 operator()(iftable);
1009 for (int32_t i = 0, count = iftable->Count(); i < count; ++i) {
1010 if (iftable->GetMethodArrayCount<kVerifyNone, kWithoutReadBarrier>(i) > 0) {
1011 mirror::PointerArray* methods =
1012 iftable->GetMethodArray<kVerifyNone, kWithoutReadBarrier>(i);
1013 if (visitor.IsInAppImage(methods)) {
1014 operator()(methods);
1015 DCHECK(methods != nullptr);
1016 UpdatePointerArrayContents(methods, visitor);
1017 }
Mathieu Chartier92ec5942016-04-11 12:03:48 -07001018 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001019 }
1020 }
1021 }
1022 }
Mathieu Chartier91edc622016-02-16 17:16:01 -08001023
Andreas Gampea463b6a2016-08-12 21:53:32 -07001024 private:
1025 const PointerSize pointer_size_;
1026 gc::accounting::ContinuousSpaceBitmap* const visited_;
1027 };
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001028
Andreas Gampea463b6a2016-08-12 21:53:32 -07001029 class ForwardObjectAdapter {
1030 public:
1031 ALWAYS_INLINE explicit ForwardObjectAdapter(const FixupVisitor* visitor) : visitor_(visitor) {}
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001032
Andreas Gampea463b6a2016-08-12 21:53:32 -07001033 template <typename T>
1034 ALWAYS_INLINE T* operator()(T* src) const {
1035 return visitor_->ForwardObject(src);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001036 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001037
Andreas Gampea463b6a2016-08-12 21:53:32 -07001038 private:
1039 const FixupVisitor* const visitor_;
1040 };
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001041
Andreas Gampea463b6a2016-08-12 21:53:32 -07001042 class ForwardCodeAdapter {
1043 public:
1044 ALWAYS_INLINE explicit ForwardCodeAdapter(const FixupVisitor* visitor)
1045 : visitor_(visitor) {}
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001046
Andreas Gampea463b6a2016-08-12 21:53:32 -07001047 template <typename T>
1048 ALWAYS_INLINE T* operator()(T* src) const {
1049 return visitor_->ForwardCode(src);
1050 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001051
Andreas Gampea463b6a2016-08-12 21:53:32 -07001052 private:
1053 const FixupVisitor* const visitor_;
1054 };
1055
1056 class FixupArtMethodVisitor : public FixupVisitor, public ArtMethodVisitor {
1057 public:
1058 template<typename... Args>
1059 explicit FixupArtMethodVisitor(bool fixup_heap_objects, PointerSize pointer_size, Args... args)
1060 : FixupVisitor(args...),
1061 fixup_heap_objects_(fixup_heap_objects),
1062 pointer_size_(pointer_size) {}
1063
1064 virtual void Visit(ArtMethod* method) NO_THREAD_SAFETY_ANALYSIS {
1065 // TODO: Separate visitor for runtime vs normal methods.
1066 if (UNLIKELY(method->IsRuntimeMethod())) {
1067 ImtConflictTable* table = method->GetImtConflictTable(pointer_size_);
1068 if (table != nullptr) {
1069 ImtConflictTable* new_table = ForwardObject(table);
1070 if (table != new_table) {
1071 method->SetImtConflictTable(new_table, pointer_size_);
1072 }
1073 }
1074 const void* old_code = method->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size_);
1075 const void* new_code = ForwardCode(old_code);
1076 if (old_code != new_code) {
1077 method->SetEntryPointFromQuickCompiledCodePtrSize(new_code, pointer_size_);
1078 }
1079 } else {
1080 if (fixup_heap_objects_) {
1081 method->UpdateObjectsForImageRelocation(ForwardObjectAdapter(this), pointer_size_);
1082 }
1083 method->UpdateEntrypoints<kWithoutReadBarrier>(ForwardCodeAdapter(this), pointer_size_);
1084 }
1085 }
1086
1087 private:
1088 const bool fixup_heap_objects_;
1089 const PointerSize pointer_size_;
1090 };
1091
1092 class FixupArtFieldVisitor : public FixupVisitor, public ArtFieldVisitor {
1093 public:
1094 template<typename... Args>
1095 explicit FixupArtFieldVisitor(Args... args) : FixupVisitor(args...) {}
1096
1097 virtual void Visit(ArtField* field) NO_THREAD_SAFETY_ANALYSIS {
1098 field->UpdateObjects(ForwardObjectAdapter(this));
1099 }
1100 };
1101
1102 // Relocate an image space mapped at target_base which possibly used to be at a different base
1103 // address. Only needs a single image space, not one for both source and destination.
1104 // In place means modifying a single ImageSpace in place rather than relocating from one ImageSpace
1105 // to another.
1106 static bool RelocateInPlace(ImageHeader& image_header,
1107 uint8_t* target_base,
1108 accounting::ContinuousSpaceBitmap* bitmap,
1109 const OatFile* app_oat_file,
1110 std::string* error_msg) {
1111 DCHECK(error_msg != nullptr);
1112 if (!image_header.IsPic()) {
1113 if (image_header.GetImageBegin() == target_base) {
1114 return true;
1115 }
1116 *error_msg = StringPrintf("Cannot relocate non-pic image for oat file %s",
1117 (app_oat_file != nullptr) ? app_oat_file->GetLocation().c_str() : "");
1118 return false;
1119 }
1120 // Set up sections.
1121 uint32_t boot_image_begin = 0;
1122 uint32_t boot_image_end = 0;
1123 uint32_t boot_oat_begin = 0;
1124 uint32_t boot_oat_end = 0;
1125 const PointerSize pointer_size = image_header.GetPointerSize();
1126 gc::Heap* const heap = Runtime::Current()->GetHeap();
1127 heap->GetBootImagesSize(&boot_image_begin, &boot_image_end, &boot_oat_begin, &boot_oat_end);
1128 if (boot_image_begin == boot_image_end) {
1129 *error_msg = "Can not relocate app image without boot image space";
1130 return false;
1131 }
1132 if (boot_oat_begin == boot_oat_end) {
1133 *error_msg = "Can not relocate app image without boot oat file";
1134 return false;
1135 }
1136 const uint32_t boot_image_size = boot_image_end - boot_image_begin;
1137 const uint32_t boot_oat_size = boot_oat_end - boot_oat_begin;
1138 const uint32_t image_header_boot_image_size = image_header.GetBootImageSize();
1139 const uint32_t image_header_boot_oat_size = image_header.GetBootOatSize();
1140 if (boot_image_size != image_header_boot_image_size) {
1141 *error_msg = StringPrintf("Boot image size %" PRIu64 " does not match expected size %"
1142 PRIu64,
1143 static_cast<uint64_t>(boot_image_size),
1144 static_cast<uint64_t>(image_header_boot_image_size));
1145 return false;
1146 }
1147 if (boot_oat_size != image_header_boot_oat_size) {
1148 *error_msg = StringPrintf("Boot oat size %" PRIu64 " does not match expected size %"
1149 PRIu64,
1150 static_cast<uint64_t>(boot_oat_size),
1151 static_cast<uint64_t>(image_header_boot_oat_size));
1152 return false;
1153 }
1154 TimingLogger logger(__FUNCTION__, true, false);
1155 RelocationRange boot_image(image_header.GetBootImageBegin(),
1156 boot_image_begin,
1157 boot_image_size);
1158 RelocationRange boot_oat(image_header.GetBootOatBegin(),
1159 boot_oat_begin,
1160 boot_oat_size);
1161 RelocationRange app_image(reinterpret_cast<uintptr_t>(image_header.GetImageBegin()),
1162 reinterpret_cast<uintptr_t>(target_base),
1163 image_header.GetImageSize());
1164 // Use the oat data section since this is where the OatFile::Begin is.
1165 RelocationRange app_oat(reinterpret_cast<uintptr_t>(image_header.GetOatDataBegin()),
1166 // Not necessarily in low 4GB.
1167 reinterpret_cast<uintptr_t>(app_oat_file->Begin()),
1168 image_header.GetOatDataEnd() - image_header.GetOatDataBegin());
1169 VLOG(image) << "App image " << app_image;
1170 VLOG(image) << "App oat " << app_oat;
1171 VLOG(image) << "Boot image " << boot_image;
1172 VLOG(image) << "Boot oat " << boot_oat;
1173 // True if we need to fixup any heap pointers, otherwise only code pointers.
1174 const bool fixup_image = boot_image.Delta() != 0 || app_image.Delta() != 0;
1175 const bool fixup_code = boot_oat.Delta() != 0 || app_oat.Delta() != 0;
1176 if (!fixup_image && !fixup_code) {
1177 // Nothing to fix up.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001178 return true;
1179 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07001180 ScopedDebugDisallowReadBarriers sddrb(Thread::Current());
1181 // Need to update the image to be at the target base.
1182 const ImageSection& objects_section = image_header.GetImageSection(ImageHeader::kSectionObjects);
1183 uintptr_t objects_begin = reinterpret_cast<uintptr_t>(target_base + objects_section.Offset());
1184 uintptr_t objects_end = reinterpret_cast<uintptr_t>(target_base + objects_section.End());
1185 FixupObjectAdapter fixup_adapter(boot_image, boot_oat, app_image, app_oat);
1186 if (fixup_image) {
1187 // Two pass approach, fix up all classes first, then fix up non class-objects.
1188 // The visited bitmap is used to ensure that pointer arrays are not forwarded twice.
1189 std::unique_ptr<gc::accounting::ContinuousSpaceBitmap> visited_bitmap(
1190 gc::accounting::ContinuousSpaceBitmap::Create("Relocate bitmap",
1191 target_base,
1192 image_header.GetImageSize()));
1193 FixupObjectVisitor fixup_object_visitor(visited_bitmap.get(),
1194 pointer_size,
1195 boot_image,
1196 boot_oat,
1197 app_image,
1198 app_oat);
1199 TimingLogger::ScopedTiming timing("Fixup classes", &logger);
1200 // Fixup objects may read fields in the boot image, use the mutator lock here for sanity. Though
1201 // its probably not required.
1202 ScopedObjectAccess soa(Thread::Current());
1203 timing.NewTiming("Fixup objects");
1204 bitmap->VisitMarkedRange(objects_begin, objects_end, fixup_object_visitor);
1205 // Fixup image roots.
1206 CHECK(app_image.InSource(reinterpret_cast<uintptr_t>(
1207 image_header.GetImageRoots<kWithoutReadBarrier>())));
1208 image_header.RelocateImageObjects(app_image.Delta());
1209 CHECK_EQ(image_header.GetImageBegin(), target_base);
1210 // Fix up dex cache DexFile pointers.
1211 auto* dex_caches = image_header.GetImageRoot<kWithoutReadBarrier>(ImageHeader::kDexCaches)->
1212 AsObjectArray<mirror::DexCache, kVerifyNone, kWithoutReadBarrier>();
1213 for (int32_t i = 0, count = dex_caches->GetLength(); i < count; ++i) {
1214 mirror::DexCache* dex_cache = dex_caches->Get<kVerifyNone, kWithoutReadBarrier>(i);
1215 // Fix up dex cache pointers.
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07001216 mirror::StringDexCacheType* strings = dex_cache->GetStrings();
Andreas Gampea463b6a2016-08-12 21:53:32 -07001217 if (strings != nullptr) {
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07001218 mirror::StringDexCacheType* new_strings = fixup_adapter.ForwardObject(strings);
Andreas Gampea463b6a2016-08-12 21:53:32 -07001219 if (strings != new_strings) {
1220 dex_cache->SetStrings(new_strings);
1221 }
1222 dex_cache->FixupStrings<kWithoutReadBarrier>(new_strings, fixup_adapter);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001223 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07001224 GcRoot<mirror::Class>* types = dex_cache->GetResolvedTypes();
1225 if (types != nullptr) {
1226 GcRoot<mirror::Class>* new_types = fixup_adapter.ForwardObject(types);
1227 if (types != new_types) {
1228 dex_cache->SetResolvedTypes(new_types);
1229 }
1230 dex_cache->FixupResolvedTypes<kWithoutReadBarrier>(new_types, fixup_adapter);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001231 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07001232 ArtMethod** methods = dex_cache->GetResolvedMethods();
1233 if (methods != nullptr) {
1234 ArtMethod** new_methods = fixup_adapter.ForwardObject(methods);
1235 if (methods != new_methods) {
1236 dex_cache->SetResolvedMethods(new_methods);
1237 }
1238 for (size_t j = 0, num = dex_cache->NumResolvedMethods(); j != num; ++j) {
1239 ArtMethod* orig = mirror::DexCache::GetElementPtrSize(new_methods, j, pointer_size);
1240 ArtMethod* copy = fixup_adapter.ForwardObject(orig);
1241 if (orig != copy) {
1242 mirror::DexCache::SetElementPtrSize(new_methods, j, copy, pointer_size);
1243 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001244 }
1245 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07001246 ArtField** fields = dex_cache->GetResolvedFields();
1247 if (fields != nullptr) {
1248 ArtField** new_fields = fixup_adapter.ForwardObject(fields);
1249 if (fields != new_fields) {
1250 dex_cache->SetResolvedFields(new_fields);
1251 }
1252 for (size_t j = 0, num = dex_cache->NumResolvedFields(); j != num; ++j) {
1253 ArtField* orig = mirror::DexCache::GetElementPtrSize(new_fields, j, pointer_size);
1254 ArtField* copy = fixup_adapter.ForwardObject(orig);
1255 if (orig != copy) {
1256 mirror::DexCache::SetElementPtrSize(new_fields, j, copy, pointer_size);
1257 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001258 }
1259 }
Narayan Kamath7fe56582016-10-14 18:49:12 +01001260
1261 mirror::MethodTypeDexCacheType* method_types = dex_cache->GetResolvedMethodTypes();
1262 if (method_types != nullptr) {
1263 mirror::MethodTypeDexCacheType* new_method_types =
1264 fixup_adapter.ForwardObject(method_types);
1265 if (method_types != new_method_types) {
1266 dex_cache->SetResolvedMethodTypes(new_method_types);
1267 }
1268 dex_cache->FixupResolvedMethodTypes<kWithoutReadBarrier>(new_method_types, fixup_adapter);
1269 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001270 }
1271 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001272 {
1273 // Only touches objects in the app image, no need for mutator lock.
Andreas Gampea463b6a2016-08-12 21:53:32 -07001274 TimingLogger::ScopedTiming timing("Fixup methods", &logger);
1275 FixupArtMethodVisitor method_visitor(fixup_image,
1276 pointer_size,
1277 boot_image,
1278 boot_oat,
1279 app_image,
1280 app_oat);
1281 image_header.VisitPackedArtMethods(&method_visitor, target_base, pointer_size);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001282 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07001283 if (fixup_image) {
1284 {
1285 // Only touches objects in the app image, no need for mutator lock.
1286 TimingLogger::ScopedTiming timing("Fixup fields", &logger);
1287 FixupArtFieldVisitor field_visitor(boot_image, boot_oat, app_image, app_oat);
1288 image_header.VisitPackedArtFields(&field_visitor, target_base);
1289 }
1290 {
1291 TimingLogger::ScopedTiming timing("Fixup imt", &logger);
1292 image_header.VisitPackedImTables(fixup_adapter, target_base, pointer_size);
1293 }
1294 {
1295 TimingLogger::ScopedTiming timing("Fixup conflict tables", &logger);
1296 image_header.VisitPackedImtConflictTables(fixup_adapter, target_base, pointer_size);
1297 }
1298 // In the app image case, the image methods are actually in the boot image.
1299 image_header.RelocateImageMethods(boot_image.Delta());
1300 const auto& class_table_section = image_header.GetImageSection(ImageHeader::kSectionClassTable);
1301 if (class_table_section.Size() > 0u) {
1302 // Note that we require that ReadFromMemory does not make an internal copy of the elements.
1303 // This also relies on visit roots not doing any verification which could fail after we update
1304 // the roots to be the image addresses.
1305 ScopedObjectAccess soa(Thread::Current());
1306 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
1307 ClassTable temp_table;
1308 temp_table.ReadFromMemory(target_base + class_table_section.Offset());
1309 FixupRootVisitor root_visitor(boot_image, boot_oat, app_image, app_oat);
1310 temp_table.VisitRoots(root_visitor);
1311 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001312 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07001313 if (VLOG_IS_ON(image)) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07001314 logger.Dump(LOG_STREAM(INFO));
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001315 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07001316 return true;
Andreas Gampe7fa55782016-06-15 17:45:01 -07001317 }
1318
Andreas Gampea463b6a2016-08-12 21:53:32 -07001319 static std::unique_ptr<OatFile> OpenOatFile(const ImageSpace& image,
1320 const char* image_path,
1321 std::string* error_msg) {
1322 const ImageHeader& image_header = image.GetImageHeader();
1323 std::string oat_filename = ImageHeader::GetOatLocationFromImageLocation(image_path);
Andreas Gampe7fa55782016-06-15 17:45:01 -07001324
Andreas Gampea463b6a2016-08-12 21:53:32 -07001325 CHECK(image_header.GetOatDataBegin() != nullptr);
1326
1327 std::unique_ptr<OatFile> oat_file(OatFile::Open(oat_filename,
1328 oat_filename,
1329 image_header.GetOatDataBegin(),
1330 image_header.GetOatFileBegin(),
1331 !Runtime::Current()->IsAotCompiler(),
1332 /*low_4gb*/false,
1333 nullptr,
1334 error_msg));
1335 if (oat_file == nullptr) {
1336 *error_msg = StringPrintf("Failed to open oat file '%s' referenced from image %s: %s",
1337 oat_filename.c_str(),
1338 image.GetName(),
1339 error_msg->c_str());
Andreas Gampe7fa55782016-06-15 17:45:01 -07001340 return nullptr;
1341 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07001342 uint32_t oat_checksum = oat_file->GetOatHeader().GetChecksum();
1343 uint32_t image_oat_checksum = image_header.GetOatChecksum();
Mathieu Chartier9ff84602016-01-29 12:22:17 -08001344 if (oat_checksum != image_oat_checksum) {
Andreas Gampea463b6a2016-08-12 21:53:32 -07001345 *error_msg = StringPrintf("Failed to match oat file checksum 0x%x to expected oat checksum 0x%x"
1346 " in image %s",
Mathieu Chartier9ff84602016-01-29 12:22:17 -08001347 oat_checksum,
1348 image_oat_checksum,
Andreas Gampea463b6a2016-08-12 21:53:32 -07001349 image.GetName());
Mathieu Chartier9ff84602016-01-29 12:22:17 -08001350 return nullptr;
1351 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07001352 int32_t image_patch_delta = image_header.GetPatchDelta();
1353 int32_t oat_patch_delta = oat_file->GetOatHeader().GetImagePatchDelta();
1354 if (oat_patch_delta != image_patch_delta && !image_header.CompilePic()) {
1355 // We should have already relocated by this point. Bail out.
1356 *error_msg = StringPrintf("Failed to match oat file patch delta %d to expected patch delta %d "
1357 "in image %s",
1358 oat_patch_delta,
1359 image_patch_delta,
1360 image.GetName());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001361 return nullptr;
1362 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07001363
1364 return oat_file;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001365 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07001366
1367 static bool ValidateOatFile(const ImageSpace& space,
1368 const OatFile& oat_file,
1369 std::string* error_msg) {
1370 for (const OatFile::OatDexFile* oat_dex_file : oat_file.GetOatDexFiles()) {
1371 const std::string& dex_file_location = oat_dex_file->GetDexFileLocation();
1372 uint32_t dex_file_location_checksum;
1373 if (!DexFile::GetChecksum(dex_file_location.c_str(), &dex_file_location_checksum, error_msg)) {
1374 *error_msg = StringPrintf("Failed to get checksum of dex file '%s' referenced by image %s: "
1375 "%s",
1376 dex_file_location.c_str(),
1377 space.GetName(),
1378 error_msg->c_str());
1379 return false;
1380 }
1381 if (dex_file_location_checksum != oat_dex_file->GetDexFileLocationChecksum()) {
1382 *error_msg = StringPrintf("ValidateOatFile found checksum mismatch between oat file '%s' and "
1383 "dex file '%s' (0x%x != 0x%x)",
1384 oat_file.GetLocation().c_str(),
1385 dex_file_location.c_str(),
1386 oat_dex_file->GetDexFileLocationChecksum(),
1387 dex_file_location_checksum);
1388 return false;
1389 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001390 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07001391 return true;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001392 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07001393};
Hiroshi Yamauchibd0fb612014-05-20 13:46:00 -07001394
Andreas Gampea463b6a2016-08-12 21:53:32 -07001395static constexpr uint64_t kLowSpaceValue = 50 * MB;
1396static constexpr uint64_t kTmpFsSentinelValue = 384 * MB;
1397
1398// Read the free space of the cache partition and make a decision whether to keep the generated
1399// image. This is to try to mitigate situations where the system might run out of space later.
1400static bool CheckSpace(const std::string& cache_filename, std::string* error_msg) {
1401 // Using statvfs vs statvfs64 because of b/18207376, and it is enough for all practical purposes.
1402 struct statvfs buf;
1403
1404 int res = TEMP_FAILURE_RETRY(statvfs(cache_filename.c_str(), &buf));
1405 if (res != 0) {
1406 // Could not stat. Conservatively tell the system to delete the image.
1407 *error_msg = "Could not stat the filesystem, assuming low-memory situation.";
1408 return false;
Nicolas Geoffray1bc977c2016-01-23 14:15:49 +00001409 }
Nicolas Geoffray1bc977c2016-01-23 14:15:49 +00001410
Andreas Gampea463b6a2016-08-12 21:53:32 -07001411 uint64_t fs_overall_size = buf.f_bsize * static_cast<uint64_t>(buf.f_blocks);
1412 // Zygote is privileged, but other things are not. Use bavail.
1413 uint64_t fs_free_size = buf.f_bsize * static_cast<uint64_t>(buf.f_bavail);
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001414
Andreas Gampea463b6a2016-08-12 21:53:32 -07001415 // Take the overall size as an indicator for a tmpfs, which is being used for the decryption
1416 // environment. We do not want to fail quickening the boot image there, as it is beneficial
1417 // for time-to-UI.
1418 if (fs_overall_size > kTmpFsSentinelValue) {
1419 if (fs_free_size < kLowSpaceValue) {
1420 *error_msg = StringPrintf("Low-memory situation: only %4.2f megabytes available, need at "
1421 "least %" PRIu64 ".",
1422 static_cast<double>(fs_free_size) / MB,
1423 kLowSpaceValue / MB);
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001424 return false;
1425 }
1426 }
1427 return true;
1428}
1429
Andreas Gampea463b6a2016-08-12 21:53:32 -07001430std::unique_ptr<ImageSpace> ImageSpace::CreateBootImage(const char* image_location,
1431 const InstructionSet image_isa,
1432 bool secondary_image,
1433 std::string* error_msg) {
1434 ScopedTrace trace(__FUNCTION__);
1435
1436 // Step 0: Extra zygote work.
1437
1438 // Step 0.a: If we're the zygote, mark boot.
1439 const bool is_zygote = Runtime::Current()->IsZygote();
Robert Sesekbfa1f8d2016-08-15 15:21:09 -04001440 if (is_zygote && !secondary_image && CanWriteToDalvikCache(image_isa)) {
Andreas Gampea463b6a2016-08-12 21:53:32 -07001441 MarkZygoteStart(image_isa, Runtime::Current()->GetZygoteMaxFailedBoots());
1442 }
1443
1444 // Step 0.b: If we're the zygote, check for free space, and prune the cache preemptively,
1445 // if necessary. While the runtime may be fine (it is pretty tolerant to
1446 // out-of-disk-space situations), other parts of the platform are not.
1447 //
1448 // The advantage of doing this proactively is that the later steps are simplified,
1449 // i.e., we do not need to code retries.
1450 std::string system_filename;
1451 bool has_system = false;
1452 std::string cache_filename;
1453 bool has_cache = false;
1454 bool dalvik_cache_exists = false;
1455 bool is_global_cache = true;
1456 std::string dalvik_cache;
1457 bool found_image = FindImageFilenameImpl(image_location,
1458 image_isa,
1459 &has_system,
1460 &system_filename,
1461 &dalvik_cache_exists,
1462 &dalvik_cache,
1463 &is_global_cache,
1464 &has_cache,
1465 &cache_filename);
1466
1467 if (is_zygote && dalvik_cache_exists) {
1468 DCHECK(!dalvik_cache.empty());
1469 std::string local_error_msg;
1470 if (!CheckSpace(dalvik_cache, &local_error_msg)) {
1471 LOG(WARNING) << local_error_msg << " Preemptively pruning the dalvik cache.";
1472 PruneDalvikCache(image_isa);
1473
1474 // Re-evaluate the image.
1475 found_image = FindImageFilenameImpl(image_location,
1476 image_isa,
1477 &has_system,
1478 &system_filename,
1479 &dalvik_cache_exists,
1480 &dalvik_cache,
1481 &is_global_cache,
1482 &has_cache,
1483 &cache_filename);
1484 }
1485 }
1486
1487 // Collect all the errors.
1488 std::vector<std::string> error_msgs;
1489
1490 // Step 1: Check if we have an existing and relocated image.
1491
1492 // Step 1.a: Have files in system and cache. Then they need to match.
1493 if (found_image && has_system && has_cache) {
1494 std::string local_error_msg;
1495 // Check that the files are matching.
1496 if (ChecksumsMatch(system_filename.c_str(), cache_filename.c_str(), &local_error_msg)) {
1497 std::unique_ptr<ImageSpace> relocated_space =
1498 ImageSpaceLoader::Load(image_location,
1499 cache_filename,
1500 is_zygote,
1501 is_global_cache,
Andreas Gampe44c8ed62016-08-19 16:43:00 -07001502 /* validate_oat_file */ false,
Andreas Gampea463b6a2016-08-12 21:53:32 -07001503 &local_error_msg);
1504 if (relocated_space != nullptr) {
1505 return relocated_space;
1506 }
1507 }
1508 error_msgs.push_back(local_error_msg);
1509 }
1510
1511 // Step 1.b: Only have a cache file.
1512 if (found_image && !has_system && has_cache) {
1513 std::string local_error_msg;
1514 std::unique_ptr<ImageSpace> cache_space =
1515 ImageSpaceLoader::Load(image_location,
1516 cache_filename,
1517 is_zygote,
1518 is_global_cache,
Andreas Gampe44c8ed62016-08-19 16:43:00 -07001519 /* validate_oat_file */ true,
Andreas Gampea463b6a2016-08-12 21:53:32 -07001520 &local_error_msg);
1521 if (cache_space != nullptr) {
1522 return cache_space;
1523 }
1524 error_msgs.push_back(local_error_msg);
1525 }
1526
1527 // Step 2: We have an existing image in /system.
1528
1529 // Step 2.a: We are not required to relocate it. Then we can use it directly.
1530 bool relocate = Runtime::Current()->ShouldRelocate();
1531
1532 if (found_image && has_system && !relocate) {
1533 std::string local_error_msg;
1534 std::unique_ptr<ImageSpace> system_space =
1535 ImageSpaceLoader::Load(image_location,
1536 system_filename,
1537 is_zygote,
1538 is_global_cache,
Andreas Gampe44c8ed62016-08-19 16:43:00 -07001539 /* validate_oat_file */ false,
Andreas Gampea463b6a2016-08-12 21:53:32 -07001540 &local_error_msg);
1541 if (system_space != nullptr) {
1542 return system_space;
1543 }
1544 error_msgs.push_back(local_error_msg);
1545 }
1546
1547 // Step 2.b: We require a relocated image. Then we must patch it. This step fails if this is a
1548 // secondary image.
1549 if (found_image && has_system && relocate) {
1550 std::string local_error_msg;
1551 if (!Runtime::Current()->IsImageDex2OatEnabled()) {
1552 local_error_msg = "Patching disabled.";
1553 } else if (secondary_image) {
1554 local_error_msg = "Cannot patch a secondary image.";
Robert Sesekbfa1f8d2016-08-15 15:21:09 -04001555 } else if (ImageCreationAllowed(is_global_cache, image_isa, &local_error_msg)) {
Andreas Gampea463b6a2016-08-12 21:53:32 -07001556 bool patch_success =
1557 RelocateImage(image_location, cache_filename.c_str(), image_isa, &local_error_msg);
1558 if (patch_success) {
1559 std::unique_ptr<ImageSpace> patched_space =
1560 ImageSpaceLoader::Load(image_location,
1561 cache_filename,
1562 is_zygote,
1563 is_global_cache,
Andreas Gampe44c8ed62016-08-19 16:43:00 -07001564 /* validate_oat_file */ false,
Andreas Gampea463b6a2016-08-12 21:53:32 -07001565 &local_error_msg);
1566 if (patched_space != nullptr) {
1567 return patched_space;
1568 }
1569 }
1570 }
1571 error_msgs.push_back(StringPrintf("Cannot relocate image %s to %s: %s",
1572 image_location,
1573 cache_filename.c_str(),
1574 local_error_msg.c_str()));
1575 }
1576
1577 // Step 3: We do not have an existing image in /system, so generate an image into the dalvik
1578 // cache. This step fails if this is a secondary image.
1579 if (!has_system) {
1580 std::string local_error_msg;
1581 if (!Runtime::Current()->IsImageDex2OatEnabled()) {
1582 local_error_msg = "Image compilation disabled.";
1583 } else if (secondary_image) {
1584 local_error_msg = "Cannot compile a secondary image.";
Robert Sesekbfa1f8d2016-08-15 15:21:09 -04001585 } else if (ImageCreationAllowed(is_global_cache, image_isa, &local_error_msg)) {
Andreas Gampea463b6a2016-08-12 21:53:32 -07001586 bool compilation_success = GenerateImage(cache_filename, image_isa, &local_error_msg);
1587 if (compilation_success) {
1588 std::unique_ptr<ImageSpace> compiled_space =
1589 ImageSpaceLoader::Load(image_location,
1590 cache_filename,
1591 is_zygote,
1592 is_global_cache,
Andreas Gampe44c8ed62016-08-19 16:43:00 -07001593 /* validate_oat_file */ false,
Andreas Gampea463b6a2016-08-12 21:53:32 -07001594 &local_error_msg);
1595 if (compiled_space != nullptr) {
1596 return compiled_space;
1597 }
1598 }
1599 }
1600 error_msgs.push_back(StringPrintf("Cannot compile image to %s: %s",
1601 cache_filename.c_str(),
1602 local_error_msg.c_str()));
1603 }
1604
1605 // We failed. Prune the cache the free up space, create a compound error message and return no
1606 // image.
1607 PruneDalvikCache(image_isa);
1608
1609 std::ostringstream oss;
1610 bool first = true;
Andreas Gampe4c481a42016-11-03 08:21:59 -07001611 for (const auto& msg : error_msgs) {
Andreas Gampea463b6a2016-08-12 21:53:32 -07001612 if (!first) {
1613 oss << "\n ";
1614 }
1615 oss << msg;
1616 }
1617 *error_msg = oss.str();
1618
1619 return nullptr;
1620}
1621
Andreas Gampe2bd84282016-12-05 12:37:36 -08001622bool ImageSpace::LoadBootImage(const std::string& image_file_name,
1623 const InstructionSet image_instruction_set,
1624 std::vector<space::ImageSpace*>* boot_image_spaces,
1625 uint8_t** oat_file_end) {
1626 DCHECK(boot_image_spaces != nullptr);
1627 DCHECK(boot_image_spaces->empty());
1628 DCHECK(oat_file_end != nullptr);
1629 DCHECK_NE(image_instruction_set, InstructionSet::kNone);
1630
1631 if (image_file_name.empty()) {
1632 return false;
1633 }
1634
1635 // For code reuse, handle this like a work queue.
1636 std::vector<std::string> image_file_names;
1637 image_file_names.push_back(image_file_name);
1638
1639 bool error = false;
1640 uint8_t* oat_file_end_tmp = *oat_file_end;
1641
1642 for (size_t index = 0; index < image_file_names.size(); ++index) {
1643 std::string& image_name = image_file_names[index];
1644 std::string error_msg;
1645 std::unique_ptr<space::ImageSpace> boot_image_space_uptr = CreateBootImage(
1646 image_name.c_str(),
1647 image_instruction_set,
1648 index > 0,
1649 &error_msg);
1650 if (boot_image_space_uptr != nullptr) {
1651 space::ImageSpace* boot_image_space = boot_image_space_uptr.release();
1652 boot_image_spaces->push_back(boot_image_space);
1653 // Oat files referenced by image files immediately follow them in memory, ensure alloc space
1654 // isn't going to get in the middle
1655 uint8_t* oat_file_end_addr = boot_image_space->GetImageHeader().GetOatFileEnd();
1656 CHECK_GT(oat_file_end_addr, boot_image_space->End());
1657 oat_file_end_tmp = AlignUp(oat_file_end_addr, kPageSize);
1658
1659 if (index == 0) {
1660 // If this was the first space, check whether there are more images to load.
1661 const OatFile* boot_oat_file = boot_image_space->GetOatFile();
1662 if (boot_oat_file == nullptr) {
1663 continue;
1664 }
1665
1666 const OatHeader& boot_oat_header = boot_oat_file->GetOatHeader();
1667 const char* boot_classpath =
1668 boot_oat_header.GetStoreValueByKey(OatHeader::kBootClassPathKey);
1669 if (boot_classpath == nullptr) {
1670 continue;
1671 }
1672
1673 ExtractMultiImageLocations(image_file_name, boot_classpath, &image_file_names);
1674 }
1675 } else {
1676 error = true;
1677 LOG(ERROR) << "Could not create image space with image file '" << image_file_name << "'. "
1678 << "Attempting to fall back to imageless running. Error was: " << error_msg
1679 << "\nAttempted image: " << image_name;
1680 break;
1681 }
1682 }
1683
1684 if (error) {
1685 // Remove already loaded spaces.
1686 for (space::Space* loaded_space : *boot_image_spaces) {
1687 delete loaded_space;
1688 }
1689 boot_image_spaces->clear();
1690 return false;
1691 }
1692
1693 *oat_file_end = oat_file_end_tmp;
1694 return true;
1695}
1696
Andreas Gampea463b6a2016-08-12 21:53:32 -07001697std::unique_ptr<ImageSpace> ImageSpace::CreateFromAppImage(const char* image,
1698 const OatFile* oat_file,
1699 std::string* error_msg) {
1700 return ImageSpaceLoader::Init(image,
1701 image,
1702 /*validate_oat_file*/false,
1703 oat_file,
1704 /*out*/error_msg);
1705}
1706
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001707const OatFile* ImageSpace::GetOatFile() const {
Andreas Gampe88da3b02015-06-12 20:38:49 -07001708 return oat_file_non_owned_;
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001709}
1710
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -07001711std::unique_ptr<const OatFile> ImageSpace::ReleaseOatFile() {
1712 CHECK(oat_file_ != nullptr);
1713 return std::move(oat_file_);
Ian Rogers1d54e732013-05-02 21:10:01 -07001714}
1715
Ian Rogers1d54e732013-05-02 21:10:01 -07001716void ImageSpace::Dump(std::ostream& os) const {
1717 os << GetType()
Mathieu Chartier590fee92013-09-13 13:46:47 -07001718 << " begin=" << reinterpret_cast<void*>(Begin())
Ian Rogers1d54e732013-05-02 21:10:01 -07001719 << ",end=" << reinterpret_cast<void*>(End())
1720 << ",size=" << PrettySize(Size())
1721 << ",name=\"" << GetName() << "\"]";
1722}
1723
Mathieu Chartier866d8742016-09-21 15:24:18 -07001724std::string ImageSpace::GetMultiImageBootClassPath(
1725 const std::vector<const char*>& dex_locations,
1726 const std::vector<const char*>& oat_filenames,
1727 const std::vector<const char*>& image_filenames) {
1728 DCHECK_GT(oat_filenames.size(), 1u);
1729 // If the image filename was adapted (e.g., for our tests), we need to change this here,
1730 // too, but need to strip all path components (they will be re-established when loading).
1731 std::ostringstream bootcp_oss;
1732 bool first_bootcp = true;
1733 for (size_t i = 0; i < dex_locations.size(); ++i) {
1734 if (!first_bootcp) {
1735 bootcp_oss << ":";
1736 }
1737
1738 std::string dex_loc = dex_locations[i];
1739 std::string image_filename = image_filenames[i];
1740
1741 // Use the dex_loc path, but the image_filename name (without path elements).
1742 size_t dex_last_slash = dex_loc.rfind('/');
1743
1744 // npos is max(size_t). That makes this a bit ugly.
1745 size_t image_last_slash = image_filename.rfind('/');
1746 size_t image_last_at = image_filename.rfind('@');
1747 size_t image_last_sep = (image_last_slash == std::string::npos)
1748 ? image_last_at
1749 : (image_last_at == std::string::npos)
1750 ? std::string::npos
1751 : std::max(image_last_slash, image_last_at);
1752 // Note: whenever image_last_sep == npos, +1 overflow means using the full string.
1753
1754 if (dex_last_slash == std::string::npos) {
1755 dex_loc = image_filename.substr(image_last_sep + 1);
1756 } else {
1757 dex_loc = dex_loc.substr(0, dex_last_slash + 1) +
1758 image_filename.substr(image_last_sep + 1);
1759 }
1760
1761 // Image filenames already end with .art, no need to replace.
1762
1763 bootcp_oss << dex_loc;
1764 first_bootcp = false;
1765 }
1766 return bootcp_oss.str();
1767}
1768
1769void ImageSpace::ExtractMultiImageLocations(const std::string& input_image_file_name,
1770 const std::string& boot_classpath,
1771 std::vector<std::string>* image_file_names) {
Andreas Gampe8994a042015-12-30 19:03:17 +00001772 DCHECK(image_file_names != nullptr);
1773
1774 std::vector<std::string> images;
1775 Split(boot_classpath, ':', &images);
1776
1777 // Add the rest into the list. We have to adjust locations, possibly:
1778 //
1779 // For example, image_file_name is /a/b/c/d/e.art
1780 // images[0] is f/c/d/e.art
1781 // ----------------------------------------------
1782 // images[1] is g/h/i/j.art -> /a/b/h/i/j.art
Mathieu Chartier8b8f6d62016-03-08 16:50:20 -08001783 const std::string& first_image = images[0];
1784 // Length of common suffix.
1785 size_t common = 0;
1786 while (common < input_image_file_name.size() &&
1787 common < first_image.size() &&
1788 *(input_image_file_name.end() - common - 1) == *(first_image.end() - common - 1)) {
1789 ++common;
Andreas Gampe8994a042015-12-30 19:03:17 +00001790 }
Mathieu Chartier8b8f6d62016-03-08 16:50:20 -08001791 // We want to replace the prefix of the input image with the prefix of the boot class path.
1792 // This handles the case where the image file contains @ separators.
1793 // Example image_file_name is oats/system@framework@boot.art
1794 // images[0] is .../arm/boot.art
1795 // means that the image name prefix will be oats/system@framework@
1796 // so that the other images are openable.
1797 const size_t old_prefix_length = first_image.size() - common;
1798 const std::string new_prefix = input_image_file_name.substr(
1799 0,
1800 input_image_file_name.size() - common);
Andreas Gampe8994a042015-12-30 19:03:17 +00001801
1802 // Apply pattern to images[1] .. images[n].
1803 for (size_t i = 1; i < images.size(); ++i) {
Mathieu Chartier8b8f6d62016-03-08 16:50:20 -08001804 const std::string& image = images[i];
1805 CHECK_GT(image.length(), old_prefix_length);
1806 std::string suffix = image.substr(old_prefix_length);
1807 image_file_names->push_back(new_prefix + suffix);
Andreas Gampe8994a042015-12-30 19:03:17 +00001808 }
1809}
1810
Mathieu Chartierd5f3f322016-03-21 14:05:56 -07001811void ImageSpace::DumpSections(std::ostream& os) const {
1812 const uint8_t* base = Begin();
1813 const ImageHeader& header = GetImageHeader();
1814 for (size_t i = 0; i < ImageHeader::kSectionCount; ++i) {
1815 auto section_type = static_cast<ImageHeader::ImageSections>(i);
1816 const ImageSection& section = header.GetImageSection(section_type);
1817 os << section_type << " " << reinterpret_cast<const void*>(base + section.Offset())
1818 << "-" << reinterpret_cast<const void*>(base + section.End()) << "\n";
1819 }
1820}
1821
Ian Rogers1d54e732013-05-02 21:10:01 -07001822} // namespace space
1823} // namespace gc
1824} // namespace art