blob: 5ff1cb7a2edd771ffdb4b771b4a1b588ade0201c [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"
Ian Rogersc7dd2952014-10-21 23:31:19 -070026#include "base/macros.h"
Brian Carlstrom56d947f2013-07-15 13:14:23 -070027#include "base/stl_util.h"
Narayan Kamathd1c606f2014-06-09 16:50:19 +010028#include "base/scoped_flock.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080029#include "base/systrace.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010030#include "base/time_utils.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070031#include "gc/accounting/space_bitmap-inl.h"
Mathieu Chartier4a26f172016-01-26 14:26:18 -080032#include "image-inl.h"
Andreas Gampebec63582015-11-20 19:26:51 -080033#include "image_space_fs.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070034#include "mirror/class-inl.h"
35#include "mirror/object-inl.h"
Brian Carlstrom56d947f2013-07-15 13:14:23 -070036#include "oat_file.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070037#include "os.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070038#include "space-inl.h"
39#include "utils.h"
40
41namespace art {
42namespace gc {
43namespace space {
44
Ian Rogersef7d42f2014-01-06 12:55:46 -080045Atomic<uint32_t> ImageSpace::bitmap_index_(0);
Ian Rogers1d54e732013-05-02 21:10:01 -070046
Jeff Haodcdc85b2015-12-04 14:06:18 -080047ImageSpace::ImageSpace(const std::string& image_filename,
48 const char* image_location,
49 MemMap* mem_map,
50 accounting::ContinuousSpaceBitmap* live_bitmap,
Mathieu Chartier2d124ec2016-01-05 18:03:15 -080051 uint8_t* end)
52 : MemMapSpace(image_filename,
53 mem_map,
54 mem_map->Begin(),
55 end,
56 end,
Narayan Kamath52f84882014-05-02 10:10:39 +010057 kGcRetentionPolicyNeverCollect),
Jeff Haodcdc85b2015-12-04 14:06:18 -080058 oat_file_non_owned_(nullptr),
Mathieu Chartier2d124ec2016-01-05 18:03:15 -080059 image_location_(image_location) {
Mathieu Chartier590fee92013-09-13 13:46:47 -070060 DCHECK(live_bitmap != nullptr);
Mathieu Chartier31e89252013-08-28 11:29:12 -070061 live_bitmap_.reset(live_bitmap);
Ian Rogers1d54e732013-05-02 21:10:01 -070062}
63
Alex Lightcf4bf382014-07-24 11:29:14 -070064static int32_t ChooseRelocationOffsetDelta(int32_t min_delta, int32_t max_delta) {
65 CHECK_ALIGNED(min_delta, kPageSize);
66 CHECK_ALIGNED(max_delta, kPageSize);
67 CHECK_LT(min_delta, max_delta);
68
Alex Light15324762015-11-19 11:03:10 -080069 int32_t r = GetRandomNumber<int32_t>(min_delta, max_delta);
Alex Lightcf4bf382014-07-24 11:29:14 -070070 if (r % 2 == 0) {
71 r = RoundUp(r, kPageSize);
72 } else {
73 r = RoundDown(r, kPageSize);
74 }
75 CHECK_LE(min_delta, r);
76 CHECK_GE(max_delta, r);
77 CHECK_ALIGNED(r, kPageSize);
78 return r;
79}
80
Alex Light25396132014-08-27 15:37:23 -070081static bool GenerateImage(const std::string& image_filename, InstructionSet image_isa,
82 std::string* error_msg) {
Brian Carlstrom56d947f2013-07-15 13:14:23 -070083 const std::string boot_class_path_string(Runtime::Current()->GetBootClassPathString());
84 std::vector<std::string> boot_class_path;
Ian Rogers6f3dbba2014-10-14 17:41:57 -070085 Split(boot_class_path_string, ':', &boot_class_path);
Brian Carlstrom56d947f2013-07-15 13:14:23 -070086 if (boot_class_path.empty()) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -070087 *error_msg = "Failed to generate image because no boot class path specified";
88 return false;
Brian Carlstrom56d947f2013-07-15 13:14:23 -070089 }
Alex Light25396132014-08-27 15:37:23 -070090 // We should clean up so we are more likely to have room for the image.
91 if (Runtime::Current()->IsZygote()) {
Andreas Gampe3c13a792014-09-18 20:56:04 -070092 LOG(INFO) << "Pruning dalvik-cache since we are generating an image and will need to recompile";
Narayan Kamath28bc9872014-11-07 17:46:28 +000093 PruneDalvikCache(image_isa);
Alex Light25396132014-08-27 15:37:23 -070094 }
Brian Carlstrom56d947f2013-07-15 13:14:23 -070095
Mathieu Chartier8bbc8c02013-07-31 16:27:01 -070096 std::vector<std::string> arg_vector;
Brian Carlstrom56d947f2013-07-15 13:14:23 -070097
Tsu Chiang Chuang12e6d742014-05-22 10:22:25 -070098 std::string dex2oat(Runtime::Current()->GetCompilerExecutable());
Mathieu Chartier08d7d442013-07-31 18:08:51 -070099 arg_vector.push_back(dex2oat);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700100
101 std::string image_option_string("--image=");
Narayan Kamath52f84882014-05-02 10:10:39 +0100102 image_option_string += image_filename;
Mathieu Chartier8bbc8c02013-07-31 16:27:01 -0700103 arg_vector.push_back(image_option_string);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700104
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700105 for (size_t i = 0; i < boot_class_path.size(); i++) {
Mathieu Chartier8bbc8c02013-07-31 16:27:01 -0700106 arg_vector.push_back(std::string("--dex-file=") + boot_class_path[i]);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700107 }
108
109 std::string oat_file_option_string("--oat-file=");
Brian Carlstrom2f1e15c2014-10-27 16:27:06 -0700110 oat_file_option_string += ImageHeader::GetOatLocationFromImageLocation(image_filename);
Mathieu Chartier8bbc8c02013-07-31 16:27:01 -0700111 arg_vector.push_back(oat_file_option_string);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700112
Sebastien Hertz0de11332015-05-13 12:14:05 +0200113 // Note: we do not generate a fully debuggable boot image so we do not pass the
114 // compiler flag --debuggable here.
115
Igor Murashkinb1d8c312015-08-04 11:18:43 -0700116 Runtime::Current()->AddCurrentRuntimeFeaturesAsDex2OatArguments(&arg_vector);
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700117 CHECK_EQ(image_isa, kRuntimeISA)
118 << "We should always be generating an image for the current isa.";
Ian Rogers8afeb852014-04-02 14:55:49 -0700119
Alex Lightcf4bf382014-07-24 11:29:14 -0700120 int32_t base_offset = ChooseRelocationOffsetDelta(ART_BASE_ADDRESS_MIN_DELTA,
121 ART_BASE_ADDRESS_MAX_DELTA);
122 LOG(INFO) << "Using an offset of 0x" << std::hex << base_offset << " from default "
123 << "art base address of 0x" << std::hex << ART_BASE_ADDRESS;
124 arg_vector.push_back(StringPrintf("--base=0x%x", ART_BASE_ADDRESS + base_offset));
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700125
Brian Carlstrom57309db2014-07-30 15:13:25 -0700126 if (!kIsTargetBuild) {
Mathieu Chartier8bbc8c02013-07-31 16:27:01 -0700127 arg_vector.push_back("--host");
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700128 }
129
Brian Carlstrom6449c622014-02-10 23:48:36 -0800130 const std::vector<std::string>& compiler_options = Runtime::Current()->GetImageCompilerOptions();
Brian Carlstrom2ec65202014-03-03 15:16:37 -0800131 for (size_t i = 0; i < compiler_options.size(); ++i) {
Brian Carlstrom6449c622014-02-10 23:48:36 -0800132 arg_vector.push_back(compiler_options[i].c_str());
133 }
134
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700135 std::string command_line(Join(arg_vector, ' '));
136 LOG(INFO) << "GenerateImage: " << command_line;
Brian Carlstrom6449c622014-02-10 23:48:36 -0800137 return Exec(arg_vector, error_msg);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700138}
139
Narayan Kamath52f84882014-05-02 10:10:39 +0100140bool ImageSpace::FindImageFilename(const char* image_location,
141 const InstructionSet image_isa,
Alex Lighta59dd802014-07-02 16:28:08 -0700142 std::string* system_filename,
143 bool* has_system,
144 std::string* cache_filename,
145 bool* dalvik_cache_exists,
Andreas Gampe3c13a792014-09-18 20:56:04 -0700146 bool* has_cache,
147 bool* is_global_cache) {
Alex Lighta59dd802014-07-02 16:28:08 -0700148 *has_system = false;
149 *has_cache = false;
Brian Carlstrom0e12bdc2014-05-14 17:44:28 -0700150 // image_location = /system/framework/boot.art
151 // system_image_location = /system/framework/<image_isa>/boot.art
152 std::string system_image_filename(GetSystemImageFilename(image_location, image_isa));
153 if (OS::FileExists(system_image_filename.c_str())) {
Alex Lighta59dd802014-07-02 16:28:08 -0700154 *system_filename = system_image_filename;
155 *has_system = true;
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700156 }
Narayan Kamath52f84882014-05-02 10:10:39 +0100157
Alex Lighta59dd802014-07-02 16:28:08 -0700158 bool have_android_data = false;
159 *dalvik_cache_exists = false;
160 std::string dalvik_cache;
161 GetDalvikCache(GetInstructionSetString(image_isa), true, &dalvik_cache,
Andreas Gampe3c13a792014-09-18 20:56:04 -0700162 &have_android_data, dalvik_cache_exists, is_global_cache);
Narayan Kamath52f84882014-05-02 10:10:39 +0100163
Alex Lighta59dd802014-07-02 16:28:08 -0700164 if (have_android_data && *dalvik_cache_exists) {
165 // Always set output location even if it does not exist,
166 // so that the caller knows where to create the image.
167 //
168 // image_location = /system/framework/boot.art
169 // *image_filename = /data/dalvik-cache/<image_isa>/boot.art
170 std::string error_msg;
171 if (!GetDalvikCacheFilename(image_location, dalvik_cache.c_str(), cache_filename, &error_msg)) {
172 LOG(WARNING) << error_msg;
173 return *has_system;
174 }
175 *has_cache = OS::FileExists(cache_filename->c_str());
176 }
177 return *has_system || *has_cache;
178}
179
180static bool ReadSpecificImageHeader(const char* filename, ImageHeader* image_header) {
181 std::unique_ptr<File> image_file(OS::OpenFileForReading(filename));
182 if (image_file.get() == nullptr) {
183 return false;
184 }
185 const bool success = image_file->ReadFully(image_header, sizeof(ImageHeader));
186 if (!success || !image_header->IsValid()) {
187 return false;
188 }
189 return true;
190}
191
Alex Light6e183f22014-07-18 14:57:04 -0700192// Relocate the image at image_location to dest_filename and relocate it by a random amount.
193static bool RelocateImage(const char* image_location, const char* dest_filename,
Alex Lighta59dd802014-07-02 16:28:08 -0700194 InstructionSet isa, std::string* error_msg) {
Alex Light25396132014-08-27 15:37:23 -0700195 // We should clean up so we are more likely to have room for the image.
196 if (Runtime::Current()->IsZygote()) {
197 LOG(INFO) << "Pruning dalvik-cache since we are relocating an image and will need to recompile";
Narayan Kamath28bc9872014-11-07 17:46:28 +0000198 PruneDalvikCache(isa);
Alex Light25396132014-08-27 15:37:23 -0700199 }
200
Alex Lighta59dd802014-07-02 16:28:08 -0700201 std::string patchoat(Runtime::Current()->GetPatchoatExecutable());
202
203 std::string input_image_location_arg("--input-image-location=");
204 input_image_location_arg += image_location;
205
206 std::string output_image_filename_arg("--output-image-file=");
207 output_image_filename_arg += dest_filename;
208
Alex Lighta59dd802014-07-02 16:28:08 -0700209 std::string instruction_set_arg("--instruction-set=");
210 instruction_set_arg += GetInstructionSetString(isa);
211
212 std::string base_offset_arg("--base-offset-delta=");
213 StringAppendF(&base_offset_arg, "%d", ChooseRelocationOffsetDelta(ART_BASE_ADDRESS_MIN_DELTA,
214 ART_BASE_ADDRESS_MAX_DELTA));
215
216 std::vector<std::string> argv;
217 argv.push_back(patchoat);
218
219 argv.push_back(input_image_location_arg);
220 argv.push_back(output_image_filename_arg);
221
Alex Lighta59dd802014-07-02 16:28:08 -0700222 argv.push_back(instruction_set_arg);
223 argv.push_back(base_offset_arg);
224
225 std::string command_line(Join(argv, ' '));
226 LOG(INFO) << "RelocateImage: " << command_line;
227 return Exec(argv, error_msg);
228}
229
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700230static ImageHeader* ReadSpecificImageHeader(const char* filename, std::string* error_msg) {
Alex Lighta59dd802014-07-02 16:28:08 -0700231 std::unique_ptr<ImageHeader> hdr(new ImageHeader);
232 if (!ReadSpecificImageHeader(filename, hdr.get())) {
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700233 *error_msg = StringPrintf("Unable to read image header for %s", filename);
Alex Lighta59dd802014-07-02 16:28:08 -0700234 return nullptr;
235 }
236 return hdr.release();
Narayan Kamath52f84882014-05-02 10:10:39 +0100237}
238
239ImageHeader* ImageSpace::ReadImageHeaderOrDie(const char* image_location,
240 const InstructionSet image_isa) {
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700241 std::string error_msg;
242 ImageHeader* image_header = ReadImageHeader(image_location, image_isa, &error_msg);
243 if (image_header == nullptr) {
244 LOG(FATAL) << error_msg;
245 }
246 return image_header;
247}
248
249ImageHeader* ImageSpace::ReadImageHeader(const char* image_location,
250 const InstructionSet image_isa,
251 std::string* error_msg) {
Alex Lighta59dd802014-07-02 16:28:08 -0700252 std::string system_filename;
253 bool has_system = false;
254 std::string cache_filename;
255 bool has_cache = false;
256 bool dalvik_cache_exists = false;
Andreas Gampe3c13a792014-09-18 20:56:04 -0700257 bool is_global_cache = false;
Alex Lighta59dd802014-07-02 16:28:08 -0700258 if (FindImageFilename(image_location, image_isa, &system_filename, &has_system,
Andreas Gampe3c13a792014-09-18 20:56:04 -0700259 &cache_filename, &dalvik_cache_exists, &has_cache, &is_global_cache)) {
Alex Lighta59dd802014-07-02 16:28:08 -0700260 if (Runtime::Current()->ShouldRelocate()) {
261 if (has_system && has_cache) {
262 std::unique_ptr<ImageHeader> sys_hdr(new ImageHeader);
263 std::unique_ptr<ImageHeader> cache_hdr(new ImageHeader);
264 if (!ReadSpecificImageHeader(system_filename.c_str(), sys_hdr.get())) {
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700265 *error_msg = StringPrintf("Unable to read image header for %s at %s",
266 image_location, system_filename.c_str());
Alex Lighta59dd802014-07-02 16:28:08 -0700267 return nullptr;
268 }
269 if (!ReadSpecificImageHeader(cache_filename.c_str(), cache_hdr.get())) {
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700270 *error_msg = StringPrintf("Unable to read image header for %s at %s",
271 image_location, cache_filename.c_str());
Alex Lighta59dd802014-07-02 16:28:08 -0700272 return nullptr;
273 }
274 if (sys_hdr->GetOatChecksum() != cache_hdr->GetOatChecksum()) {
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700275 *error_msg = StringPrintf("Unable to find a relocated version of image file %s",
276 image_location);
Alex Lighta59dd802014-07-02 16:28:08 -0700277 return nullptr;
278 }
279 return cache_hdr.release();
280 } else if (!has_cache) {
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700281 *error_msg = StringPrintf("Unable to find a relocated version of image file %s",
282 image_location);
Alex Lighta59dd802014-07-02 16:28:08 -0700283 return nullptr;
284 } else if (!has_system && has_cache) {
285 // This can probably just use the cache one.
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700286 return ReadSpecificImageHeader(cache_filename.c_str(), error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -0700287 }
288 } else {
289 // We don't want to relocate, Just pick the appropriate one if we have it and return.
290 if (has_system && has_cache) {
291 // We want the cache if the checksum matches, otherwise the system.
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700292 std::unique_ptr<ImageHeader> system(ReadSpecificImageHeader(system_filename.c_str(),
293 error_msg));
294 std::unique_ptr<ImageHeader> cache(ReadSpecificImageHeader(cache_filename.c_str(),
295 error_msg));
Alex Lighta59dd802014-07-02 16:28:08 -0700296 if (system.get() == nullptr ||
297 (cache.get() != nullptr && cache->GetOatChecksum() == system->GetOatChecksum())) {
298 return cache.release();
299 } else {
300 return system.release();
301 }
302 } else if (has_system) {
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700303 return ReadSpecificImageHeader(system_filename.c_str(), error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -0700304 } else if (has_cache) {
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700305 return ReadSpecificImageHeader(cache_filename.c_str(), error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -0700306 }
Narayan Kamath52f84882014-05-02 10:10:39 +0100307 }
Narayan Kamath52f84882014-05-02 10:10:39 +0100308 }
309
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700310 *error_msg = StringPrintf("Unable to find image file for %s", image_location);
Narayan Kamath52f84882014-05-02 10:10:39 +0100311 return nullptr;
312}
313
Alex Lighta59dd802014-07-02 16:28:08 -0700314static bool ChecksumsMatch(const char* image_a, const char* image_b) {
315 ImageHeader hdr_a;
316 ImageHeader hdr_b;
317 return ReadSpecificImageHeader(image_a, &hdr_a) && ReadSpecificImageHeader(image_b, &hdr_b)
318 && hdr_a.GetOatChecksum() == hdr_b.GetOatChecksum();
319}
320
Andreas Gampe3c13a792014-09-18 20:56:04 -0700321static bool ImageCreationAllowed(bool is_global_cache, std::string* error_msg) {
322 // Anyone can write into a "local" cache.
323 if (!is_global_cache) {
324 return true;
325 }
326
327 // Only the zygote is allowed to create the global boot image.
328 if (Runtime::Current()->IsZygote()) {
329 return true;
330 }
331
332 *error_msg = "Only the zygote can create the global boot image.";
333 return false;
334}
335
Andreas Gampe70be1fb2014-10-31 16:45:19 -0700336static constexpr uint64_t kLowSpaceValue = 50 * MB;
337static constexpr uint64_t kTmpFsSentinelValue = 384 * MB;
338
339// Read the free space of the cache partition and make a decision whether to keep the generated
340// image. This is to try to mitigate situations where the system might run out of space later.
341static bool CheckSpace(const std::string& cache_filename, std::string* error_msg) {
342 // Using statvfs vs statvfs64 because of b/18207376, and it is enough for all practical purposes.
343 struct statvfs buf;
344
345 int res = TEMP_FAILURE_RETRY(statvfs(cache_filename.c_str(), &buf));
346 if (res != 0) {
347 // Could not stat. Conservatively tell the system to delete the image.
348 *error_msg = "Could not stat the filesystem, assuming low-memory situation.";
349 return false;
350 }
351
352 uint64_t fs_overall_size = buf.f_bsize * static_cast<uint64_t>(buf.f_blocks);
353 // Zygote is privileged, but other things are not. Use bavail.
354 uint64_t fs_free_size = buf.f_bsize * static_cast<uint64_t>(buf.f_bavail);
355
356 // Take the overall size as an indicator for a tmpfs, which is being used for the decryption
357 // environment. We do not want to fail quickening the boot image there, as it is beneficial
358 // for time-to-UI.
359 if (fs_overall_size > kTmpFsSentinelValue) {
360 if (fs_free_size < kLowSpaceValue) {
361 *error_msg = StringPrintf("Low-memory situation: only %4.2f megabytes available after image"
362 " generation, need at least %" PRIu64 ".",
363 static_cast<double>(fs_free_size) / MB,
364 kLowSpaceValue / MB);
365 return false;
366 }
367 }
368 return true;
369}
370
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800371ImageSpace* ImageSpace::CreateBootImage(const char* image_location,
372 const InstructionSet image_isa,
373 bool secondary_image,
374 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800375 ScopedTrace trace(__FUNCTION__);
Alex Lighta59dd802014-07-02 16:28:08 -0700376 std::string system_filename;
377 bool has_system = false;
378 std::string cache_filename;
379 bool has_cache = false;
380 bool dalvik_cache_exists = false;
Andreas Gampe3c13a792014-09-18 20:56:04 -0700381 bool is_global_cache = true;
Andreas Gampebec63582015-11-20 19:26:51 -0800382 bool found_image = FindImageFilename(image_location, image_isa, &system_filename,
383 &has_system, &cache_filename, &dalvik_cache_exists,
384 &has_cache, &is_global_cache);
385
386 // If we're starting with the global cache, and we're the zygote, try to see whether there are
387 // OTA artifacts from the A/B OTA preopting to move over.
388 // (It is structurally simpler to check this here, instead of complicating the compile/relocate
389 // logic below.)
390 const bool is_zygote = Runtime::Current()->IsZygote();
391 if (is_global_cache && is_zygote) {
392 VLOG(startup) << "Checking for A/B OTA data.";
393 TryMoveOTAArtifacts(cache_filename, dalvik_cache_exists);
394
395 // Retry. There are two cases where the old info is outdated:
396 // * There wasn't a boot image before (e.g., some failure on boot), but now the OTA preopted
397 // image has been moved in-place.
398 // * There was a boot image before, and we tried to move the OTA preopted image, but a failure
399 // happened and there is no file anymore.
400 found_image = FindImageFilename(image_location,
401 image_isa,
402 &system_filename,
403 &has_system,
404 &cache_filename,
405 &dalvik_cache_exists,
406 &has_cache,
407 &is_global_cache);
408 }
Narayan Kamathd1c606f2014-06-09 16:50:19 +0100409
Jeff Haodcdc85b2015-12-04 14:06:18 -0800410 if (Runtime::Current()->IsZygote() && !secondary_image) {
Narayan Kamath5a2be3f2015-02-16 13:51:51 +0000411 MarkZygoteStart(image_isa, Runtime::Current()->GetZygoteMaxFailedBoots());
Narayan Kamath28bc9872014-11-07 17:46:28 +0000412 }
413
Alex Lighta59dd802014-07-02 16:28:08 -0700414 ImageSpace* space;
415 bool relocate = Runtime::Current()->ShouldRelocate();
Alex Light64ad14d2014-08-19 14:23:13 -0700416 bool can_compile = Runtime::Current()->IsImageDex2OatEnabled();
Narayan Kamathd1c606f2014-06-09 16:50:19 +0100417 if (found_image) {
Alex Lighta59dd802014-07-02 16:28:08 -0700418 const std::string* image_filename;
419 bool is_system = false;
420 bool relocated_version_used = false;
421 if (relocate) {
Alex Light64ad14d2014-08-19 14:23:13 -0700422 if (!dalvik_cache_exists) {
423 *error_msg = StringPrintf("Requiring relocation for image '%s' at '%s' but we do not have "
424 "any dalvik_cache to find/place it in.",
425 image_location, system_filename.c_str());
426 return nullptr;
427 }
Alex Lighta59dd802014-07-02 16:28:08 -0700428 if (has_system) {
429 if (has_cache && ChecksumsMatch(system_filename.c_str(), cache_filename.c_str())) {
430 // We already have a relocated version
431 image_filename = &cache_filename;
432 relocated_version_used = true;
433 } else {
434 // We cannot have a relocated version, Relocate the system one and use it.
Andreas Gampe3c13a792014-09-18 20:56:04 -0700435
436 std::string reason;
437 bool success;
438
439 // Check whether we are allowed to relocate.
440 if (!can_compile) {
441 reason = "Image dex2oat disabled by -Xnoimage-dex2oat.";
442 success = false;
443 } else if (!ImageCreationAllowed(is_global_cache, &reason)) {
444 // Whether we can write to the cache.
445 success = false;
Andreas Gampe8994a042015-12-30 19:03:17 +0000446 } else if (secondary_image) {
Jeff Haoab4a4d22016-03-14 18:50:49 -0700447 if (Runtime::Current()->IsZygote()) {
448 // Secondary image is out of date. Clear cache and exit to let it retry from scratch.
449 LOG(ERROR) << "Cannot patch secondary image '" << image_location
450 << "', clearing dalvik_cache and restarting zygote.";
451 PruneDalvikCache(image_isa);
452 _exit(1);
453 } else {
454 reason = "Should not have to patch secondary image.";
455 success = false;
456 }
Andreas Gampe3c13a792014-09-18 20:56:04 -0700457 } else {
458 // Try to relocate.
459 success = RelocateImage(image_location, cache_filename.c_str(), image_isa, &reason);
460 }
461
462 if (success) {
Alex Lighta59dd802014-07-02 16:28:08 -0700463 relocated_version_used = true;
464 image_filename = &cache_filename;
465 } else {
Andreas Gampe3c13a792014-09-18 20:56:04 -0700466 *error_msg = StringPrintf("Unable to relocate image '%s' from '%s' to '%s': %s",
Alex Light64ad14d2014-08-19 14:23:13 -0700467 image_location, system_filename.c_str(),
468 cache_filename.c_str(), reason.c_str());
Brian Carlstrome9105f72014-10-28 15:53:43 -0700469 // We failed to create files, remove any possibly garbage output.
470 // Since ImageCreationAllowed was true above, we are the zygote
471 // and therefore the only process expected to generate these for
472 // the device.
Narayan Kamath28bc9872014-11-07 17:46:28 +0000473 PruneDalvikCache(image_isa);
Alex Lighta59dd802014-07-02 16:28:08 -0700474 return nullptr;
475 }
476 }
477 } else {
478 CHECK(has_cache);
479 // We can just use cache's since it should be fine. This might or might not be relocated.
480 image_filename = &cache_filename;
481 }
482 } else {
483 if (has_system && has_cache) {
484 // Check they have the same cksum. If they do use the cache. Otherwise system.
485 if (ChecksumsMatch(system_filename.c_str(), cache_filename.c_str())) {
486 image_filename = &cache_filename;
487 relocated_version_used = true;
488 } else {
489 image_filename = &system_filename;
Alex Light1a762132014-07-31 09:32:13 -0700490 is_system = true;
Alex Lighta59dd802014-07-02 16:28:08 -0700491 }
492 } else if (has_system) {
493 image_filename = &system_filename;
Alex Light1a762132014-07-31 09:32:13 -0700494 is_system = true;
Alex Lighta59dd802014-07-02 16:28:08 -0700495 } else {
496 CHECK(has_cache);
497 image_filename = &cache_filename;
498 }
499 }
500 {
501 // Note that we must not use the file descriptor associated with
502 // ScopedFlock::GetFile to Init the image file. We want the file
503 // descriptor (and the associated exclusive lock) to be released when
504 // we leave Create.
505 ScopedFlock image_lock;
Alex Light64ad14d2014-08-19 14:23:13 -0700506 image_lock.Init(image_filename->c_str(), error_msg);
Alex Lightb6cabc12014-08-21 09:45:00 -0700507 VLOG(startup) << "Using image file " << image_filename->c_str() << " for image location "
508 << image_location;
Alex Lightb93637a2014-07-31 10:48:46 -0700509 // If we are in /system we can assume the image is good. We can also
510 // assume this if we are using a relocated image (i.e. image checksum
511 // matches) since this is only different by the offset. We need this to
512 // make sure that host tests continue to work.
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800513 // Since we are the boot image, pass null since we load the oat file from the boot image oat
514 // file name.
515 space = ImageSpace::Init(image_filename->c_str(),
516 image_location,
517 !(is_system || relocated_version_used),
518 /* oat_file */nullptr,
519 error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -0700520 }
Narayan Kamath52f84882014-05-02 10:10:39 +0100521 if (space != nullptr) {
522 return space;
523 }
524
Alex Lighta59dd802014-07-02 16:28:08 -0700525 if (relocated_version_used) {
Brian Carlstrome9105f72014-10-28 15:53:43 -0700526 // Something is wrong with the relocated copy (even though checksums match). Cleanup.
527 // This can happen if the .oat is corrupt, since the above only checks the .art checksums.
528 // TODO: Check the oat file validity earlier.
529 *error_msg = StringPrintf("Attempted to use relocated version of %s at %s generated from %s "
530 "but image failed to load: %s",
531 image_location, cache_filename.c_str(), system_filename.c_str(),
532 error_msg->c_str());
Narayan Kamath28bc9872014-11-07 17:46:28 +0000533 PruneDalvikCache(image_isa);
Alex Lighta59dd802014-07-02 16:28:08 -0700534 return nullptr;
535 } else if (is_system) {
Brian Carlstrome9105f72014-10-28 15:53:43 -0700536 // If the /system file exists, it should be up-to-date, don't try to generate it.
Alex Light64ad14d2014-08-19 14:23:13 -0700537 *error_msg = StringPrintf("Failed to load /system image '%s': %s",
538 image_filename->c_str(), error_msg->c_str());
Narayan Kamath52f84882014-05-02 10:10:39 +0100539 return nullptr;
Mathieu Chartierc7cb1902014-03-05 14:41:03 -0800540 } else {
Brian Carlstrome9105f72014-10-28 15:53:43 -0700541 // Otherwise, log a warning and fall through to GenerateImage.
Alex Light64ad14d2014-08-19 14:23:13 -0700542 LOG(WARNING) << *error_msg;
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700543 }
544 }
Narayan Kamath52f84882014-05-02 10:10:39 +0100545
Alex Light64ad14d2014-08-19 14:23:13 -0700546 if (!can_compile) {
547 *error_msg = "Not attempting to compile image because -Xnoimage-dex2oat";
548 return nullptr;
549 } else if (!dalvik_cache_exists) {
550 *error_msg = StringPrintf("No place to put generated image.");
551 return nullptr;
Andreas Gampe3c13a792014-09-18 20:56:04 -0700552 } else if (!ImageCreationAllowed(is_global_cache, error_msg)) {
553 return nullptr;
Andreas Gampe8994a042015-12-30 19:03:17 +0000554 } else if (secondary_image) {
555 *error_msg = "Cannot compile a secondary image.";
556 return nullptr;
Alex Light25396132014-08-27 15:37:23 -0700557 } else if (!GenerateImage(cache_filename, image_isa, error_msg)) {
Alex Light64ad14d2014-08-19 14:23:13 -0700558 *error_msg = StringPrintf("Failed to generate image '%s': %s",
559 cache_filename.c_str(), error_msg->c_str());
Brian Carlstrome9105f72014-10-28 15:53:43 -0700560 // We failed to create files, remove any possibly garbage output.
561 // Since ImageCreationAllowed was true above, we are the zygote
562 // and therefore the only process expected to generate these for
563 // the device.
Narayan Kamath28bc9872014-11-07 17:46:28 +0000564 PruneDalvikCache(image_isa);
Alex Light64ad14d2014-08-19 14:23:13 -0700565 return nullptr;
566 } else {
Andreas Gampe70be1fb2014-10-31 16:45:19 -0700567 // Check whether there is enough space left over after we have generated the image.
568 if (!CheckSpace(cache_filename, error_msg)) {
569 // No. Delete the generated image and try to run out of the dex files.
Narayan Kamath28bc9872014-11-07 17:46:28 +0000570 PruneDalvikCache(image_isa);
Andreas Gampe70be1fb2014-10-31 16:45:19 -0700571 return nullptr;
572 }
573
Alex Lighta59dd802014-07-02 16:28:08 -0700574 // Note that we must not use the file descriptor associated with
575 // ScopedFlock::GetFile to Init the image file. We want the file
576 // descriptor (and the associated exclusive lock) to be released when
577 // we leave Create.
578 ScopedFlock image_lock;
Alex Light64ad14d2014-08-19 14:23:13 -0700579 image_lock.Init(cache_filename.c_str(), error_msg);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800580 space = ImageSpace::Init(cache_filename.c_str(), image_location, true, nullptr, error_msg);
Alex Light64ad14d2014-08-19 14:23:13 -0700581 if (space == nullptr) {
582 *error_msg = StringPrintf("Failed to load generated image '%s': %s",
583 cache_filename.c_str(), error_msg->c_str());
584 }
585 return space;
Alex Lighta59dd802014-07-02 16:28:08 -0700586 }
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700587}
588
Mathieu Chartier31e89252013-08-28 11:29:12 -0700589void ImageSpace::VerifyImageAllocations() {
Ian Rogers13735952014-10-08 12:43:28 -0700590 uint8_t* current = Begin() + RoundUp(sizeof(ImageHeader), kObjectAlignment);
Mathieu Chartier31e89252013-08-28 11:29:12 -0700591 while (current < End()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700592 CHECK_ALIGNED(current, kObjectAlignment);
593 auto* obj = reinterpret_cast<mirror::Object*>(current);
Mathieu Chartier31e89252013-08-28 11:29:12 -0700594 CHECK(obj->GetClass() != nullptr) << "Image object at address " << obj << " has null class";
Mathieu Chartierc7853442015-03-27 14:35:38 -0700595 CHECK(live_bitmap_->Test(obj)) << PrettyTypeOf(obj);
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -0700596 if (kUseBakerOrBrooksReadBarrier) {
597 obj->AssertReadBarrierPointer();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800598 }
Mathieu Chartier31e89252013-08-28 11:29:12 -0700599 current += RoundUp(obj->SizeOf(), kObjectAlignment);
600 }
601}
602
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800603// Helper class for relocating from one range of memory to another.
604class RelocationRange {
605 public:
606 RelocationRange() = default;
607 RelocationRange(const RelocationRange&) = default;
608 RelocationRange(uintptr_t source, uintptr_t dest, uintptr_t length)
609 : source_(source),
610 dest_(dest),
611 length_(length) {}
612
Mathieu Chartier91edc622016-02-16 17:16:01 -0800613 bool InSource(uintptr_t address) const {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800614 return address - source_ < length_;
615 }
616
Mathieu Chartier91edc622016-02-16 17:16:01 -0800617 bool InDest(uintptr_t address) const {
618 return address - dest_ < length_;
619 }
620
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800621 // Translate a source address to the destination space.
622 uintptr_t ToDest(uintptr_t address) const {
Mathieu Chartier91edc622016-02-16 17:16:01 -0800623 DCHECK(InSource(address));
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800624 return address + Delta();
625 }
626
627 // Returns the delta between the dest from the source.
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800628 uintptr_t Delta() const {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800629 return dest_ - source_;
630 }
631
632 uintptr_t Source() const {
633 return source_;
634 }
635
636 uintptr_t Dest() const {
637 return dest_;
638 }
639
640 uintptr_t Length() const {
641 return length_;
642 }
643
644 private:
645 const uintptr_t source_;
646 const uintptr_t dest_;
647 const uintptr_t length_;
648};
649
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800650std::ostream& operator<<(std::ostream& os, const RelocationRange& reloc) {
651 return os << "(" << reinterpret_cast<const void*>(reloc.Source()) << "-"
652 << reinterpret_cast<const void*>(reloc.Source() + reloc.Length()) << ")->("
653 << reinterpret_cast<const void*>(reloc.Dest()) << "-"
654 << reinterpret_cast<const void*>(reloc.Dest() + reloc.Length()) << ")";
655}
656
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800657class FixupVisitor : public ValueObject {
658 public:
659 FixupVisitor(const RelocationRange& boot_image,
660 const RelocationRange& boot_oat,
661 const RelocationRange& app_image,
662 const RelocationRange& app_oat)
663 : boot_image_(boot_image),
664 boot_oat_(boot_oat),
665 app_image_(app_image),
666 app_oat_(app_oat) {}
667
668 // Return the relocated address of a heap object.
669 template <typename T>
670 ALWAYS_INLINE T* ForwardObject(T* src) const {
671 const uintptr_t uint_src = reinterpret_cast<uintptr_t>(src);
Mathieu Chartier91edc622016-02-16 17:16:01 -0800672 if (boot_image_.InSource(uint_src)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800673 return reinterpret_cast<T*>(boot_image_.ToDest(uint_src));
674 }
Mathieu Chartier91edc622016-02-16 17:16:01 -0800675 if (app_image_.InSource(uint_src)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800676 return reinterpret_cast<T*>(app_image_.ToDest(uint_src));
677 }
Mathieu Chartier91edc622016-02-16 17:16:01 -0800678 // Since we are fixing up the app image, there should only be pointers to the app image and
679 // boot image.
680 DCHECK(src == nullptr) << reinterpret_cast<const void*>(src);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800681 return src;
682 }
683
684 // Return the relocated address of a code pointer (contained by an oat file).
685 ALWAYS_INLINE const void* ForwardCode(const void* src) const {
686 const uintptr_t uint_src = reinterpret_cast<uintptr_t>(src);
Mathieu Chartier91edc622016-02-16 17:16:01 -0800687 if (boot_oat_.InSource(uint_src)) {
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800688 return reinterpret_cast<const void*>(boot_oat_.ToDest(uint_src));
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800689 }
Mathieu Chartier91edc622016-02-16 17:16:01 -0800690 if (app_oat_.InSource(uint_src)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800691 return reinterpret_cast<const void*>(app_oat_.ToDest(uint_src));
692 }
Mathieu Chartier91edc622016-02-16 17:16:01 -0800693 DCHECK(src == nullptr) << src;
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800694 return src;
695 }
696
697 protected:
698 // Source section.
699 const RelocationRange boot_image_;
700 const RelocationRange boot_oat_;
701 const RelocationRange app_image_;
702 const RelocationRange app_oat_;
703};
704
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800705// Adapt for mirror::Class::FixupNativePointers.
706class FixupObjectAdapter : public FixupVisitor {
707 public:
708 template<typename... Args>
709 explicit FixupObjectAdapter(Args... args) : FixupVisitor(args...) {}
710
Mathieu Chartier91edc622016-02-16 17:16:01 -0800711 // Must be called on pointers that already have been relocated to the destination relocation.
712 ALWAYS_INLINE bool IsInAppImage(mirror::Object* object) const {
713 return app_image_.InDest(reinterpret_cast<uintptr_t>(object));
714 }
715
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800716 template <typename T>
717 T* operator()(T* obj) const {
718 return ForwardObject(obj);
719 }
720};
721
722class FixupClassVisitor : public FixupVisitor {
723 public:
724 template<typename... Args>
725 explicit FixupClassVisitor(Args... args) : FixupVisitor(args...) {}
726
727 // The image space is contained so the GC doesn't need to know about it. Avoid requiring mutator
728 // lock to prevent possible pauses.
729 ALWAYS_INLINE void operator()(mirror::Object* obj) const NO_THREAD_SAFETY_ANALYSIS {
730 mirror::Class* klass = obj->GetClass<kVerifyNone, kWithoutReadBarrier>();
731 DCHECK(klass != nullptr) << "Null class in image";
732 // No AsClass since our fields aren't quite fixed up yet.
733 mirror::Class* new_klass = down_cast<mirror::Class*>(ForwardObject(klass));
734 // Keep clean if possible.
735 if (klass != new_klass) {
736 obj->SetClass<kVerifyNone>(new_klass);
737 }
738 }
739};
740
741class FixupRootVisitor : public FixupVisitor {
742 public:
743 template<typename... Args>
744 explicit FixupRootVisitor(Args... args) : FixupVisitor(args...) {}
745
746 ALWAYS_INLINE void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
747 SHARED_REQUIRES(Locks::mutator_lock_) {
748 if (!root->IsNull()) {
749 VisitRoot(root);
750 }
751 }
752
753 ALWAYS_INLINE void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
754 SHARED_REQUIRES(Locks::mutator_lock_) {
755 mirror::Object* ref = root->AsMirrorPtr();
756 mirror::Object* new_ref = ForwardObject(ref);
757 if (ref != new_ref) {
758 root->Assign(new_ref);
759 }
760 }
761};
762
763class FixupObjectVisitor : public FixupVisitor {
764 public:
765 template<typename... Args>
Mathieu Chartier91edc622016-02-16 17:16:01 -0800766 explicit FixupObjectVisitor(gc::accounting::ContinuousSpaceBitmap* pointer_array_visited,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800767 const size_t pointer_size,
Mathieu Chartier91edc622016-02-16 17:16:01 -0800768 Args... args)
769 : FixupVisitor(args...),
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800770 pointer_size_(pointer_size),
Mathieu Chartier91edc622016-02-16 17:16:01 -0800771 pointer_array_visited_(pointer_array_visited) {}
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800772
773 // Fix up separately since we also need to fix up method entrypoints.
774 ALWAYS_INLINE void VisitRootIfNonNull(
775 mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const {}
776
777 ALWAYS_INLINE void VisitRoot(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED)
778 const {}
779
780 ALWAYS_INLINE void operator()(mirror::Object* obj,
781 MemberOffset offset,
782 bool is_static ATTRIBUTE_UNUSED) const
783 NO_THREAD_SAFETY_ANALYSIS {
784 // There could be overlap between ranges, we must avoid visiting the same reference twice.
785 // Avoid the class field since we already fixed it up in FixupClassVisitor.
786 if (offset.Uint32Value() != mirror::Object::ClassOffset().Uint32Value()) {
787 // Space is not yet added to the heap, don't do a read barrier.
788 mirror::Object* ref = obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(
789 offset);
790 // Use SetFieldObjectWithoutWriteBarrier to avoid card marking since we are writing to the
791 // image.
792 obj->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(offset, ForwardObject(ref));
793 }
794 }
795
Mathieu Chartier91edc622016-02-16 17:16:01 -0800796 // Visit a pointer array and forward corresponding native data. Ignores pointer arrays in the
797 // boot image. Uses the bitmap to ensure the same array is not visited multiple times.
798 template <typename Visitor>
799 void VisitPointerArray(mirror::PointerArray* array, const Visitor& visitor) const
800 NO_THREAD_SAFETY_ANALYSIS {
801 if (array != nullptr &&
802 visitor.IsInAppImage(array) &&
803 !pointer_array_visited_->Test(array)) {
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800804 array->Fixup<kVerifyNone, kWithoutReadBarrier>(array, pointer_size_, visitor);
Mathieu Chartier91edc622016-02-16 17:16:01 -0800805 pointer_array_visited_->Set(array);
806 }
807 }
808
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800809 // java.lang.ref.Reference visitor.
810 void operator()(mirror::Class* klass ATTRIBUTE_UNUSED, mirror::Reference* ref) const
811 SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
812 mirror::Object* obj = ref->GetReferent<kWithoutReadBarrier>();
813 ref->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
814 mirror::Reference::ReferentOffset(),
815 ForwardObject(obj));
816 }
817
818 ALWAYS_INLINE void operator()(mirror::Object* obj) const NO_THREAD_SAFETY_ANALYSIS {
819 obj->VisitReferences</*visit native roots*/false, kVerifyNone, kWithoutReadBarrier>(
820 *this,
821 *this);
822 // We want to use our own class loader and not the one in the image.
823 if (obj->IsClass<kVerifyNone, kWithoutReadBarrier>()) {
824 mirror::Class* klass = obj->AsClass<kVerifyNone, kWithoutReadBarrier>();
825 FixupObjectAdapter visitor(boot_image_, boot_oat_, app_image_, app_oat_);
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800826 klass->FixupNativePointers<kVerifyNone, kWithoutReadBarrier>(klass, pointer_size_, visitor);
Mathieu Chartier91edc622016-02-16 17:16:01 -0800827 // Deal with the pointer arrays. Use the helper function since multiple classes can reference
828 // the same arrays.
829 VisitPointerArray(klass->GetVTable<kVerifyNone, kWithoutReadBarrier>(), visitor);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800830 mirror::IfTable* iftable = klass->GetIfTable<kVerifyNone, kWithoutReadBarrier>();
831 if (iftable != nullptr) {
Mathieu Chartierdfe02f62016-02-01 20:15:11 -0800832 for (int32_t i = 0, count = iftable->Count(); i < count; ++i) {
833 if (iftable->GetMethodArrayCount<kVerifyNone, kWithoutReadBarrier>(i) > 0) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800834 mirror::PointerArray* methods =
835 iftable->GetMethodArray<kVerifyNone, kWithoutReadBarrier>(i);
836 DCHECK(methods != nullptr);
Mathieu Chartier91edc622016-02-16 17:16:01 -0800837 VisitPointerArray(methods, visitor);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800838 }
839 }
840 }
841 }
842 }
Mathieu Chartier91edc622016-02-16 17:16:01 -0800843
844 private:
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800845 const size_t pointer_size_;
Mathieu Chartier91edc622016-02-16 17:16:01 -0800846 gc::accounting::ContinuousSpaceBitmap* const pointer_array_visited_;
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800847};
848
849class ForwardObjectAdapter {
850 public:
851 ALWAYS_INLINE ForwardObjectAdapter(const FixupVisitor* visitor) : visitor_(visitor) {}
852
853 template <typename T>
854 ALWAYS_INLINE T* operator()(T* src) const {
855 return visitor_->ForwardObject(src);
856 }
857
858 private:
859 const FixupVisitor* const visitor_;
860};
861
862class ForwardCodeAdapter {
863 public:
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800864 ALWAYS_INLINE ForwardCodeAdapter(const FixupVisitor* visitor)
865 : visitor_(visitor) {}
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800866
867 template <typename T>
868 ALWAYS_INLINE T* operator()(T* src) const {
869 return visitor_->ForwardCode(src);
870 }
871
872 private:
873 const FixupVisitor* const visitor_;
874};
875
876class FixupArtMethodVisitor : public FixupVisitor, public ArtMethodVisitor {
877 public:
878 template<typename... Args>
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800879 explicit FixupArtMethodVisitor(bool fixup_heap_objects, size_t pointer_size, Args... args)
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800880 : FixupVisitor(args...),
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800881 fixup_heap_objects_(fixup_heap_objects),
882 pointer_size_(pointer_size) {}
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800883
884 virtual void Visit(ArtMethod* method) NO_THREAD_SAFETY_ANALYSIS {
885 if (fixup_heap_objects_) {
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800886 method->UpdateObjectsForImageRelocation(ForwardObjectAdapter(this), pointer_size_);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800887 }
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800888 method->UpdateEntrypoints<kWithoutReadBarrier>(ForwardCodeAdapter(this), pointer_size_);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800889 }
890
891 private:
892 const bool fixup_heap_objects_;
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800893 const size_t pointer_size_;
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800894};
895
896class FixupArtFieldVisitor : public FixupVisitor, public ArtFieldVisitor {
897 public:
898 template<typename... Args>
899 explicit FixupArtFieldVisitor(Args... args) : FixupVisitor(args...) {}
900
901 virtual void Visit(ArtField* field) NO_THREAD_SAFETY_ANALYSIS {
902 field->UpdateObjects(ForwardObjectAdapter(this));
903 }
904};
905
906// Relocate an image space mapped at target_base which possibly used to be at a different base
907// address. Only needs a single image space, not one for both source and destination.
908// In place means modifying a single ImageSpace in place rather than relocating from one ImageSpace
909// to another.
910static bool RelocateInPlace(ImageHeader& image_header,
911 uint8_t* target_base,
912 accounting::ContinuousSpaceBitmap* bitmap,
913 const OatFile* app_oat_file,
914 std::string* error_msg) {
915 DCHECK(error_msg != nullptr);
916 if (!image_header.IsPic()) {
917 if (image_header.GetImageBegin() == target_base) {
918 return true;
919 }
920 *error_msg = StringPrintf("Cannot relocate non-pic image for oat file %s",
921 (app_oat_file != nullptr) ? app_oat_file->GetLocation().c_str() : "");
922 return false;
923 }
924 // Set up sections.
925 uint32_t boot_image_begin = 0;
926 uint32_t boot_image_end = 0;
927 uint32_t boot_oat_begin = 0;
928 uint32_t boot_oat_end = 0;
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800929 const size_t pointer_size = image_header.GetPointerSize();
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800930 gc::Heap* const heap = Runtime::Current()->GetHeap();
931 heap->GetBootImagesSize(&boot_image_begin, &boot_image_end, &boot_oat_begin, &boot_oat_end);
932 CHECK_NE(boot_image_begin, boot_image_end)
933 << "Can not relocate app image without boot image space";
934 CHECK_NE(boot_oat_begin, boot_oat_end) << "Can not relocate app image without boot oat file";
935 const uint32_t boot_image_size = boot_image_end - boot_image_begin;
936 const uint32_t boot_oat_size = boot_oat_end - boot_oat_begin;
937 const uint32_t image_header_boot_image_size = image_header.GetBootImageSize();
938 const uint32_t image_header_boot_oat_size = image_header.GetBootOatSize();
939 if (boot_image_size != image_header_boot_image_size) {
940 *error_msg = StringPrintf("Boot image size %" PRIu64 " does not match expected size %"
941 PRIu64,
942 static_cast<uint64_t>(boot_image_size),
943 static_cast<uint64_t>(image_header_boot_image_size));
944 return false;
945 }
946 if (boot_oat_size != image_header_boot_oat_size) {
947 *error_msg = StringPrintf("Boot oat size %" PRIu64 " does not match expected size %"
948 PRIu64,
949 static_cast<uint64_t>(boot_oat_size),
950 static_cast<uint64_t>(image_header_boot_oat_size));
951 return false;
952 }
953 TimingLogger logger(__FUNCTION__, true, false);
954 RelocationRange boot_image(image_header.GetBootImageBegin(),
955 boot_image_begin,
956 boot_image_size);
957 RelocationRange boot_oat(image_header.GetBootOatBegin(),
958 boot_oat_begin,
959 boot_oat_size);
960 RelocationRange app_image(reinterpret_cast<uintptr_t>(image_header.GetImageBegin()),
961 reinterpret_cast<uintptr_t>(target_base),
962 image_header.GetImageSize());
963 // Use the oat data section since this is where the OatFile::Begin is.
964 RelocationRange app_oat(reinterpret_cast<uintptr_t>(image_header.GetOatDataBegin()),
965 // Not necessarily in low 4GB.
966 reinterpret_cast<uintptr_t>(app_oat_file->Begin()),
967 image_header.GetOatDataEnd() - image_header.GetOatDataBegin());
968 VLOG(image) << "App image " << app_image;
969 VLOG(image) << "App oat " << app_oat;
970 VLOG(image) << "Boot image " << boot_image;
971 VLOG(image) << "Boot oat " << boot_oat;
972 // True if we need to fixup any heap pointers, otherwise only code pointers.
973 const bool fixup_image = boot_image.Delta() != 0 || app_image.Delta() != 0;
974 const bool fixup_code = boot_oat.Delta() != 0 || app_oat.Delta() != 0;
975 if (!fixup_image && !fixup_code) {
976 // Nothing to fix up.
977 return true;
978 }
Mathieu Chartierdfe02f62016-02-01 20:15:11 -0800979 ScopedDebugDisallowReadBarriers sddrb(Thread::Current());
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800980 // Need to update the image to be at the target base.
981 const ImageSection& objects_section = image_header.GetImageSection(ImageHeader::kSectionObjects);
982 uintptr_t objects_begin = reinterpret_cast<uintptr_t>(target_base + objects_section.Offset());
983 uintptr_t objects_end = reinterpret_cast<uintptr_t>(target_base + objects_section.End());
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800984 if (fixup_image) {
Mathieu Chartier91edc622016-02-16 17:16:01 -0800985 // Two pass approach, fix up all classes first, then fix up non class-objects.
986 // The visited bitmap is used to ensure that pointer arrays are not forwarded twice.
987 std::unique_ptr<gc::accounting::ContinuousSpaceBitmap> visited_bitmap(
988 gc::accounting::ContinuousSpaceBitmap::Create("Pointer array bitmap",
989 target_base,
990 image_header.GetImageSize()));
991 FixupObjectVisitor fixup_object_visitor(visited_bitmap.get(),
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800992 pointer_size,
Mathieu Chartier91edc622016-02-16 17:16:01 -0800993 boot_image,
994 boot_oat,
995 app_image,
996 app_oat);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800997 TimingLogger::ScopedTiming timing("Fixup classes", &logger);
998 // Fixup class only touches app image classes, don't need the mutator lock since the space is
999 // not yet visible to the GC.
1000 FixupClassVisitor fixup_class_visitor(boot_image, boot_oat, app_image, app_oat);
1001 bitmap->VisitMarkedRange(objects_begin, objects_end, fixup_class_visitor);
1002 // Fixup objects may read fields in the boot image, use the mutator lock here for sanity. Though
1003 // its probably not required.
1004 ScopedObjectAccess soa(Thread::Current());
1005 timing.NewTiming("Fixup objects");
1006 bitmap->VisitMarkedRange(objects_begin, objects_end, fixup_object_visitor);
1007 FixupObjectAdapter fixup_adapter(boot_image, boot_oat, app_image, app_oat);
1008 // Fixup image roots.
Mathieu Chartier91edc622016-02-16 17:16:01 -08001009 CHECK(app_image.InSource(reinterpret_cast<uintptr_t>(
Mathieu Chartier4a26f172016-01-26 14:26:18 -08001010 image_header.GetImageRoots<kWithoutReadBarrier>())));
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001011 image_header.RelocateImageObjects(app_image.Delta());
1012 CHECK_EQ(image_header.GetImageBegin(), target_base);
1013 // Fix up dex cache DexFile pointers.
Mathieu Chartier4a26f172016-01-26 14:26:18 -08001014 auto* dex_caches = image_header.GetImageRoot<kWithoutReadBarrier>(ImageHeader::kDexCaches)->
Mathieu Chartierdfe02f62016-02-01 20:15:11 -08001015 AsObjectArray<mirror::DexCache, kVerifyNone, kWithoutReadBarrier>();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001016 for (int32_t i = 0, count = dex_caches->GetLength(); i < count; ++i) {
Mathieu Chartier60bc39c2016-01-27 18:37:48 -08001017 mirror::DexCache* dex_cache = dex_caches->Get<kVerifyNone, kWithoutReadBarrier>(i);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001018 // Fix up dex cache pointers.
1019 GcRoot<mirror::String>* strings = dex_cache->GetStrings();
1020 if (strings != nullptr) {
1021 GcRoot<mirror::String>* new_strings = fixup_adapter.ForwardObject(strings);
1022 if (strings != new_strings) {
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001023 dex_cache->SetStrings(new_strings);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001024 }
Mathieu Chartier60bc39c2016-01-27 18:37:48 -08001025 dex_cache->FixupStrings<kWithoutReadBarrier>(new_strings, fixup_adapter);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001026 }
1027 GcRoot<mirror::Class>* types = dex_cache->GetResolvedTypes();
1028 if (types != nullptr) {
1029 GcRoot<mirror::Class>* new_types = fixup_adapter.ForwardObject(types);
1030 if (types != new_types) {
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001031 dex_cache->SetResolvedTypes(new_types);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001032 }
Mathieu Chartier60bc39c2016-01-27 18:37:48 -08001033 dex_cache->FixupResolvedTypes<kWithoutReadBarrier>(new_types, fixup_adapter);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001034 }
1035 ArtMethod** methods = dex_cache->GetResolvedMethods();
1036 if (methods != nullptr) {
1037 ArtMethod** new_methods = fixup_adapter.ForwardObject(methods);
1038 if (methods != new_methods) {
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001039 dex_cache->SetResolvedMethods(new_methods);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001040 }
1041 for (size_t j = 0, num = dex_cache->NumResolvedMethods(); j != num; ++j) {
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001042 ArtMethod* orig = mirror::DexCache::GetElementPtrSize(new_methods, j, pointer_size);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001043 ArtMethod* copy = fixup_adapter.ForwardObject(orig);
1044 if (orig != copy) {
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001045 mirror::DexCache::SetElementPtrSize(new_methods, j, copy, pointer_size);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001046 }
1047 }
1048 }
1049 ArtField** fields = dex_cache->GetResolvedFields();
1050 if (fields != nullptr) {
1051 ArtField** new_fields = fixup_adapter.ForwardObject(fields);
1052 if (fields != new_fields) {
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001053 dex_cache->SetResolvedFields(new_fields);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001054 }
1055 for (size_t j = 0, num = dex_cache->NumResolvedFields(); j != num; ++j) {
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001056 ArtField* orig = mirror::DexCache::GetElementPtrSize(new_fields, j, pointer_size);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001057 ArtField* copy = fixup_adapter.ForwardObject(orig);
1058 if (orig != copy) {
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001059 mirror::DexCache::SetElementPtrSize(new_fields, j, copy, pointer_size);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001060 }
1061 }
1062 }
1063 }
1064 }
1065 {
1066 // Only touches objects in the app image, no need for mutator lock.
1067 TimingLogger::ScopedTiming timing("Fixup methods", &logger);
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001068 FixupArtMethodVisitor method_visitor(fixup_image,
1069 pointer_size,
1070 boot_image,
1071 boot_oat,
1072 app_image,
1073 app_oat);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001074 image_header.GetImageSection(ImageHeader::kSectionArtMethods).VisitPackedArtMethods(
1075 &method_visitor,
1076 target_base,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001077 pointer_size);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001078 }
1079 if (fixup_image) {
1080 {
1081 // Only touches objects in the app image, no need for mutator lock.
1082 TimingLogger::ScopedTiming timing("Fixup fields", &logger);
1083 FixupArtFieldVisitor field_visitor(boot_image, boot_oat, app_image, app_oat);
1084 image_header.GetImageSection(ImageHeader::kSectionArtFields).VisitPackedArtFields(
1085 &field_visitor,
1086 target_base);
1087 }
1088 // In the app image case, the image methods are actually in the boot image.
1089 image_header.RelocateImageMethods(boot_image.Delta());
1090 const auto& class_table_section = image_header.GetImageSection(ImageHeader::kSectionClassTable);
1091 if (class_table_section.Size() > 0u) {
1092 // Note that we require that ReadFromMemory does not make an internal copy of the elements.
1093 // This also relies on visit roots not doing any verification which could fail after we update
1094 // the roots to be the image addresses.
1095 ScopedObjectAccess soa(Thread::Current());
1096 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
1097 ClassTable temp_table;
1098 temp_table.ReadFromMemory(target_base + class_table_section.Offset());
1099 FixupRootVisitor root_visitor(boot_image, boot_oat, app_image, app_oat);
1100 temp_table.VisitRoots(root_visitor);
1101 }
1102 }
1103 if (VLOG_IS_ON(image)) {
1104 logger.Dump(LOG(INFO));
1105 }
1106 return true;
1107}
1108
1109ImageSpace* ImageSpace::Init(const char* image_filename,
1110 const char* image_location,
1111 bool validate_oat_file,
1112 const OatFile* oat_file,
1113 std::string* error_msg) {
Narayan Kamath52f84882014-05-02 10:10:39 +01001114 CHECK(image_filename != nullptr);
1115 CHECK(image_location != nullptr);
Ian Rogers1d54e732013-05-02 21:10:01 -07001116
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001117 TimingLogger logger(__PRETTY_FUNCTION__, true, VLOG_IS_ON(image));
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001118 VLOG(image) << "ImageSpace::Init entering image_filename=" << image_filename;
Nicolas Geoffray1bc977c2016-01-23 14:15:49 +00001119
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001120 std::unique_ptr<File> file;
1121 {
1122 TimingLogger::ScopedTiming timing("OpenImageFile", &logger);
1123 file.reset(OS::OpenFileForReading(image_filename));
1124 if (file == nullptr) {
1125 *error_msg = StringPrintf("Failed to open '%s'", image_filename);
1126 return nullptr;
1127 }
Nicolas Geoffray1bc977c2016-01-23 14:15:49 +00001128 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001129 ImageHeader temp_image_header;
1130 ImageHeader* image_header = &temp_image_header;
1131 {
1132 TimingLogger::ScopedTiming timing("ReadImageHeader", &logger);
1133 bool success = file->ReadFully(image_header, sizeof(*image_header));
1134 if (!success || !image_header->IsValid()) {
1135 *error_msg = StringPrintf("Invalid image header in '%s'", image_filename);
1136 return nullptr;
1137 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001138 }
Mathieu Chartierceb07b32015-12-10 09:33:21 -08001139 // Check that the file is larger or equal to the header size + data size.
1140 const uint64_t image_file_size = static_cast<uint64_t>(file->GetLength());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001141 if (image_file_size < sizeof(ImageHeader) + image_header->GetDataSize()) {
Mathieu Chartierceb07b32015-12-10 09:33:21 -08001142 *error_msg = StringPrintf("Image file truncated: %" PRIu64 " vs. %" PRIu64 ".",
1143 image_file_size,
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001144 sizeof(ImageHeader) + image_header->GetDataSize());
Andreas Gampe6c8b49f2015-02-19 11:42:36 -08001145 return nullptr;
1146 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001147
Mathieu Chartier9ff84602016-01-29 12:22:17 -08001148 if (oat_file != nullptr) {
1149 // If we have an oat file, check the oat file checksum. The oat file is only non-null for the
1150 // app image case. Otherwise, we open the oat file after the image and check the checksum there.
1151 const uint32_t oat_checksum = oat_file->GetOatHeader().GetChecksum();
1152 const uint32_t image_oat_checksum = image_header->GetOatChecksum();
1153 if (oat_checksum != image_oat_checksum) {
1154 *error_msg = StringPrintf("Oat checksum 0x%x does not match the image one 0x%x in image %s",
1155 oat_checksum,
1156 image_oat_checksum,
1157 image_filename);
1158 return nullptr;
1159 }
1160 }
1161
Jeff Haodcdc85b2015-12-04 14:06:18 -08001162 if (VLOG_IS_ON(startup)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001163 LOG(INFO) << "Dumping image sections";
1164 for (size_t i = 0; i < ImageHeader::kSectionCount; ++i) {
1165 const auto section_idx = static_cast<ImageHeader::ImageSections>(i);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001166 auto& section = image_header->GetImageSection(section_idx);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001167 LOG(INFO) << section_idx << " start="
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001168 << reinterpret_cast<void*>(image_header->GetImageBegin() + section.Offset()) << " "
1169 << section;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001170 }
1171 }
1172
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001173 const auto& bitmap_section = image_header->GetImageSection(ImageHeader::kSectionImageBitmap);
Mathieu Chartierceb07b32015-12-10 09:33:21 -08001174 // The location we want to map from is the first aligned page after the end of the stored
1175 // (possibly compressed) data.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001176 const size_t image_bitmap_offset = RoundUp(sizeof(ImageHeader) + image_header->GetDataSize(),
Mathieu Chartierceb07b32015-12-10 09:33:21 -08001177 kPageSize);
1178 const size_t end_of_bitmap = image_bitmap_offset + bitmap_section.Size();
Mathieu Chartierc7853442015-03-27 14:35:38 -07001179 if (end_of_bitmap != image_file_size) {
1180 *error_msg = StringPrintf(
1181 "Image file size does not equal end of bitmap: size=%" PRIu64 " vs. %zu.", image_file_size,
1182 end_of_bitmap);
Andreas Gampe6c8b49f2015-02-19 11:42:36 -08001183 return nullptr;
1184 }
1185
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001186 // The preferred address to map the image, null specifies any address. If we manage to map the
1187 // image at the image begin, the amount of fixup work required is minimized.
1188 std::vector<uint8_t*> addresses(1, image_header->GetImageBegin());
1189 if (image_header->IsPic()) {
1190 // Can also map at a random low_4gb address since we can relocate in-place.
1191 addresses.push_back(nullptr);
1192 }
1193
Mathieu Chartier31e89252013-08-28 11:29:12 -07001194 // Note: The image header is part of the image due to mmap page alignment required of offset.
Mathieu Chartierceb07b32015-12-10 09:33:21 -08001195 std::unique_ptr<MemMap> map;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001196 std::string temp_error_msg;
1197 for (uint8_t* address : addresses) {
1198 TimingLogger::ScopedTiming timing("MapImageFile", &logger);
1199 // Only care about the error message for the last address in addresses. We want to avoid the
1200 // overhead of printing the process maps if we can relocate.
1201 std::string* out_error_msg = (address == addresses.back()) ? &temp_error_msg : nullptr;
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -08001202 const ImageHeader::StorageMode storage_mode = image_header->GetStorageMode();
1203 if (storage_mode == ImageHeader::kStorageModeUncompressed) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001204 map.reset(MemMap::MapFileAtAddress(address,
1205 image_header->GetImageSize(),
1206 PROT_READ | PROT_WRITE,
1207 MAP_PRIVATE,
1208 file->Fd(),
1209 0,
1210 /*low_4gb*/true,
1211 /*reuse*/false,
1212 image_filename,
1213 /*out*/out_error_msg));
1214 } else {
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -08001215 if (storage_mode != ImageHeader::kStorageModeLZ4 &&
1216 storage_mode != ImageHeader::kStorageModeLZ4HC) {
1217 *error_msg = StringPrintf("Invalid storage mode in image header %d",
1218 static_cast<int>(storage_mode));
1219 return nullptr;
1220 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001221 // Reserve output and decompress into it.
1222 map.reset(MemMap::MapAnonymous(image_location,
1223 address,
1224 image_header->GetImageSize(),
1225 PROT_READ | PROT_WRITE,
1226 /*low_4gb*/true,
1227 /*reuse*/false,
Mathieu Chartierc5dd3192015-12-09 16:38:30 -08001228 /*out*/out_error_msg));
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001229 if (map != nullptr) {
1230 const size_t stored_size = image_header->GetDataSize();
Mathieu Chartier8e864bf2016-03-14 11:02:59 -07001231 const size_t decompress_offset = sizeof(ImageHeader); // Skip the header.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001232 std::unique_ptr<MemMap> temp_map(MemMap::MapFile(sizeof(ImageHeader) + stored_size,
1233 PROT_READ,
1234 MAP_PRIVATE,
1235 file->Fd(),
1236 /*offset*/0,
1237 /*low_4gb*/false,
1238 image_filename,
1239 out_error_msg));
1240 if (temp_map == nullptr) {
1241 DCHECK(!out_error_msg->empty());
1242 return nullptr;
1243 }
1244 memcpy(map->Begin(), image_header, sizeof(ImageHeader));
1245 const uint64_t start = NanoTime();
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -08001246 // LZ4HC and LZ4 have same internal format, both use LZ4_decompress.
Mathieu Chartier31317c32016-02-25 12:28:40 -08001247 TimingLogger::ScopedTiming timing2("LZ4 decompress image", &logger);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001248 const size_t decompressed_size = LZ4_decompress_safe(
1249 reinterpret_cast<char*>(temp_map->Begin()) + sizeof(ImageHeader),
Mathieu Chartier8e864bf2016-03-14 11:02:59 -07001250 reinterpret_cast<char*>(map->Begin()) + decompress_offset,
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001251 stored_size,
Mathieu Chartier8e864bf2016-03-14 11:02:59 -07001252 map->Size() - decompress_offset);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001253 VLOG(image) << "Decompressing image took " << PrettyDuration(NanoTime() - start);
1254 if (decompressed_size + sizeof(ImageHeader) != image_header->GetImageSize()) {
Mathieu Chartier8e864bf2016-03-14 11:02:59 -07001255 *error_msg = StringPrintf(
1256 "Decompressed size does not match expected image size %zu vs %zu",
1257 decompressed_size + sizeof(ImageHeader),
1258 image_header->GetImageSize());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001259 return nullptr;
1260 }
1261 }
1262 }
Mathieu Chartierceb07b32015-12-10 09:33:21 -08001263 if (map != nullptr) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001264 break;
Mathieu Chartierceb07b32015-12-10 09:33:21 -08001265 }
1266 }
1267
Mathieu Chartier42bddce2015-11-09 15:16:56 -08001268 if (map == nullptr) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001269 DCHECK(!temp_error_msg.empty());
1270 *error_msg = temp_error_msg;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001271 return nullptr;
Ian Rogers1d54e732013-05-02 21:10:01 -07001272 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001273 DCHECK_EQ(0, memcmp(image_header, map->Begin(), sizeof(ImageHeader)));
Ian Rogers1d54e732013-05-02 21:10:01 -07001274
Mathieu Chartierceb07b32015-12-10 09:33:21 -08001275 std::unique_ptr<MemMap> image_bitmap_map(MemMap::MapFileAtAddress(nullptr,
1276 bitmap_section.Size(),
1277 PROT_READ, MAP_PRIVATE,
1278 file->Fd(),
1279 image_bitmap_offset,
1280 /*low_4gb*/false,
1281 /*reuse*/false,
1282 image_filename,
1283 error_msg));
1284 if (image_bitmap_map == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001285 *error_msg = StringPrintf("Failed to map image bitmap: %s", error_msg->c_str());
1286 return nullptr;
1287 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001288 // Loaded the map, use the image header from the file now in case we patch it with
1289 // RelocateInPlace.
1290 image_header = reinterpret_cast<ImageHeader*>(map->Begin());
1291 const uint32_t bitmap_index = bitmap_index_.FetchAndAddSequentiallyConsistent(1);
1292 std::string bitmap_name(StringPrintf("imagespace %s live-bitmap %u",
1293 image_filename,
Mathieu Chartier31e89252013-08-28 11:29:12 -07001294 bitmap_index));
Mathieu Chartier2d124ec2016-01-05 18:03:15 -08001295 // Bitmap only needs to cover until the end of the mirror objects section.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001296 const ImageSection& image_objects = image_header->GetImageSection(ImageHeader::kSectionObjects);
1297 // We only want the mirror object, not the ArtFields and ArtMethods.
1298 uint8_t* const image_end = map->Begin() + image_objects.End();
1299 std::unique_ptr<accounting::ContinuousSpaceBitmap> bitmap;
1300 {
1301 TimingLogger::ScopedTiming timing("CreateImageBitmap", &logger);
1302 bitmap.reset(
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001303 accounting::ContinuousSpaceBitmap::CreateFromMemMap(
Mathieu Chartierceb07b32015-12-10 09:33:21 -08001304 bitmap_name,
1305 image_bitmap_map.release(),
1306 reinterpret_cast<uint8_t*>(map->Begin()),
Mathieu Chartier2d124ec2016-01-05 18:03:15 -08001307 image_objects.End()));
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001308 if (bitmap == nullptr) {
1309 *error_msg = StringPrintf("Could not create bitmap '%s'", bitmap_name.c_str());
1310 return nullptr;
1311 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001312 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001313 {
1314 TimingLogger::ScopedTiming timing("RelocateImage", &logger);
1315 if (!RelocateInPlace(*image_header,
1316 map->Begin(),
1317 bitmap.get(),
1318 oat_file,
1319 error_msg)) {
1320 return nullptr;
1321 }
1322 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001323 // We only want the mirror object, not the ArtFields and ArtMethods.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001324 std::unique_ptr<ImageSpace> space(new ImageSpace(image_filename,
1325 image_location,
1326 map.release(),
1327 bitmap.release(),
Mathieu Chartier2d124ec2016-01-05 18:03:15 -08001328 image_end));
Hiroshi Yamauchibd0fb612014-05-20 13:46:00 -07001329
1330 // VerifyImageAllocations() will be called later in Runtime::Init()
1331 // as some class roots like ArtMethod::java_lang_reflect_ArtMethod_
1332 // and ArtField::java_lang_reflect_ArtField_, which are used from
1333 // Object::SizeOf() which VerifyImageAllocations() calls, are not
1334 // set yet at this point.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001335 if (oat_file == nullptr) {
1336 TimingLogger::ScopedTiming timing("OpenOatFile", &logger);
1337 space->oat_file_.reset(space->OpenOatFile(image_filename, error_msg));
1338 if (space->oat_file_ == nullptr) {
1339 DCHECK(!error_msg->empty());
1340 return nullptr;
1341 }
1342 space->oat_file_non_owned_ = space->oat_file_.get();
1343 } else {
1344 space->oat_file_non_owned_ = oat_file;
Nicolas Geoffray1bc977c2016-01-23 14:15:49 +00001345 }
Nicolas Geoffray1bc977c2016-01-23 14:15:49 +00001346
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001347 if (validate_oat_file) {
1348 TimingLogger::ScopedTiming timing("ValidateOatFile", &logger);
1349 if (!space->ValidateOatFile(error_msg)) {
1350 DCHECK(!error_msg->empty());
1351 return nullptr;
1352 }
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001353 }
1354
Vladimir Marko7624d252014-05-02 14:40:15 +01001355 Runtime* runtime = Runtime::Current();
Vladimir Marko7624d252014-05-02 14:40:15 +01001356
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001357 // If oat_file is null, then it is the boot image space. Use oat_file_non_owned_ from the space
1358 // to set the runtime methods.
1359 CHECK_EQ(oat_file != nullptr, image_header->IsAppImage());
1360 if (image_header->IsAppImage()) {
1361 CHECK_EQ(runtime->GetResolutionMethod(),
1362 image_header->GetImageMethod(ImageHeader::kResolutionMethod));
1363 CHECK_EQ(runtime->GetImtConflictMethod(),
1364 image_header->GetImageMethod(ImageHeader::kImtConflictMethod));
1365 CHECK_EQ(runtime->GetImtUnimplementedMethod(),
1366 image_header->GetImageMethod(ImageHeader::kImtUnimplementedMethod));
1367 CHECK_EQ(runtime->GetCalleeSaveMethod(Runtime::kSaveAll),
1368 image_header->GetImageMethod(ImageHeader::kCalleeSaveMethod));
1369 CHECK_EQ(runtime->GetCalleeSaveMethod(Runtime::kRefsOnly),
1370 image_header->GetImageMethod(ImageHeader::kRefsOnlySaveMethod));
1371 CHECK_EQ(runtime->GetCalleeSaveMethod(Runtime::kRefsAndArgs),
1372 image_header->GetImageMethod(ImageHeader::kRefsAndArgsSaveMethod));
1373 } else if (!runtime->HasResolutionMethod()) {
1374 runtime->SetInstructionSet(space->oat_file_non_owned_->GetOatHeader().GetInstructionSet());
1375 runtime->SetResolutionMethod(image_header->GetImageMethod(ImageHeader::kResolutionMethod));
1376 runtime->SetImtConflictMethod(image_header->GetImageMethod(ImageHeader::kImtConflictMethod));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001377 runtime->SetImtUnimplementedMethod(
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001378 image_header->GetImageMethod(ImageHeader::kImtUnimplementedMethod));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001379 runtime->SetCalleeSaveMethod(
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001380 image_header->GetImageMethod(ImageHeader::kCalleeSaveMethod), Runtime::kSaveAll);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001381 runtime->SetCalleeSaveMethod(
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001382 image_header->GetImageMethod(ImageHeader::kRefsOnlySaveMethod), Runtime::kRefsOnly);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001383 runtime->SetCalleeSaveMethod(
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001384 image_header->GetImageMethod(ImageHeader::kRefsAndArgsSaveMethod), Runtime::kRefsAndArgs);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001385 }
Vladimir Marko7624d252014-05-02 14:40:15 +01001386
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001387 VLOG(image) << "ImageSpace::Init exiting " << *space.get();
1388 if (VLOG_IS_ON(image)) {
1389 logger.Dump(LOG(INFO));
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001390 }
1391 return space.release();
1392}
1393
Nicolas Geoffray9583fbc2014-02-28 15:21:07 +00001394OatFile* ImageSpace::OpenOatFile(const char* image_path, std::string* error_msg) const {
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001395 const ImageHeader& image_header = GetImageHeader();
Nicolas Geoffray9583fbc2014-02-28 15:21:07 +00001396 std::string oat_filename = ImageHeader::GetOatLocationFromImageLocation(image_path);
1397
Igor Murashkin46774762014-10-22 11:37:02 -07001398 CHECK(image_header.GetOatDataBegin() != nullptr);
1399
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -07001400 OatFile* oat_file = OatFile::Open(oat_filename,
1401 oat_filename,
1402 image_header.GetOatDataBegin(),
Igor Murashkin46774762014-10-22 11:37:02 -07001403 image_header.GetOatFileBegin(),
Richard Uhlere5fed032015-03-18 08:21:11 -07001404 !Runtime::Current()->IsAotCompiler(),
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001405 /*low_4gb*/false,
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -07001406 nullptr,
1407 error_msg);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001408 if (oat_file == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001409 *error_msg = StringPrintf("Failed to open oat file '%s' referenced from image %s: %s",
1410 oat_filename.c_str(), GetName(), error_msg->c_str());
1411 return nullptr;
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001412 }
1413 uint32_t oat_checksum = oat_file->GetOatHeader().GetChecksum();
1414 uint32_t image_oat_checksum = image_header.GetOatChecksum();
1415 if (oat_checksum != image_oat_checksum) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001416 *error_msg = StringPrintf("Failed to match oat file checksum 0x%x to expected oat checksum 0x%x"
1417 " in image %s", oat_checksum, image_oat_checksum, GetName());
1418 return nullptr;
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001419 }
Alex Lighta59dd802014-07-02 16:28:08 -07001420 int32_t image_patch_delta = image_header.GetPatchDelta();
1421 int32_t oat_patch_delta = oat_file->GetOatHeader().GetImagePatchDelta();
Igor Murashkin46774762014-10-22 11:37:02 -07001422 if (oat_patch_delta != image_patch_delta && !image_header.CompilePic()) {
Alex Lighta59dd802014-07-02 16:28:08 -07001423 // We should have already relocated by this point. Bail out.
1424 *error_msg = StringPrintf("Failed to match oat file patch delta %d to expected patch delta %d "
1425 "in image %s", oat_patch_delta, image_patch_delta, GetName());
1426 return nullptr;
1427 }
1428
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001429 return oat_file;
1430}
1431
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001432bool ImageSpace::ValidateOatFile(std::string* error_msg) const {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001433 CHECK(oat_file_.get() != nullptr);
Mathieu Chartier31e89252013-08-28 11:29:12 -07001434 for (const OatFile::OatDexFile* oat_dex_file : oat_file_->GetOatDexFiles()) {
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001435 const std::string& dex_file_location = oat_dex_file->GetDexFileLocation();
1436 uint32_t dex_file_location_checksum;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001437 if (!DexFile::GetChecksum(dex_file_location.c_str(), &dex_file_location_checksum, error_msg)) {
1438 *error_msg = StringPrintf("Failed to get checksum of dex file '%s' referenced by image %s: "
1439 "%s", dex_file_location.c_str(), GetName(), error_msg->c_str());
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001440 return false;
1441 }
1442 if (dex_file_location_checksum != oat_dex_file->GetDexFileLocationChecksum()) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001443 *error_msg = StringPrintf("ValidateOatFile found checksum mismatch between oat file '%s' and "
1444 "dex file '%s' (0x%x != 0x%x)",
1445 oat_file_->GetLocation().c_str(), dex_file_location.c_str(),
1446 oat_dex_file->GetDexFileLocationChecksum(),
1447 dex_file_location_checksum);
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001448 return false;
1449 }
1450 }
1451 return true;
1452}
1453
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001454const OatFile* ImageSpace::GetOatFile() const {
Andreas Gampe88da3b02015-06-12 20:38:49 -07001455 return oat_file_non_owned_;
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001456}
1457
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -07001458std::unique_ptr<const OatFile> ImageSpace::ReleaseOatFile() {
1459 CHECK(oat_file_ != nullptr);
1460 return std::move(oat_file_);
Ian Rogers1d54e732013-05-02 21:10:01 -07001461}
1462
Ian Rogers1d54e732013-05-02 21:10:01 -07001463void ImageSpace::Dump(std::ostream& os) const {
1464 os << GetType()
Mathieu Chartier590fee92013-09-13 13:46:47 -07001465 << " begin=" << reinterpret_cast<void*>(Begin())
Ian Rogers1d54e732013-05-02 21:10:01 -07001466 << ",end=" << reinterpret_cast<void*>(End())
1467 << ",size=" << PrettySize(Size())
1468 << ",name=\"" << GetName() << "\"]";
1469}
1470
Andreas Gampe8994a042015-12-30 19:03:17 +00001471void ImageSpace::CreateMultiImageLocations(const std::string& input_image_file_name,
1472 const std::string& boot_classpath,
1473 std::vector<std::string>* image_file_names) {
1474 DCHECK(image_file_names != nullptr);
1475
1476 std::vector<std::string> images;
1477 Split(boot_classpath, ':', &images);
1478
1479 // Add the rest into the list. We have to adjust locations, possibly:
1480 //
1481 // For example, image_file_name is /a/b/c/d/e.art
1482 // images[0] is f/c/d/e.art
1483 // ----------------------------------------------
1484 // images[1] is g/h/i/j.art -> /a/b/h/i/j.art
Mathieu Chartier8b8f6d62016-03-08 16:50:20 -08001485 const std::string& first_image = images[0];
1486 // Length of common suffix.
1487 size_t common = 0;
1488 while (common < input_image_file_name.size() &&
1489 common < first_image.size() &&
1490 *(input_image_file_name.end() - common - 1) == *(first_image.end() - common - 1)) {
1491 ++common;
Andreas Gampe8994a042015-12-30 19:03:17 +00001492 }
Mathieu Chartier8b8f6d62016-03-08 16:50:20 -08001493 // We want to replace the prefix of the input image with the prefix of the boot class path.
1494 // This handles the case where the image file contains @ separators.
1495 // Example image_file_name is oats/system@framework@boot.art
1496 // images[0] is .../arm/boot.art
1497 // means that the image name prefix will be oats/system@framework@
1498 // so that the other images are openable.
1499 const size_t old_prefix_length = first_image.size() - common;
1500 const std::string new_prefix = input_image_file_name.substr(
1501 0,
1502 input_image_file_name.size() - common);
Andreas Gampe8994a042015-12-30 19:03:17 +00001503
1504 // Apply pattern to images[1] .. images[n].
1505 for (size_t i = 1; i < images.size(); ++i) {
Mathieu Chartier8b8f6d62016-03-08 16:50:20 -08001506 const std::string& image = images[i];
1507 CHECK_GT(image.length(), old_prefix_length);
1508 std::string suffix = image.substr(old_prefix_length);
1509 image_file_names->push_back(new_prefix + suffix);
Andreas Gampe8994a042015-12-30 19:03:17 +00001510 }
1511}
1512
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001513ImageSpace* ImageSpace::CreateFromAppImage(const char* image,
1514 const OatFile* oat_file,
1515 std::string* error_msg) {
1516 return gc::space::ImageSpace::Init(image,
1517 image,
1518 /*validate_oat_file*/false,
1519 oat_file,
1520 /*out*/error_msg);
1521}
1522
Ian Rogers1d54e732013-05-02 21:10:01 -07001523} // namespace space
1524} // namespace gc
1525} // namespace art