blob: d140b754ff630344395a91a55aac4baee4720af7 [file] [log] [blame]
Ian Rogers1d54e732013-05-02 21:10:01 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "image_space.h"
18
Mathieu Chartierceb07b32015-12-10 09:33:21 -080019#include <lz4.h>
20#include <random>
Andreas Gampe70be1fb2014-10-31 16:45:19 -070021#include <sys/statvfs.h>
Alex Light25396132014-08-27 15:37:23 -070022#include <sys/types.h>
Narayan Kamath5a2be3f2015-02-16 13:51:51 +000023#include <unistd.h>
Alex Light25396132014-08-27 15:37:23 -070024
Mathieu Chartiere401d142015-04-22 13:56:20 -070025#include "art_method.h"
Andreas Gampe542451c2016-07-26 09:02:02 -070026#include "base/enums.h"
Ian Rogersc7dd2952014-10-21 23:31:19 -070027#include "base/macros.h"
Brian Carlstrom56d947f2013-07-15 13:14:23 -070028#include "base/stl_util.h"
Narayan Kamathd1c606f2014-06-09 16:50:19 +010029#include "base/scoped_flock.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080030#include "base/systrace.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010031#include "base/time_utils.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070032#include "gc/accounting/space_bitmap-inl.h"
Mathieu Chartier4a26f172016-01-26 14:26:18 -080033#include "image-inl.h"
Andreas Gampebec63582015-11-20 19:26:51 -080034#include "image_space_fs.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070035#include "mirror/class-inl.h"
36#include "mirror/object-inl.h"
Brian Carlstrom56d947f2013-07-15 13:14:23 -070037#include "oat_file.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070038#include "os.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070039#include "space-inl.h"
40#include "utils.h"
41
42namespace art {
43namespace gc {
44namespace space {
45
Ian Rogersef7d42f2014-01-06 12:55:46 -080046Atomic<uint32_t> ImageSpace::bitmap_index_(0);
Ian Rogers1d54e732013-05-02 21:10:01 -070047
Jeff Haodcdc85b2015-12-04 14:06:18 -080048ImageSpace::ImageSpace(const std::string& image_filename,
49 const char* image_location,
50 MemMap* mem_map,
51 accounting::ContinuousSpaceBitmap* live_bitmap,
Mathieu Chartier2d124ec2016-01-05 18:03:15 -080052 uint8_t* end)
53 : MemMapSpace(image_filename,
54 mem_map,
55 mem_map->Begin(),
56 end,
57 end,
Narayan Kamath52f84882014-05-02 10:10:39 +010058 kGcRetentionPolicyNeverCollect),
Jeff Haodcdc85b2015-12-04 14:06:18 -080059 oat_file_non_owned_(nullptr),
Mathieu Chartier2d124ec2016-01-05 18:03:15 -080060 image_location_(image_location) {
Mathieu Chartier590fee92013-09-13 13:46:47 -070061 DCHECK(live_bitmap != nullptr);
Mathieu Chartier31e89252013-08-28 11:29:12 -070062 live_bitmap_.reset(live_bitmap);
Ian Rogers1d54e732013-05-02 21:10:01 -070063}
64
Alex Lightcf4bf382014-07-24 11:29:14 -070065static int32_t ChooseRelocationOffsetDelta(int32_t min_delta, int32_t max_delta) {
66 CHECK_ALIGNED(min_delta, kPageSize);
67 CHECK_ALIGNED(max_delta, kPageSize);
68 CHECK_LT(min_delta, max_delta);
69
Alex Light15324762015-11-19 11:03:10 -080070 int32_t r = GetRandomNumber<int32_t>(min_delta, max_delta);
Alex Lightcf4bf382014-07-24 11:29:14 -070071 if (r % 2 == 0) {
72 r = RoundUp(r, kPageSize);
73 } else {
74 r = RoundDown(r, kPageSize);
75 }
76 CHECK_LE(min_delta, r);
77 CHECK_GE(max_delta, r);
78 CHECK_ALIGNED(r, kPageSize);
79 return r;
80}
81
Alex Light25396132014-08-27 15:37:23 -070082static bool GenerateImage(const std::string& image_filename, InstructionSet image_isa,
83 std::string* error_msg) {
Brian Carlstrom56d947f2013-07-15 13:14:23 -070084 const std::string boot_class_path_string(Runtime::Current()->GetBootClassPathString());
85 std::vector<std::string> boot_class_path;
Ian Rogers6f3dbba2014-10-14 17:41:57 -070086 Split(boot_class_path_string, ':', &boot_class_path);
Brian Carlstrom56d947f2013-07-15 13:14:23 -070087 if (boot_class_path.empty()) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -070088 *error_msg = "Failed to generate image because no boot class path specified";
89 return false;
Brian Carlstrom56d947f2013-07-15 13:14:23 -070090 }
Alex Light25396132014-08-27 15:37:23 -070091 // We should clean up so we are more likely to have room for the image.
92 if (Runtime::Current()->IsZygote()) {
Andreas Gampe3c13a792014-09-18 20:56:04 -070093 LOG(INFO) << "Pruning dalvik-cache since we are generating an image and will need to recompile";
Narayan Kamath28bc9872014-11-07 17:46:28 +000094 PruneDalvikCache(image_isa);
Alex Light25396132014-08-27 15:37:23 -070095 }
Brian Carlstrom56d947f2013-07-15 13:14:23 -070096
Mathieu Chartier8bbc8c02013-07-31 16:27:01 -070097 std::vector<std::string> arg_vector;
Brian Carlstrom56d947f2013-07-15 13:14:23 -070098
Tsu Chiang Chuang12e6d742014-05-22 10:22:25 -070099 std::string dex2oat(Runtime::Current()->GetCompilerExecutable());
Mathieu Chartier08d7d442013-07-31 18:08:51 -0700100 arg_vector.push_back(dex2oat);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700101
102 std::string image_option_string("--image=");
Narayan Kamath52f84882014-05-02 10:10:39 +0100103 image_option_string += image_filename;
Mathieu Chartier8bbc8c02013-07-31 16:27:01 -0700104 arg_vector.push_back(image_option_string);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700105
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700106 for (size_t i = 0; i < boot_class_path.size(); i++) {
Mathieu Chartier8bbc8c02013-07-31 16:27:01 -0700107 arg_vector.push_back(std::string("--dex-file=") + boot_class_path[i]);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700108 }
109
110 std::string oat_file_option_string("--oat-file=");
Brian Carlstrom2f1e15c2014-10-27 16:27:06 -0700111 oat_file_option_string += ImageHeader::GetOatLocationFromImageLocation(image_filename);
Mathieu Chartier8bbc8c02013-07-31 16:27:01 -0700112 arg_vector.push_back(oat_file_option_string);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700113
Sebastien Hertz0de11332015-05-13 12:14:05 +0200114 // Note: we do not generate a fully debuggable boot image so we do not pass the
115 // compiler flag --debuggable here.
116
Igor Murashkinb1d8c312015-08-04 11:18:43 -0700117 Runtime::Current()->AddCurrentRuntimeFeaturesAsDex2OatArguments(&arg_vector);
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700118 CHECK_EQ(image_isa, kRuntimeISA)
119 << "We should always be generating an image for the current isa.";
Ian Rogers8afeb852014-04-02 14:55:49 -0700120
Alex Lightcf4bf382014-07-24 11:29:14 -0700121 int32_t base_offset = ChooseRelocationOffsetDelta(ART_BASE_ADDRESS_MIN_DELTA,
122 ART_BASE_ADDRESS_MAX_DELTA);
123 LOG(INFO) << "Using an offset of 0x" << std::hex << base_offset << " from default "
124 << "art base address of 0x" << std::hex << ART_BASE_ADDRESS;
125 arg_vector.push_back(StringPrintf("--base=0x%x", ART_BASE_ADDRESS + base_offset));
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700126
Brian Carlstrom57309db2014-07-30 15:13:25 -0700127 if (!kIsTargetBuild) {
Mathieu Chartier8bbc8c02013-07-31 16:27:01 -0700128 arg_vector.push_back("--host");
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700129 }
130
Brian Carlstrom6449c622014-02-10 23:48:36 -0800131 const std::vector<std::string>& compiler_options = Runtime::Current()->GetImageCompilerOptions();
Brian Carlstrom2ec65202014-03-03 15:16:37 -0800132 for (size_t i = 0; i < compiler_options.size(); ++i) {
Brian Carlstrom6449c622014-02-10 23:48:36 -0800133 arg_vector.push_back(compiler_options[i].c_str());
134 }
135
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700136 std::string command_line(Join(arg_vector, ' '));
137 LOG(INFO) << "GenerateImage: " << command_line;
Brian Carlstrom6449c622014-02-10 23:48:36 -0800138 return Exec(arg_vector, error_msg);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700139}
140
Narayan Kamath52f84882014-05-02 10:10:39 +0100141bool ImageSpace::FindImageFilename(const char* image_location,
142 const InstructionSet image_isa,
Alex Lighta59dd802014-07-02 16:28:08 -0700143 std::string* system_filename,
144 bool* has_system,
145 std::string* cache_filename,
146 bool* dalvik_cache_exists,
Andreas Gampe3c13a792014-09-18 20:56:04 -0700147 bool* has_cache,
148 bool* is_global_cache) {
Alex Lighta59dd802014-07-02 16:28:08 -0700149 *has_system = false;
150 *has_cache = false;
Brian Carlstrom0e12bdc2014-05-14 17:44:28 -0700151 // image_location = /system/framework/boot.art
152 // system_image_location = /system/framework/<image_isa>/boot.art
153 std::string system_image_filename(GetSystemImageFilename(image_location, image_isa));
154 if (OS::FileExists(system_image_filename.c_str())) {
Alex Lighta59dd802014-07-02 16:28:08 -0700155 *system_filename = system_image_filename;
156 *has_system = true;
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700157 }
Narayan Kamath52f84882014-05-02 10:10:39 +0100158
Alex Lighta59dd802014-07-02 16:28:08 -0700159 bool have_android_data = false;
160 *dalvik_cache_exists = false;
161 std::string dalvik_cache;
162 GetDalvikCache(GetInstructionSetString(image_isa), true, &dalvik_cache,
Andreas Gampe3c13a792014-09-18 20:56:04 -0700163 &have_android_data, dalvik_cache_exists, is_global_cache);
Narayan Kamath52f84882014-05-02 10:10:39 +0100164
Alex Lighta59dd802014-07-02 16:28:08 -0700165 if (have_android_data && *dalvik_cache_exists) {
166 // Always set output location even if it does not exist,
167 // so that the caller knows where to create the image.
168 //
169 // image_location = /system/framework/boot.art
170 // *image_filename = /data/dalvik-cache/<image_isa>/boot.art
171 std::string error_msg;
172 if (!GetDalvikCacheFilename(image_location, dalvik_cache.c_str(), cache_filename, &error_msg)) {
173 LOG(WARNING) << error_msg;
174 return *has_system;
175 }
176 *has_cache = OS::FileExists(cache_filename->c_str());
177 }
178 return *has_system || *has_cache;
179}
180
181static bool ReadSpecificImageHeader(const char* filename, ImageHeader* image_header) {
182 std::unique_ptr<File> image_file(OS::OpenFileForReading(filename));
183 if (image_file.get() == nullptr) {
184 return false;
185 }
186 const bool success = image_file->ReadFully(image_header, sizeof(ImageHeader));
187 if (!success || !image_header->IsValid()) {
188 return false;
189 }
190 return true;
191}
192
Alex Light6e183f22014-07-18 14:57:04 -0700193// Relocate the image at image_location to dest_filename and relocate it by a random amount.
194static bool RelocateImage(const char* image_location, const char* dest_filename,
Alex Lighta59dd802014-07-02 16:28:08 -0700195 InstructionSet isa, std::string* error_msg) {
Alex Light25396132014-08-27 15:37:23 -0700196 // We should clean up so we are more likely to have room for the image.
197 if (Runtime::Current()->IsZygote()) {
198 LOG(INFO) << "Pruning dalvik-cache since we are relocating an image and will need to recompile";
Narayan Kamath28bc9872014-11-07 17:46:28 +0000199 PruneDalvikCache(isa);
Alex Light25396132014-08-27 15:37:23 -0700200 }
201
Alex Lighta59dd802014-07-02 16:28:08 -0700202 std::string patchoat(Runtime::Current()->GetPatchoatExecutable());
203
204 std::string input_image_location_arg("--input-image-location=");
205 input_image_location_arg += image_location;
206
207 std::string output_image_filename_arg("--output-image-file=");
208 output_image_filename_arg += dest_filename;
209
Alex Lighta59dd802014-07-02 16:28:08 -0700210 std::string instruction_set_arg("--instruction-set=");
211 instruction_set_arg += GetInstructionSetString(isa);
212
213 std::string base_offset_arg("--base-offset-delta=");
214 StringAppendF(&base_offset_arg, "%d", ChooseRelocationOffsetDelta(ART_BASE_ADDRESS_MIN_DELTA,
215 ART_BASE_ADDRESS_MAX_DELTA));
216
217 std::vector<std::string> argv;
218 argv.push_back(patchoat);
219
220 argv.push_back(input_image_location_arg);
221 argv.push_back(output_image_filename_arg);
222
Alex Lighta59dd802014-07-02 16:28:08 -0700223 argv.push_back(instruction_set_arg);
224 argv.push_back(base_offset_arg);
225
226 std::string command_line(Join(argv, ' '));
227 LOG(INFO) << "RelocateImage: " << command_line;
228 return Exec(argv, error_msg);
229}
230
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700231static ImageHeader* ReadSpecificImageHeader(const char* filename, std::string* error_msg) {
Alex Lighta59dd802014-07-02 16:28:08 -0700232 std::unique_ptr<ImageHeader> hdr(new ImageHeader);
233 if (!ReadSpecificImageHeader(filename, hdr.get())) {
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700234 *error_msg = StringPrintf("Unable to read image header for %s", filename);
Alex Lighta59dd802014-07-02 16:28:08 -0700235 return nullptr;
236 }
237 return hdr.release();
Narayan Kamath52f84882014-05-02 10:10:39 +0100238}
239
240ImageHeader* ImageSpace::ReadImageHeaderOrDie(const char* image_location,
241 const InstructionSet image_isa) {
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700242 std::string error_msg;
243 ImageHeader* image_header = ReadImageHeader(image_location, image_isa, &error_msg);
244 if (image_header == nullptr) {
245 LOG(FATAL) << error_msg;
246 }
247 return image_header;
248}
249
250ImageHeader* ImageSpace::ReadImageHeader(const char* image_location,
251 const InstructionSet image_isa,
252 std::string* error_msg) {
Alex Lighta59dd802014-07-02 16:28:08 -0700253 std::string system_filename;
254 bool has_system = false;
255 std::string cache_filename;
256 bool has_cache = false;
257 bool dalvik_cache_exists = false;
Andreas Gampe3c13a792014-09-18 20:56:04 -0700258 bool is_global_cache = false;
Alex Lighta59dd802014-07-02 16:28:08 -0700259 if (FindImageFilename(image_location, image_isa, &system_filename, &has_system,
Andreas Gampe3c13a792014-09-18 20:56:04 -0700260 &cache_filename, &dalvik_cache_exists, &has_cache, &is_global_cache)) {
Alex Lighta59dd802014-07-02 16:28:08 -0700261 if (Runtime::Current()->ShouldRelocate()) {
262 if (has_system && has_cache) {
263 std::unique_ptr<ImageHeader> sys_hdr(new ImageHeader);
264 std::unique_ptr<ImageHeader> cache_hdr(new ImageHeader);
265 if (!ReadSpecificImageHeader(system_filename.c_str(), sys_hdr.get())) {
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700266 *error_msg = StringPrintf("Unable to read image header for %s at %s",
267 image_location, system_filename.c_str());
Alex Lighta59dd802014-07-02 16:28:08 -0700268 return nullptr;
269 }
270 if (!ReadSpecificImageHeader(cache_filename.c_str(), cache_hdr.get())) {
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700271 *error_msg = StringPrintf("Unable to read image header for %s at %s",
272 image_location, cache_filename.c_str());
Alex Lighta59dd802014-07-02 16:28:08 -0700273 return nullptr;
274 }
275 if (sys_hdr->GetOatChecksum() != cache_hdr->GetOatChecksum()) {
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700276 *error_msg = StringPrintf("Unable to find a relocated version of image file %s",
277 image_location);
Alex Lighta59dd802014-07-02 16:28:08 -0700278 return nullptr;
279 }
280 return cache_hdr.release();
281 } else if (!has_cache) {
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700282 *error_msg = StringPrintf("Unable to find a relocated version of image file %s",
283 image_location);
Alex Lighta59dd802014-07-02 16:28:08 -0700284 return nullptr;
285 } else if (!has_system && has_cache) {
286 // This can probably just use the cache one.
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700287 return ReadSpecificImageHeader(cache_filename.c_str(), error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -0700288 }
289 } else {
290 // We don't want to relocate, Just pick the appropriate one if we have it and return.
291 if (has_system && has_cache) {
292 // We want the cache if the checksum matches, otherwise the system.
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700293 std::unique_ptr<ImageHeader> system(ReadSpecificImageHeader(system_filename.c_str(),
294 error_msg));
295 std::unique_ptr<ImageHeader> cache(ReadSpecificImageHeader(cache_filename.c_str(),
296 error_msg));
Alex Lighta59dd802014-07-02 16:28:08 -0700297 if (system.get() == nullptr ||
298 (cache.get() != nullptr && cache->GetOatChecksum() == system->GetOatChecksum())) {
299 return cache.release();
300 } else {
301 return system.release();
302 }
303 } else if (has_system) {
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700304 return ReadSpecificImageHeader(system_filename.c_str(), error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -0700305 } else if (has_cache) {
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700306 return ReadSpecificImageHeader(cache_filename.c_str(), error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -0700307 }
Narayan Kamath52f84882014-05-02 10:10:39 +0100308 }
Narayan Kamath52f84882014-05-02 10:10:39 +0100309 }
310
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700311 *error_msg = StringPrintf("Unable to find image file for %s", image_location);
Narayan Kamath52f84882014-05-02 10:10:39 +0100312 return nullptr;
313}
314
Alex Lighta59dd802014-07-02 16:28:08 -0700315static bool ChecksumsMatch(const char* image_a, const char* image_b) {
316 ImageHeader hdr_a;
317 ImageHeader hdr_b;
318 return ReadSpecificImageHeader(image_a, &hdr_a) && ReadSpecificImageHeader(image_b, &hdr_b)
319 && hdr_a.GetOatChecksum() == hdr_b.GetOatChecksum();
320}
321
Andreas Gampe3c13a792014-09-18 20:56:04 -0700322static bool ImageCreationAllowed(bool is_global_cache, std::string* error_msg) {
323 // Anyone can write into a "local" cache.
324 if (!is_global_cache) {
325 return true;
326 }
327
328 // Only the zygote is allowed to create the global boot image.
329 if (Runtime::Current()->IsZygote()) {
330 return true;
331 }
332
333 *error_msg = "Only the zygote can create the global boot image.";
334 return false;
335}
336
Andreas Gampe70be1fb2014-10-31 16:45:19 -0700337static constexpr uint64_t kLowSpaceValue = 50 * MB;
338static constexpr uint64_t kTmpFsSentinelValue = 384 * MB;
339
340// Read the free space of the cache partition and make a decision whether to keep the generated
341// image. This is to try to mitigate situations where the system might run out of space later.
342static bool CheckSpace(const std::string& cache_filename, std::string* error_msg) {
343 // Using statvfs vs statvfs64 because of b/18207376, and it is enough for all practical purposes.
344 struct statvfs buf;
345
346 int res = TEMP_FAILURE_RETRY(statvfs(cache_filename.c_str(), &buf));
347 if (res != 0) {
348 // Could not stat. Conservatively tell the system to delete the image.
349 *error_msg = "Could not stat the filesystem, assuming low-memory situation.";
350 return false;
351 }
352
353 uint64_t fs_overall_size = buf.f_bsize * static_cast<uint64_t>(buf.f_blocks);
354 // Zygote is privileged, but other things are not. Use bavail.
355 uint64_t fs_free_size = buf.f_bsize * static_cast<uint64_t>(buf.f_bavail);
356
357 // Take the overall size as an indicator for a tmpfs, which is being used for the decryption
358 // environment. We do not want to fail quickening the boot image there, as it is beneficial
359 // for time-to-UI.
360 if (fs_overall_size > kTmpFsSentinelValue) {
361 if (fs_free_size < kLowSpaceValue) {
362 *error_msg = StringPrintf("Low-memory situation: only %4.2f megabytes available after image"
363 " generation, need at least %" PRIu64 ".",
364 static_cast<double>(fs_free_size) / MB,
365 kLowSpaceValue / MB);
366 return false;
367 }
368 }
369 return true;
370}
371
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800372ImageSpace* ImageSpace::CreateBootImage(const char* image_location,
373 const InstructionSet image_isa,
374 bool secondary_image,
375 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800376 ScopedTrace trace(__FUNCTION__);
Alex Lighta59dd802014-07-02 16:28:08 -0700377 std::string system_filename;
378 bool has_system = false;
379 std::string cache_filename;
380 bool has_cache = false;
381 bool dalvik_cache_exists = false;
Andreas Gampe3c13a792014-09-18 20:56:04 -0700382 bool is_global_cache = true;
Andreas Gampebec63582015-11-20 19:26:51 -0800383 bool found_image = FindImageFilename(image_location, image_isa, &system_filename,
384 &has_system, &cache_filename, &dalvik_cache_exists,
385 &has_cache, &is_global_cache);
386
387 // If we're starting with the global cache, and we're the zygote, try to see whether there are
388 // OTA artifacts from the A/B OTA preopting to move over.
389 // (It is structurally simpler to check this here, instead of complicating the compile/relocate
390 // logic below.)
391 const bool is_zygote = Runtime::Current()->IsZygote();
392 if (is_global_cache && is_zygote) {
393 VLOG(startup) << "Checking for A/B OTA data.";
394 TryMoveOTAArtifacts(cache_filename, dalvik_cache_exists);
395
396 // Retry. There are two cases where the old info is outdated:
397 // * There wasn't a boot image before (e.g., some failure on boot), but now the OTA preopted
398 // image has been moved in-place.
399 // * There was a boot image before, and we tried to move the OTA preopted image, but a failure
400 // happened and there is no file anymore.
401 found_image = FindImageFilename(image_location,
402 image_isa,
403 &system_filename,
404 &has_system,
405 &cache_filename,
406 &dalvik_cache_exists,
407 &has_cache,
408 &is_global_cache);
409 }
Narayan Kamathd1c606f2014-06-09 16:50:19 +0100410
Andreas Gampeacc1be32016-04-05 10:26:42 -0700411 if (is_zygote && !secondary_image) {
Narayan Kamath5a2be3f2015-02-16 13:51:51 +0000412 MarkZygoteStart(image_isa, Runtime::Current()->GetZygoteMaxFailedBoots());
Narayan Kamath28bc9872014-11-07 17:46:28 +0000413 }
414
Alex Lighta59dd802014-07-02 16:28:08 -0700415 ImageSpace* space;
416 bool relocate = Runtime::Current()->ShouldRelocate();
Alex Light64ad14d2014-08-19 14:23:13 -0700417 bool can_compile = Runtime::Current()->IsImageDex2OatEnabled();
Narayan Kamathd1c606f2014-06-09 16:50:19 +0100418 if (found_image) {
Alex Lighta59dd802014-07-02 16:28:08 -0700419 const std::string* image_filename;
420 bool is_system = false;
421 bool relocated_version_used = false;
422 if (relocate) {
Alex Light64ad14d2014-08-19 14:23:13 -0700423 if (!dalvik_cache_exists) {
424 *error_msg = StringPrintf("Requiring relocation for image '%s' at '%s' but we do not have "
425 "any dalvik_cache to find/place it in.",
426 image_location, system_filename.c_str());
427 return nullptr;
428 }
Alex Lighta59dd802014-07-02 16:28:08 -0700429 if (has_system) {
430 if (has_cache && ChecksumsMatch(system_filename.c_str(), cache_filename.c_str())) {
431 // We already have a relocated version
432 image_filename = &cache_filename;
433 relocated_version_used = true;
434 } else {
435 // We cannot have a relocated version, Relocate the system one and use it.
Andreas Gampe3c13a792014-09-18 20:56:04 -0700436
437 std::string reason;
438 bool success;
439
440 // Check whether we are allowed to relocate.
441 if (!can_compile) {
442 reason = "Image dex2oat disabled by -Xnoimage-dex2oat.";
443 success = false;
444 } else if (!ImageCreationAllowed(is_global_cache, &reason)) {
445 // Whether we can write to the cache.
446 success = false;
Andreas Gampe8994a042015-12-30 19:03:17 +0000447 } else if (secondary_image) {
Andreas Gampeacc1be32016-04-05 10:26:42 -0700448 if (is_zygote) {
Jeff Haoab4a4d22016-03-14 18:50:49 -0700449 // Secondary image is out of date. Clear cache and exit to let it retry from scratch.
450 LOG(ERROR) << "Cannot patch secondary image '" << image_location
451 << "', clearing dalvik_cache and restarting zygote.";
452 PruneDalvikCache(image_isa);
453 _exit(1);
454 } else {
455 reason = "Should not have to patch secondary image.";
456 success = false;
457 }
Andreas Gampe3c13a792014-09-18 20:56:04 -0700458 } else {
459 // Try to relocate.
460 success = RelocateImage(image_location, cache_filename.c_str(), image_isa, &reason);
461 }
462
463 if (success) {
Alex Lighta59dd802014-07-02 16:28:08 -0700464 relocated_version_used = true;
465 image_filename = &cache_filename;
466 } else {
Andreas Gampe3c13a792014-09-18 20:56:04 -0700467 *error_msg = StringPrintf("Unable to relocate image '%s' from '%s' to '%s': %s",
Alex Light64ad14d2014-08-19 14:23:13 -0700468 image_location, system_filename.c_str(),
469 cache_filename.c_str(), reason.c_str());
Brian Carlstrome9105f72014-10-28 15:53:43 -0700470 // We failed to create files, remove any possibly garbage output.
471 // Since ImageCreationAllowed was true above, we are the zygote
472 // and therefore the only process expected to generate these for
473 // the device.
Narayan Kamath28bc9872014-11-07 17:46:28 +0000474 PruneDalvikCache(image_isa);
Alex Lighta59dd802014-07-02 16:28:08 -0700475 return nullptr;
476 }
477 }
478 } else {
479 CHECK(has_cache);
480 // We can just use cache's since it should be fine. This might or might not be relocated.
481 image_filename = &cache_filename;
482 }
483 } else {
484 if (has_system && has_cache) {
485 // Check they have the same cksum. If they do use the cache. Otherwise system.
486 if (ChecksumsMatch(system_filename.c_str(), cache_filename.c_str())) {
487 image_filename = &cache_filename;
488 relocated_version_used = true;
489 } else {
490 image_filename = &system_filename;
Alex Light1a762132014-07-31 09:32:13 -0700491 is_system = true;
Alex Lighta59dd802014-07-02 16:28:08 -0700492 }
493 } else if (has_system) {
494 image_filename = &system_filename;
Alex Light1a762132014-07-31 09:32:13 -0700495 is_system = true;
Alex Lighta59dd802014-07-02 16:28:08 -0700496 } else {
497 CHECK(has_cache);
498 image_filename = &cache_filename;
499 }
500 }
501 {
502 // Note that we must not use the file descriptor associated with
503 // ScopedFlock::GetFile to Init the image file. We want the file
504 // descriptor (and the associated exclusive lock) to be released when
505 // we leave Create.
506 ScopedFlock image_lock;
Andreas Gampeacc1be32016-04-05 10:26:42 -0700507 // Should this be a RDWR lock? This is only a defensive measure, as at
508 // this point the image should exist.
509 // However, only the zygote can write into the global dalvik-cache, so
510 // restrict to zygote processes, or any process that isn't using
511 // /data/dalvik-cache (which we assume to be allowed to write there).
512 const bool rw_lock = is_zygote || !is_global_cache;
513 image_lock.Init(image_filename->c_str(),
514 rw_lock ? (O_CREAT | O_RDWR) : O_RDONLY /* flags */,
515 true /* block */,
516 error_msg);
Alex Lightb6cabc12014-08-21 09:45:00 -0700517 VLOG(startup) << "Using image file " << image_filename->c_str() << " for image location "
518 << image_location;
Alex Lightb93637a2014-07-31 10:48:46 -0700519 // If we are in /system we can assume the image is good. We can also
520 // assume this if we are using a relocated image (i.e. image checksum
521 // matches) since this is only different by the offset. We need this to
522 // make sure that host tests continue to work.
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800523 // Since we are the boot image, pass null since we load the oat file from the boot image oat
524 // file name.
525 space = ImageSpace::Init(image_filename->c_str(),
526 image_location,
527 !(is_system || relocated_version_used),
528 /* oat_file */nullptr,
529 error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -0700530 }
Narayan Kamath52f84882014-05-02 10:10:39 +0100531 if (space != nullptr) {
532 return space;
533 }
534
Alex Lighta59dd802014-07-02 16:28:08 -0700535 if (relocated_version_used) {
Brian Carlstrome9105f72014-10-28 15:53:43 -0700536 // Something is wrong with the relocated copy (even though checksums match). Cleanup.
537 // This can happen if the .oat is corrupt, since the above only checks the .art checksums.
538 // TODO: Check the oat file validity earlier.
539 *error_msg = StringPrintf("Attempted to use relocated version of %s at %s generated from %s "
540 "but image failed to load: %s",
541 image_location, cache_filename.c_str(), system_filename.c_str(),
542 error_msg->c_str());
Narayan Kamath28bc9872014-11-07 17:46:28 +0000543 PruneDalvikCache(image_isa);
Alex Lighta59dd802014-07-02 16:28:08 -0700544 return nullptr;
545 } else if (is_system) {
Brian Carlstrome9105f72014-10-28 15:53:43 -0700546 // If the /system file exists, it should be up-to-date, don't try to generate it.
Alex Light64ad14d2014-08-19 14:23:13 -0700547 *error_msg = StringPrintf("Failed to load /system image '%s': %s",
548 image_filename->c_str(), error_msg->c_str());
Narayan Kamath52f84882014-05-02 10:10:39 +0100549 return nullptr;
Mathieu Chartierc7cb1902014-03-05 14:41:03 -0800550 } else {
Brian Carlstrome9105f72014-10-28 15:53:43 -0700551 // Otherwise, log a warning and fall through to GenerateImage.
Alex Light64ad14d2014-08-19 14:23:13 -0700552 LOG(WARNING) << *error_msg;
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700553 }
554 }
Narayan Kamath52f84882014-05-02 10:10:39 +0100555
Alex Light64ad14d2014-08-19 14:23:13 -0700556 if (!can_compile) {
557 *error_msg = "Not attempting to compile image because -Xnoimage-dex2oat";
558 return nullptr;
559 } else if (!dalvik_cache_exists) {
560 *error_msg = StringPrintf("No place to put generated image.");
561 return nullptr;
Andreas Gampe3c13a792014-09-18 20:56:04 -0700562 } else if (!ImageCreationAllowed(is_global_cache, error_msg)) {
563 return nullptr;
Andreas Gampe8994a042015-12-30 19:03:17 +0000564 } else if (secondary_image) {
565 *error_msg = "Cannot compile a secondary image.";
566 return nullptr;
Alex Light25396132014-08-27 15:37:23 -0700567 } else if (!GenerateImage(cache_filename, image_isa, error_msg)) {
Alex Light64ad14d2014-08-19 14:23:13 -0700568 *error_msg = StringPrintf("Failed to generate image '%s': %s",
569 cache_filename.c_str(), error_msg->c_str());
Brian Carlstrome9105f72014-10-28 15:53:43 -0700570 // We failed to create files, remove any possibly garbage output.
571 // Since ImageCreationAllowed was true above, we are the zygote
572 // and therefore the only process expected to generate these for
573 // the device.
Narayan Kamath28bc9872014-11-07 17:46:28 +0000574 PruneDalvikCache(image_isa);
Alex Light64ad14d2014-08-19 14:23:13 -0700575 return nullptr;
576 } else {
Andreas Gampe70be1fb2014-10-31 16:45:19 -0700577 // Check whether there is enough space left over after we have generated the image.
578 if (!CheckSpace(cache_filename, error_msg)) {
579 // No. Delete the generated image and try to run out of the dex files.
Narayan Kamath28bc9872014-11-07 17:46:28 +0000580 PruneDalvikCache(image_isa);
Andreas Gampe70be1fb2014-10-31 16:45:19 -0700581 return nullptr;
582 }
583
Alex Lighta59dd802014-07-02 16:28:08 -0700584 // Note that we must not use the file descriptor associated with
585 // ScopedFlock::GetFile to Init the image file. We want the file
586 // descriptor (and the associated exclusive lock) to be released when
587 // we leave Create.
588 ScopedFlock image_lock;
Alex Light64ad14d2014-08-19 14:23:13 -0700589 image_lock.Init(cache_filename.c_str(), error_msg);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800590 space = ImageSpace::Init(cache_filename.c_str(), image_location, true, nullptr, error_msg);
Alex Light64ad14d2014-08-19 14:23:13 -0700591 if (space == nullptr) {
592 *error_msg = StringPrintf("Failed to load generated image '%s': %s",
593 cache_filename.c_str(), error_msg->c_str());
594 }
595 return space;
Alex Lighta59dd802014-07-02 16:28:08 -0700596 }
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700597}
598
Mathieu Chartier31e89252013-08-28 11:29:12 -0700599void ImageSpace::VerifyImageAllocations() {
Ian Rogers13735952014-10-08 12:43:28 -0700600 uint8_t* current = Begin() + RoundUp(sizeof(ImageHeader), kObjectAlignment);
Mathieu Chartier31e89252013-08-28 11:29:12 -0700601 while (current < End()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700602 CHECK_ALIGNED(current, kObjectAlignment);
603 auto* obj = reinterpret_cast<mirror::Object*>(current);
Mathieu Chartier31e89252013-08-28 11:29:12 -0700604 CHECK(obj->GetClass() != nullptr) << "Image object at address " << obj << " has null class";
Mathieu Chartierc7853442015-03-27 14:35:38 -0700605 CHECK(live_bitmap_->Test(obj)) << PrettyTypeOf(obj);
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -0700606 if (kUseBakerOrBrooksReadBarrier) {
607 obj->AssertReadBarrierPointer();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800608 }
Mathieu Chartier31e89252013-08-28 11:29:12 -0700609 current += RoundUp(obj->SizeOf(), kObjectAlignment);
610 }
611}
612
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800613// Helper class for relocating from one range of memory to another.
614class RelocationRange {
615 public:
616 RelocationRange() = default;
617 RelocationRange(const RelocationRange&) = default;
618 RelocationRange(uintptr_t source, uintptr_t dest, uintptr_t length)
619 : source_(source),
620 dest_(dest),
621 length_(length) {}
622
Mathieu Chartier91edc622016-02-16 17:16:01 -0800623 bool InSource(uintptr_t address) const {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800624 return address - source_ < length_;
625 }
626
Mathieu Chartier91edc622016-02-16 17:16:01 -0800627 bool InDest(uintptr_t address) const {
628 return address - dest_ < length_;
629 }
630
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800631 // Translate a source address to the destination space.
632 uintptr_t ToDest(uintptr_t address) const {
Mathieu Chartier91edc622016-02-16 17:16:01 -0800633 DCHECK(InSource(address));
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800634 return address + Delta();
635 }
636
637 // Returns the delta between the dest from the source.
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800638 uintptr_t Delta() const {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800639 return dest_ - source_;
640 }
641
642 uintptr_t Source() const {
643 return source_;
644 }
645
646 uintptr_t Dest() const {
647 return dest_;
648 }
649
650 uintptr_t Length() const {
651 return length_;
652 }
653
654 private:
655 const uintptr_t source_;
656 const uintptr_t dest_;
657 const uintptr_t length_;
658};
659
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800660std::ostream& operator<<(std::ostream& os, const RelocationRange& reloc) {
661 return os << "(" << reinterpret_cast<const void*>(reloc.Source()) << "-"
662 << reinterpret_cast<const void*>(reloc.Source() + reloc.Length()) << ")->("
663 << reinterpret_cast<const void*>(reloc.Dest()) << "-"
664 << reinterpret_cast<const void*>(reloc.Dest() + reloc.Length()) << ")";
665}
666
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800667class FixupVisitor : public ValueObject {
668 public:
669 FixupVisitor(const RelocationRange& boot_image,
670 const RelocationRange& boot_oat,
671 const RelocationRange& app_image,
672 const RelocationRange& app_oat)
673 : boot_image_(boot_image),
674 boot_oat_(boot_oat),
675 app_image_(app_image),
676 app_oat_(app_oat) {}
677
678 // Return the relocated address of a heap object.
679 template <typename T>
680 ALWAYS_INLINE T* ForwardObject(T* src) const {
681 const uintptr_t uint_src = reinterpret_cast<uintptr_t>(src);
Mathieu Chartier91edc622016-02-16 17:16:01 -0800682 if (boot_image_.InSource(uint_src)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800683 return reinterpret_cast<T*>(boot_image_.ToDest(uint_src));
684 }
Mathieu Chartier91edc622016-02-16 17:16:01 -0800685 if (app_image_.InSource(uint_src)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800686 return reinterpret_cast<T*>(app_image_.ToDest(uint_src));
687 }
Mathieu Chartier91edc622016-02-16 17:16:01 -0800688 // Since we are fixing up the app image, there should only be pointers to the app image and
689 // boot image.
690 DCHECK(src == nullptr) << reinterpret_cast<const void*>(src);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800691 return src;
692 }
693
694 // Return the relocated address of a code pointer (contained by an oat file).
695 ALWAYS_INLINE const void* ForwardCode(const void* src) const {
696 const uintptr_t uint_src = reinterpret_cast<uintptr_t>(src);
Mathieu Chartier91edc622016-02-16 17:16:01 -0800697 if (boot_oat_.InSource(uint_src)) {
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800698 return reinterpret_cast<const void*>(boot_oat_.ToDest(uint_src));
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800699 }
Mathieu Chartier91edc622016-02-16 17:16:01 -0800700 if (app_oat_.InSource(uint_src)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800701 return reinterpret_cast<const void*>(app_oat_.ToDest(uint_src));
702 }
Mathieu Chartier91edc622016-02-16 17:16:01 -0800703 DCHECK(src == nullptr) << src;
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800704 return src;
705 }
706
Mathieu Chartier92ec5942016-04-11 12:03:48 -0700707 // Must be called on pointers that already have been relocated to the destination relocation.
708 ALWAYS_INLINE bool IsInAppImage(mirror::Object* object) const {
709 return app_image_.InDest(reinterpret_cast<uintptr_t>(object));
710 }
711
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800712 protected:
713 // Source section.
714 const RelocationRange boot_image_;
715 const RelocationRange boot_oat_;
716 const RelocationRange app_image_;
717 const RelocationRange app_oat_;
718};
719
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800720// Adapt for mirror::Class::FixupNativePointers.
721class FixupObjectAdapter : public FixupVisitor {
722 public:
723 template<typename... Args>
724 explicit FixupObjectAdapter(Args... args) : FixupVisitor(args...) {}
725
726 template <typename T>
727 T* operator()(T* obj) const {
728 return ForwardObject(obj);
729 }
730};
731
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800732class FixupRootVisitor : public FixupVisitor {
733 public:
734 template<typename... Args>
735 explicit FixupRootVisitor(Args... args) : FixupVisitor(args...) {}
736
737 ALWAYS_INLINE void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
738 SHARED_REQUIRES(Locks::mutator_lock_) {
739 if (!root->IsNull()) {
740 VisitRoot(root);
741 }
742 }
743
744 ALWAYS_INLINE void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
745 SHARED_REQUIRES(Locks::mutator_lock_) {
746 mirror::Object* ref = root->AsMirrorPtr();
747 mirror::Object* new_ref = ForwardObject(ref);
748 if (ref != new_ref) {
749 root->Assign(new_ref);
750 }
751 }
752};
753
754class FixupObjectVisitor : public FixupVisitor {
755 public:
756 template<typename... Args>
Mathieu Chartier92ec5942016-04-11 12:03:48 -0700757 explicit FixupObjectVisitor(gc::accounting::ContinuousSpaceBitmap* visited,
Andreas Gampe542451c2016-07-26 09:02:02 -0700758 const PointerSize pointer_size,
Mathieu Chartier91edc622016-02-16 17:16:01 -0800759 Args... args)
760 : FixupVisitor(args...),
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800761 pointer_size_(pointer_size),
Mathieu Chartier92ec5942016-04-11 12:03:48 -0700762 visited_(visited) {}
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800763
764 // Fix up separately since we also need to fix up method entrypoints.
765 ALWAYS_INLINE void VisitRootIfNonNull(
766 mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const {}
767
768 ALWAYS_INLINE void VisitRoot(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED)
769 const {}
770
771 ALWAYS_INLINE void operator()(mirror::Object* obj,
772 MemberOffset offset,
773 bool is_static ATTRIBUTE_UNUSED) const
774 NO_THREAD_SAFETY_ANALYSIS {
775 // There could be overlap between ranges, we must avoid visiting the same reference twice.
776 // Avoid the class field since we already fixed it up in FixupClassVisitor.
777 if (offset.Uint32Value() != mirror::Object::ClassOffset().Uint32Value()) {
778 // Space is not yet added to the heap, don't do a read barrier.
779 mirror::Object* ref = obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(
780 offset);
781 // Use SetFieldObjectWithoutWriteBarrier to avoid card marking since we are writing to the
782 // image.
783 obj->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(offset, ForwardObject(ref));
784 }
785 }
786
Mathieu Chartier91edc622016-02-16 17:16:01 -0800787 // Visit a pointer array and forward corresponding native data. Ignores pointer arrays in the
788 // boot image. Uses the bitmap to ensure the same array is not visited multiple times.
789 template <typename Visitor>
Mathieu Chartier92ec5942016-04-11 12:03:48 -0700790 void UpdatePointerArrayContents(mirror::PointerArray* array, const Visitor& visitor) const
Mathieu Chartier91edc622016-02-16 17:16:01 -0800791 NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier92ec5942016-04-11 12:03:48 -0700792 DCHECK(array != nullptr);
793 DCHECK(visitor.IsInAppImage(array));
794 // The bit for the array contents is different than the bit for the array. Since we may have
795 // already visited the array as a long / int array from walking the bitmap without knowing it
796 // was a pointer array.
797 static_assert(kObjectAlignment == 8u, "array bit may be in another object");
798 mirror::Object* const contents_bit = reinterpret_cast<mirror::Object*>(
799 reinterpret_cast<uintptr_t>(array) + kObjectAlignment);
800 // If the bit is not set then the contents have not yet been updated.
801 if (!visited_->Test(contents_bit)) {
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800802 array->Fixup<kVerifyNone, kWithoutReadBarrier>(array, pointer_size_, visitor);
Mathieu Chartier92ec5942016-04-11 12:03:48 -0700803 visited_->Set(contents_bit);
Mathieu Chartier91edc622016-02-16 17:16:01 -0800804 }
805 }
806
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800807 // java.lang.ref.Reference visitor.
808 void operator()(mirror::Class* klass ATTRIBUTE_UNUSED, mirror::Reference* ref) const
809 SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
810 mirror::Object* obj = ref->GetReferent<kWithoutReadBarrier>();
811 ref->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
812 mirror::Reference::ReferentOffset(),
813 ForwardObject(obj));
814 }
815
Goran Jakovljevic0dfb30d2016-04-12 13:11:16 +0200816 void operator()(mirror::Object* obj) const NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier92ec5942016-04-11 12:03:48 -0700817 if (visited_->Test(obj)) {
818 // Already visited.
819 return;
820 }
821 visited_->Set(obj);
822
823 // Handle class specially first since we need it to be updated to properly visit the rest of
824 // the instance fields.
825 {
826 mirror::Class* klass = obj->GetClass<kVerifyNone, kWithoutReadBarrier>();
827 DCHECK(klass != nullptr) << "Null class in image";
828 // No AsClass since our fields aren't quite fixed up yet.
829 mirror::Class* new_klass = down_cast<mirror::Class*>(ForwardObject(klass));
830 if (klass != new_klass) {
831 obj->SetClass<kVerifyNone>(new_klass);
832 }
833 if (new_klass != klass && IsInAppImage(new_klass)) {
834 // Make sure the klass contents are fixed up since we depend on it to walk the fields.
835 operator()(new_klass);
836 }
837 }
838
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800839 obj->VisitReferences</*visit native roots*/false, kVerifyNone, kWithoutReadBarrier>(
840 *this,
841 *this);
Mathieu Chartier92ec5942016-04-11 12:03:48 -0700842 // Note that this code relies on no circular dependencies.
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800843 // We want to use our own class loader and not the one in the image.
844 if (obj->IsClass<kVerifyNone, kWithoutReadBarrier>()) {
Mathieu Chartier92ec5942016-04-11 12:03:48 -0700845 mirror::Class* as_klass = obj->AsClass<kVerifyNone, kWithoutReadBarrier>();
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800846 FixupObjectAdapter visitor(boot_image_, boot_oat_, app_image_, app_oat_);
Mathieu Chartier92ec5942016-04-11 12:03:48 -0700847 as_klass->FixupNativePointers<kVerifyNone, kWithoutReadBarrier>(as_klass,
848 pointer_size_,
849 visitor);
Mathieu Chartier91edc622016-02-16 17:16:01 -0800850 // Deal with the pointer arrays. Use the helper function since multiple classes can reference
851 // the same arrays.
Mathieu Chartier92ec5942016-04-11 12:03:48 -0700852 mirror::PointerArray* const vtable = as_klass->GetVTable<kVerifyNone, kWithoutReadBarrier>();
853 if (vtable != nullptr && IsInAppImage(vtable)) {
854 operator()(vtable);
855 UpdatePointerArrayContents(vtable, visitor);
856 }
857 mirror::IfTable* iftable = as_klass->GetIfTable<kVerifyNone, kWithoutReadBarrier>();
858 // Ensure iftable arrays are fixed up since we need GetMethodArray to return the valid
859 // contents.
860 if (iftable != nullptr && IsInAppImage(iftable)) {
861 operator()(iftable);
Mathieu Chartierdfe02f62016-02-01 20:15:11 -0800862 for (int32_t i = 0, count = iftable->Count(); i < count; ++i) {
863 if (iftable->GetMethodArrayCount<kVerifyNone, kWithoutReadBarrier>(i) > 0) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800864 mirror::PointerArray* methods =
865 iftable->GetMethodArray<kVerifyNone, kWithoutReadBarrier>(i);
Mathieu Chartier92ec5942016-04-11 12:03:48 -0700866 if (visitor.IsInAppImage(methods)) {
867 operator()(methods);
868 DCHECK(methods != nullptr);
869 UpdatePointerArrayContents(methods, visitor);
870 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800871 }
872 }
873 }
874 }
875 }
Mathieu Chartier91edc622016-02-16 17:16:01 -0800876
877 private:
Andreas Gampe542451c2016-07-26 09:02:02 -0700878 const PointerSize pointer_size_;
Mathieu Chartier92ec5942016-04-11 12:03:48 -0700879 gc::accounting::ContinuousSpaceBitmap* const visited_;
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800880};
881
882class ForwardObjectAdapter {
883 public:
Chih-Hung Hsieh471118e2016-04-29 14:27:41 -0700884 ALWAYS_INLINE explicit ForwardObjectAdapter(const FixupVisitor* visitor) : visitor_(visitor) {}
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800885
886 template <typename T>
887 ALWAYS_INLINE T* operator()(T* src) const {
888 return visitor_->ForwardObject(src);
889 }
890
891 private:
892 const FixupVisitor* const visitor_;
893};
894
895class ForwardCodeAdapter {
896 public:
Chih-Hung Hsieh471118e2016-04-29 14:27:41 -0700897 ALWAYS_INLINE explicit ForwardCodeAdapter(const FixupVisitor* visitor)
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800898 : visitor_(visitor) {}
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800899
900 template <typename T>
901 ALWAYS_INLINE T* operator()(T* src) const {
902 return visitor_->ForwardCode(src);
903 }
904
905 private:
906 const FixupVisitor* const visitor_;
907};
908
909class FixupArtMethodVisitor : public FixupVisitor, public ArtMethodVisitor {
910 public:
911 template<typename... Args>
Andreas Gampe542451c2016-07-26 09:02:02 -0700912 explicit FixupArtMethodVisitor(bool fixup_heap_objects, PointerSize pointer_size, Args... args)
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800913 : FixupVisitor(args...),
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800914 fixup_heap_objects_(fixup_heap_objects),
915 pointer_size_(pointer_size) {}
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800916
917 virtual void Visit(ArtMethod* method) NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartiere42888f2016-04-14 10:49:19 -0700918 // TODO: Separate visitor for runtime vs normal methods.
919 if (UNLIKELY(method->IsRuntimeMethod())) {
920 ImtConflictTable* table = method->GetImtConflictTable(pointer_size_);
921 if (table != nullptr) {
922 ImtConflictTable* new_table = ForwardObject(table);
923 if (table != new_table) {
924 method->SetImtConflictTable(new_table, pointer_size_);
925 }
926 }
927 const void* old_code = method->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size_);
928 const void* new_code = ForwardCode(old_code);
929 if (old_code != new_code) {
930 method->SetEntryPointFromQuickCompiledCodePtrSize(new_code, pointer_size_);
931 }
932 } else {
933 if (fixup_heap_objects_) {
934 method->UpdateObjectsForImageRelocation(ForwardObjectAdapter(this), pointer_size_);
935 }
936 method->UpdateEntrypoints<kWithoutReadBarrier>(ForwardCodeAdapter(this), pointer_size_);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800937 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800938 }
939
940 private:
941 const bool fixup_heap_objects_;
Andreas Gampe542451c2016-07-26 09:02:02 -0700942 const PointerSize pointer_size_;
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800943};
944
945class FixupArtFieldVisitor : public FixupVisitor, public ArtFieldVisitor {
946 public:
947 template<typename... Args>
948 explicit FixupArtFieldVisitor(Args... args) : FixupVisitor(args...) {}
949
950 virtual void Visit(ArtField* field) NO_THREAD_SAFETY_ANALYSIS {
951 field->UpdateObjects(ForwardObjectAdapter(this));
952 }
953};
954
955// Relocate an image space mapped at target_base which possibly used to be at a different base
956// address. Only needs a single image space, not one for both source and destination.
957// In place means modifying a single ImageSpace in place rather than relocating from one ImageSpace
958// to another.
959static bool RelocateInPlace(ImageHeader& image_header,
960 uint8_t* target_base,
961 accounting::ContinuousSpaceBitmap* bitmap,
962 const OatFile* app_oat_file,
963 std::string* error_msg) {
964 DCHECK(error_msg != nullptr);
965 if (!image_header.IsPic()) {
966 if (image_header.GetImageBegin() == target_base) {
967 return true;
968 }
969 *error_msg = StringPrintf("Cannot relocate non-pic image for oat file %s",
970 (app_oat_file != nullptr) ? app_oat_file->GetLocation().c_str() : "");
971 return false;
972 }
973 // Set up sections.
974 uint32_t boot_image_begin = 0;
975 uint32_t boot_image_end = 0;
976 uint32_t boot_oat_begin = 0;
977 uint32_t boot_oat_end = 0;
Andreas Gampe542451c2016-07-26 09:02:02 -0700978 const PointerSize pointer_size = image_header.GetPointerSize();
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800979 gc::Heap* const heap = Runtime::Current()->GetHeap();
980 heap->GetBootImagesSize(&boot_image_begin, &boot_image_end, &boot_oat_begin, &boot_oat_end);
Mathieu Chartiere7199262016-04-11 13:56:45 -0700981 if (boot_image_begin == boot_image_end) {
982 *error_msg = "Can not relocate app image without boot image space";
983 return false;
984 }
985 if (boot_oat_begin == boot_oat_end) {
986 *error_msg = "Can not relocate app image without boot oat file";
987 return false;
988 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800989 const uint32_t boot_image_size = boot_image_end - boot_image_begin;
990 const uint32_t boot_oat_size = boot_oat_end - boot_oat_begin;
991 const uint32_t image_header_boot_image_size = image_header.GetBootImageSize();
992 const uint32_t image_header_boot_oat_size = image_header.GetBootOatSize();
993 if (boot_image_size != image_header_boot_image_size) {
994 *error_msg = StringPrintf("Boot image size %" PRIu64 " does not match expected size %"
995 PRIu64,
996 static_cast<uint64_t>(boot_image_size),
997 static_cast<uint64_t>(image_header_boot_image_size));
998 return false;
999 }
1000 if (boot_oat_size != image_header_boot_oat_size) {
1001 *error_msg = StringPrintf("Boot oat size %" PRIu64 " does not match expected size %"
1002 PRIu64,
1003 static_cast<uint64_t>(boot_oat_size),
1004 static_cast<uint64_t>(image_header_boot_oat_size));
1005 return false;
1006 }
1007 TimingLogger logger(__FUNCTION__, true, false);
1008 RelocationRange boot_image(image_header.GetBootImageBegin(),
1009 boot_image_begin,
1010 boot_image_size);
1011 RelocationRange boot_oat(image_header.GetBootOatBegin(),
1012 boot_oat_begin,
1013 boot_oat_size);
1014 RelocationRange app_image(reinterpret_cast<uintptr_t>(image_header.GetImageBegin()),
1015 reinterpret_cast<uintptr_t>(target_base),
1016 image_header.GetImageSize());
1017 // Use the oat data section since this is where the OatFile::Begin is.
1018 RelocationRange app_oat(reinterpret_cast<uintptr_t>(image_header.GetOatDataBegin()),
1019 // Not necessarily in low 4GB.
1020 reinterpret_cast<uintptr_t>(app_oat_file->Begin()),
1021 image_header.GetOatDataEnd() - image_header.GetOatDataBegin());
1022 VLOG(image) << "App image " << app_image;
1023 VLOG(image) << "App oat " << app_oat;
1024 VLOG(image) << "Boot image " << boot_image;
1025 VLOG(image) << "Boot oat " << boot_oat;
1026 // True if we need to fixup any heap pointers, otherwise only code pointers.
1027 const bool fixup_image = boot_image.Delta() != 0 || app_image.Delta() != 0;
1028 const bool fixup_code = boot_oat.Delta() != 0 || app_oat.Delta() != 0;
1029 if (!fixup_image && !fixup_code) {
1030 // Nothing to fix up.
1031 return true;
1032 }
Mathieu Chartierdfe02f62016-02-01 20:15:11 -08001033 ScopedDebugDisallowReadBarriers sddrb(Thread::Current());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001034 // Need to update the image to be at the target base.
1035 const ImageSection& objects_section = image_header.GetImageSection(ImageHeader::kSectionObjects);
1036 uintptr_t objects_begin = reinterpret_cast<uintptr_t>(target_base + objects_section.Offset());
1037 uintptr_t objects_end = reinterpret_cast<uintptr_t>(target_base + objects_section.End());
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001038 FixupObjectAdapter fixup_adapter(boot_image, boot_oat, app_image, app_oat);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001039 if (fixup_image) {
Mathieu Chartier91edc622016-02-16 17:16:01 -08001040 // Two pass approach, fix up all classes first, then fix up non class-objects.
1041 // The visited bitmap is used to ensure that pointer arrays are not forwarded twice.
1042 std::unique_ptr<gc::accounting::ContinuousSpaceBitmap> visited_bitmap(
Mathieu Chartier92ec5942016-04-11 12:03:48 -07001043 gc::accounting::ContinuousSpaceBitmap::Create("Relocate bitmap",
Mathieu Chartier91edc622016-02-16 17:16:01 -08001044 target_base,
1045 image_header.GetImageSize()));
1046 FixupObjectVisitor fixup_object_visitor(visited_bitmap.get(),
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001047 pointer_size,
Mathieu Chartier91edc622016-02-16 17:16:01 -08001048 boot_image,
1049 boot_oat,
1050 app_image,
1051 app_oat);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001052 TimingLogger::ScopedTiming timing("Fixup classes", &logger);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001053 // Fixup objects may read fields in the boot image, use the mutator lock here for sanity. Though
1054 // its probably not required.
1055 ScopedObjectAccess soa(Thread::Current());
1056 timing.NewTiming("Fixup objects");
1057 bitmap->VisitMarkedRange(objects_begin, objects_end, fixup_object_visitor);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001058 // Fixup image roots.
Mathieu Chartier91edc622016-02-16 17:16:01 -08001059 CHECK(app_image.InSource(reinterpret_cast<uintptr_t>(
Mathieu Chartier4a26f172016-01-26 14:26:18 -08001060 image_header.GetImageRoots<kWithoutReadBarrier>())));
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001061 image_header.RelocateImageObjects(app_image.Delta());
1062 CHECK_EQ(image_header.GetImageBegin(), target_base);
1063 // Fix up dex cache DexFile pointers.
Mathieu Chartier4a26f172016-01-26 14:26:18 -08001064 auto* dex_caches = image_header.GetImageRoot<kWithoutReadBarrier>(ImageHeader::kDexCaches)->
Mathieu Chartierdfe02f62016-02-01 20:15:11 -08001065 AsObjectArray<mirror::DexCache, kVerifyNone, kWithoutReadBarrier>();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001066 for (int32_t i = 0, count = dex_caches->GetLength(); i < count; ++i) {
Mathieu Chartier60bc39c2016-01-27 18:37:48 -08001067 mirror::DexCache* dex_cache = dex_caches->Get<kVerifyNone, kWithoutReadBarrier>(i);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001068 // Fix up dex cache pointers.
1069 GcRoot<mirror::String>* strings = dex_cache->GetStrings();
1070 if (strings != nullptr) {
1071 GcRoot<mirror::String>* new_strings = fixup_adapter.ForwardObject(strings);
1072 if (strings != new_strings) {
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001073 dex_cache->SetStrings(new_strings);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001074 }
Mathieu Chartier60bc39c2016-01-27 18:37:48 -08001075 dex_cache->FixupStrings<kWithoutReadBarrier>(new_strings, fixup_adapter);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001076 }
1077 GcRoot<mirror::Class>* types = dex_cache->GetResolvedTypes();
1078 if (types != nullptr) {
1079 GcRoot<mirror::Class>* new_types = fixup_adapter.ForwardObject(types);
1080 if (types != new_types) {
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001081 dex_cache->SetResolvedTypes(new_types);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001082 }
Mathieu Chartier60bc39c2016-01-27 18:37:48 -08001083 dex_cache->FixupResolvedTypes<kWithoutReadBarrier>(new_types, fixup_adapter);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001084 }
1085 ArtMethod** methods = dex_cache->GetResolvedMethods();
1086 if (methods != nullptr) {
1087 ArtMethod** new_methods = fixup_adapter.ForwardObject(methods);
1088 if (methods != new_methods) {
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001089 dex_cache->SetResolvedMethods(new_methods);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001090 }
1091 for (size_t j = 0, num = dex_cache->NumResolvedMethods(); j != num; ++j) {
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001092 ArtMethod* orig = mirror::DexCache::GetElementPtrSize(new_methods, j, pointer_size);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001093 ArtMethod* copy = fixup_adapter.ForwardObject(orig);
1094 if (orig != copy) {
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001095 mirror::DexCache::SetElementPtrSize(new_methods, j, copy, pointer_size);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001096 }
1097 }
1098 }
1099 ArtField** fields = dex_cache->GetResolvedFields();
1100 if (fields != nullptr) {
1101 ArtField** new_fields = fixup_adapter.ForwardObject(fields);
1102 if (fields != new_fields) {
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001103 dex_cache->SetResolvedFields(new_fields);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001104 }
1105 for (size_t j = 0, num = dex_cache->NumResolvedFields(); j != num; ++j) {
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001106 ArtField* orig = mirror::DexCache::GetElementPtrSize(new_fields, j, pointer_size);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001107 ArtField* copy = fixup_adapter.ForwardObject(orig);
1108 if (orig != copy) {
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001109 mirror::DexCache::SetElementPtrSize(new_fields, j, copy, pointer_size);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001110 }
1111 }
1112 }
1113 }
1114 }
1115 {
1116 // Only touches objects in the app image, no need for mutator lock.
1117 TimingLogger::ScopedTiming timing("Fixup methods", &logger);
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001118 FixupArtMethodVisitor method_visitor(fixup_image,
1119 pointer_size,
1120 boot_image,
1121 boot_oat,
1122 app_image,
1123 app_oat);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001124 image_header.VisitPackedArtMethods(&method_visitor, target_base, pointer_size);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001125 }
1126 if (fixup_image) {
1127 {
1128 // Only touches objects in the app image, no need for mutator lock.
1129 TimingLogger::ScopedTiming timing("Fixup fields", &logger);
1130 FixupArtFieldVisitor field_visitor(boot_image, boot_oat, app_image, app_oat);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001131 image_header.VisitPackedArtFields(&field_visitor, target_base);
1132 }
1133 {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001134 TimingLogger::ScopedTiming timing("Fixup imt", &logger);
1135 image_header.VisitPackedImTables(fixup_adapter, target_base, pointer_size);
1136 }
1137 {
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001138 TimingLogger::ScopedTiming timing("Fixup conflict tables", &logger);
1139 image_header.VisitPackedImtConflictTables(fixup_adapter, target_base, pointer_size);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001140 }
1141 // In the app image case, the image methods are actually in the boot image.
1142 image_header.RelocateImageMethods(boot_image.Delta());
1143 const auto& class_table_section = image_header.GetImageSection(ImageHeader::kSectionClassTable);
1144 if (class_table_section.Size() > 0u) {
1145 // Note that we require that ReadFromMemory does not make an internal copy of the elements.
1146 // This also relies on visit roots not doing any verification which could fail after we update
1147 // the roots to be the image addresses.
1148 ScopedObjectAccess soa(Thread::Current());
1149 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
1150 ClassTable temp_table;
1151 temp_table.ReadFromMemory(target_base + class_table_section.Offset());
1152 FixupRootVisitor root_visitor(boot_image, boot_oat, app_image, app_oat);
1153 temp_table.VisitRoots(root_visitor);
1154 }
1155 }
1156 if (VLOG_IS_ON(image)) {
1157 logger.Dump(LOG(INFO));
1158 }
1159 return true;
1160}
1161
Andreas Gampe7fa55782016-06-15 17:45:01 -07001162static MemMap* LoadImageFile(const char* image_filename,
1163 const char* image_location,
1164 const ImageHeader& image_header,
1165 uint8_t* address,
1166 int fd,
1167 TimingLogger& logger,
1168 std::string* error_msg) {
1169 TimingLogger::ScopedTiming timing("MapImageFile", &logger);
1170 const ImageHeader::StorageMode storage_mode = image_header.GetStorageMode();
1171 if (storage_mode == ImageHeader::kStorageModeUncompressed) {
1172 return MemMap::MapFileAtAddress(address,
1173 image_header.GetImageSize(),
1174 PROT_READ | PROT_WRITE,
1175 MAP_PRIVATE,
1176 fd,
1177 0,
1178 /*low_4gb*/true,
1179 /*reuse*/false,
1180 image_filename,
1181 error_msg);
1182 }
1183
1184 if (storage_mode != ImageHeader::kStorageModeLZ4 &&
1185 storage_mode != ImageHeader::kStorageModeLZ4HC) {
1186 *error_msg = StringPrintf("Invalid storage mode in image header %d",
1187 static_cast<int>(storage_mode));
1188 return nullptr;
1189 }
1190
1191 // Reserve output and decompress into it.
1192 std::unique_ptr<MemMap> map(MemMap::MapAnonymous(image_location,
1193 address,
1194 image_header.GetImageSize(),
1195 PROT_READ | PROT_WRITE,
1196 /*low_4gb*/true,
1197 /*reuse*/false,
1198 error_msg));
1199 if (map != nullptr) {
1200 const size_t stored_size = image_header.GetDataSize();
1201 const size_t decompress_offset = sizeof(ImageHeader); // Skip the header.
1202 std::unique_ptr<MemMap> temp_map(MemMap::MapFile(sizeof(ImageHeader) + stored_size,
1203 PROT_READ,
1204 MAP_PRIVATE,
1205 fd,
1206 /*offset*/0,
1207 /*low_4gb*/false,
1208 image_filename,
1209 error_msg));
1210 if (temp_map == nullptr) {
1211 DCHECK(!error_msg->empty());
1212 return nullptr;
1213 }
1214 memcpy(map->Begin(), &image_header, sizeof(ImageHeader));
1215 const uint64_t start = NanoTime();
1216 // LZ4HC and LZ4 have same internal format, both use LZ4_decompress.
1217 TimingLogger::ScopedTiming timing2("LZ4 decompress image", &logger);
1218 const size_t decompressed_size = LZ4_decompress_safe(
1219 reinterpret_cast<char*>(temp_map->Begin()) + sizeof(ImageHeader),
1220 reinterpret_cast<char*>(map->Begin()) + decompress_offset,
1221 stored_size,
1222 map->Size() - decompress_offset);
1223 VLOG(image) << "Decompressing image took " << PrettyDuration(NanoTime() - start);
1224 if (decompressed_size + sizeof(ImageHeader) != image_header.GetImageSize()) {
1225 *error_msg = StringPrintf(
1226 "Decompressed size does not match expected image size %zu vs %zu",
1227 decompressed_size + sizeof(ImageHeader),
1228 image_header.GetImageSize());
1229 return nullptr;
1230 }
1231 }
1232
1233 return map.release();
1234}
1235
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001236ImageSpace* ImageSpace::Init(const char* image_filename,
1237 const char* image_location,
1238 bool validate_oat_file,
1239 const OatFile* oat_file,
1240 std::string* error_msg) {
Narayan Kamath52f84882014-05-02 10:10:39 +01001241 CHECK(image_filename != nullptr);
1242 CHECK(image_location != nullptr);
Ian Rogers1d54e732013-05-02 21:10:01 -07001243
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001244 TimingLogger logger(__PRETTY_FUNCTION__, true, VLOG_IS_ON(image));
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001245 VLOG(image) << "ImageSpace::Init entering image_filename=" << image_filename;
Nicolas Geoffray1bc977c2016-01-23 14:15:49 +00001246
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001247 std::unique_ptr<File> file;
1248 {
1249 TimingLogger::ScopedTiming timing("OpenImageFile", &logger);
1250 file.reset(OS::OpenFileForReading(image_filename));
1251 if (file == nullptr) {
1252 *error_msg = StringPrintf("Failed to open '%s'", image_filename);
1253 return nullptr;
1254 }
Nicolas Geoffray1bc977c2016-01-23 14:15:49 +00001255 }
Andreas Gampe9e276662016-06-15 17:44:21 -07001256 ImageHeader temp_image_header;
1257 ImageHeader* image_header = &temp_image_header;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001258 {
1259 TimingLogger::ScopedTiming timing("ReadImageHeader", &logger);
1260 bool success = file->ReadFully(image_header, sizeof(*image_header));
1261 if (!success || !image_header->IsValid()) {
1262 *error_msg = StringPrintf("Invalid image header in '%s'", image_filename);
1263 return nullptr;
1264 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001265 }
Mathieu Chartierceb07b32015-12-10 09:33:21 -08001266 // Check that the file is larger or equal to the header size + data size.
1267 const uint64_t image_file_size = static_cast<uint64_t>(file->GetLength());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001268 if (image_file_size < sizeof(ImageHeader) + image_header->GetDataSize()) {
Mathieu Chartierceb07b32015-12-10 09:33:21 -08001269 *error_msg = StringPrintf("Image file truncated: %" PRIu64 " vs. %" PRIu64 ".",
1270 image_file_size,
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001271 sizeof(ImageHeader) + image_header->GetDataSize());
Andreas Gampe6c8b49f2015-02-19 11:42:36 -08001272 return nullptr;
1273 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001274
Mathieu Chartier9ff84602016-01-29 12:22:17 -08001275 if (oat_file != nullptr) {
1276 // If we have an oat file, check the oat file checksum. The oat file is only non-null for the
1277 // app image case. Otherwise, we open the oat file after the image and check the checksum there.
1278 const uint32_t oat_checksum = oat_file->GetOatHeader().GetChecksum();
1279 const uint32_t image_oat_checksum = image_header->GetOatChecksum();
1280 if (oat_checksum != image_oat_checksum) {
1281 *error_msg = StringPrintf("Oat checksum 0x%x does not match the image one 0x%x in image %s",
1282 oat_checksum,
1283 image_oat_checksum,
1284 image_filename);
1285 return nullptr;
1286 }
1287 }
1288
Jeff Haodcdc85b2015-12-04 14:06:18 -08001289 if (VLOG_IS_ON(startup)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001290 LOG(INFO) << "Dumping image sections";
1291 for (size_t i = 0; i < ImageHeader::kSectionCount; ++i) {
1292 const auto section_idx = static_cast<ImageHeader::ImageSections>(i);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001293 auto& section = image_header->GetImageSection(section_idx);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001294 LOG(INFO) << section_idx << " start="
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001295 << reinterpret_cast<void*>(image_header->GetImageBegin() + section.Offset()) << " "
1296 << section;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001297 }
1298 }
1299
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001300 const auto& bitmap_section = image_header->GetImageSection(ImageHeader::kSectionImageBitmap);
Mathieu Chartierceb07b32015-12-10 09:33:21 -08001301 // The location we want to map from is the first aligned page after the end of the stored
1302 // (possibly compressed) data.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001303 const size_t image_bitmap_offset = RoundUp(sizeof(ImageHeader) + image_header->GetDataSize(),
Mathieu Chartierceb07b32015-12-10 09:33:21 -08001304 kPageSize);
1305 const size_t end_of_bitmap = image_bitmap_offset + bitmap_section.Size();
Mathieu Chartierc7853442015-03-27 14:35:38 -07001306 if (end_of_bitmap != image_file_size) {
1307 *error_msg = StringPrintf(
1308 "Image file size does not equal end of bitmap: size=%" PRIu64 " vs. %zu.", image_file_size,
1309 end_of_bitmap);
Andreas Gampe6c8b49f2015-02-19 11:42:36 -08001310 return nullptr;
1311 }
1312
Mathieu Chartierceb07b32015-12-10 09:33:21 -08001313 std::unique_ptr<MemMap> map;
Andreas Gampe7fa55782016-06-15 17:45:01 -07001314 // GetImageBegin is the preferred address to map the image. If we manage to map the
1315 // image at the image begin, the amount of fixup work required is minimized.
1316 map.reset(LoadImageFile(image_filename,
1317 image_location,
1318 *image_header,
1319 image_header->GetImageBegin(),
1320 file->Fd(),
1321 logger,
1322 error_msg));
1323 // If the header specifies PIC mode, we can also map at a random low_4gb address since we can
1324 // relocate in-place.
1325 if (map == nullptr && image_header->IsPic()) {
1326 map.reset(LoadImageFile(image_filename,
1327 image_location,
1328 *image_header,
1329 /* address */ nullptr,
1330 file->Fd(),
1331 logger,
1332 error_msg));
Mathieu Chartierceb07b32015-12-10 09:33:21 -08001333 }
Andreas Gampe7fa55782016-06-15 17:45:01 -07001334 // Were we able to load something and continue?
Mathieu Chartier42bddce2015-11-09 15:16:56 -08001335 if (map == nullptr) {
Andreas Gampe7fa55782016-06-15 17:45:01 -07001336 DCHECK(!error_msg->empty());
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001337 return nullptr;
Ian Rogers1d54e732013-05-02 21:10:01 -07001338 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001339 DCHECK_EQ(0, memcmp(image_header, map->Begin(), sizeof(ImageHeader)));
Ian Rogers1d54e732013-05-02 21:10:01 -07001340
Mathieu Chartierceb07b32015-12-10 09:33:21 -08001341 std::unique_ptr<MemMap> image_bitmap_map(MemMap::MapFileAtAddress(nullptr,
1342 bitmap_section.Size(),
1343 PROT_READ, MAP_PRIVATE,
1344 file->Fd(),
1345 image_bitmap_offset,
1346 /*low_4gb*/false,
1347 /*reuse*/false,
1348 image_filename,
1349 error_msg));
1350 if (image_bitmap_map == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001351 *error_msg = StringPrintf("Failed to map image bitmap: %s", error_msg->c_str());
1352 return nullptr;
1353 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001354 // Loaded the map, use the image header from the file now in case we patch it with
1355 // RelocateInPlace.
1356 image_header = reinterpret_cast<ImageHeader*>(map->Begin());
1357 const uint32_t bitmap_index = bitmap_index_.FetchAndAddSequentiallyConsistent(1);
1358 std::string bitmap_name(StringPrintf("imagespace %s live-bitmap %u",
1359 image_filename,
Mathieu Chartier31e89252013-08-28 11:29:12 -07001360 bitmap_index));
Mathieu Chartier2d124ec2016-01-05 18:03:15 -08001361 // Bitmap only needs to cover until the end of the mirror objects section.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001362 const ImageSection& image_objects = image_header->GetImageSection(ImageHeader::kSectionObjects);
1363 // We only want the mirror object, not the ArtFields and ArtMethods.
1364 uint8_t* const image_end = map->Begin() + image_objects.End();
1365 std::unique_ptr<accounting::ContinuousSpaceBitmap> bitmap;
1366 {
1367 TimingLogger::ScopedTiming timing("CreateImageBitmap", &logger);
1368 bitmap.reset(
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001369 accounting::ContinuousSpaceBitmap::CreateFromMemMap(
Mathieu Chartierceb07b32015-12-10 09:33:21 -08001370 bitmap_name,
1371 image_bitmap_map.release(),
1372 reinterpret_cast<uint8_t*>(map->Begin()),
Mathieu Chartier2d124ec2016-01-05 18:03:15 -08001373 image_objects.End()));
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001374 if (bitmap == nullptr) {
1375 *error_msg = StringPrintf("Could not create bitmap '%s'", bitmap_name.c_str());
1376 return nullptr;
1377 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001378 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001379 {
1380 TimingLogger::ScopedTiming timing("RelocateImage", &logger);
1381 if (!RelocateInPlace(*image_header,
1382 map->Begin(),
1383 bitmap.get(),
1384 oat_file,
1385 error_msg)) {
1386 return nullptr;
1387 }
1388 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001389 // We only want the mirror object, not the ArtFields and ArtMethods.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001390 std::unique_ptr<ImageSpace> space(new ImageSpace(image_filename,
1391 image_location,
1392 map.release(),
1393 bitmap.release(),
Mathieu Chartier2d124ec2016-01-05 18:03:15 -08001394 image_end));
Hiroshi Yamauchibd0fb612014-05-20 13:46:00 -07001395
1396 // VerifyImageAllocations() will be called later in Runtime::Init()
1397 // as some class roots like ArtMethod::java_lang_reflect_ArtMethod_
1398 // and ArtField::java_lang_reflect_ArtField_, which are used from
1399 // Object::SizeOf() which VerifyImageAllocations() calls, are not
1400 // set yet at this point.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001401 if (oat_file == nullptr) {
1402 TimingLogger::ScopedTiming timing("OpenOatFile", &logger);
1403 space->oat_file_.reset(space->OpenOatFile(image_filename, error_msg));
1404 if (space->oat_file_ == nullptr) {
1405 DCHECK(!error_msg->empty());
1406 return nullptr;
1407 }
1408 space->oat_file_non_owned_ = space->oat_file_.get();
1409 } else {
1410 space->oat_file_non_owned_ = oat_file;
Nicolas Geoffray1bc977c2016-01-23 14:15:49 +00001411 }
Nicolas Geoffray1bc977c2016-01-23 14:15:49 +00001412
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001413 if (validate_oat_file) {
1414 TimingLogger::ScopedTiming timing("ValidateOatFile", &logger);
1415 if (!space->ValidateOatFile(error_msg)) {
1416 DCHECK(!error_msg->empty());
1417 return nullptr;
1418 }
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001419 }
1420
Vladimir Marko7624d252014-05-02 14:40:15 +01001421 Runtime* runtime = Runtime::Current();
Vladimir Marko7624d252014-05-02 14:40:15 +01001422
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001423 // If oat_file is null, then it is the boot image space. Use oat_file_non_owned_ from the space
1424 // to set the runtime methods.
1425 CHECK_EQ(oat_file != nullptr, image_header->IsAppImage());
1426 if (image_header->IsAppImage()) {
1427 CHECK_EQ(runtime->GetResolutionMethod(),
1428 image_header->GetImageMethod(ImageHeader::kResolutionMethod));
1429 CHECK_EQ(runtime->GetImtConflictMethod(),
1430 image_header->GetImageMethod(ImageHeader::kImtConflictMethod));
1431 CHECK_EQ(runtime->GetImtUnimplementedMethod(),
1432 image_header->GetImageMethod(ImageHeader::kImtUnimplementedMethod));
1433 CHECK_EQ(runtime->GetCalleeSaveMethod(Runtime::kSaveAll),
1434 image_header->GetImageMethod(ImageHeader::kCalleeSaveMethod));
1435 CHECK_EQ(runtime->GetCalleeSaveMethod(Runtime::kRefsOnly),
1436 image_header->GetImageMethod(ImageHeader::kRefsOnlySaveMethod));
1437 CHECK_EQ(runtime->GetCalleeSaveMethod(Runtime::kRefsAndArgs),
1438 image_header->GetImageMethod(ImageHeader::kRefsAndArgsSaveMethod));
1439 } else if (!runtime->HasResolutionMethod()) {
1440 runtime->SetInstructionSet(space->oat_file_non_owned_->GetOatHeader().GetInstructionSet());
1441 runtime->SetResolutionMethod(image_header->GetImageMethod(ImageHeader::kResolutionMethod));
1442 runtime->SetImtConflictMethod(image_header->GetImageMethod(ImageHeader::kImtConflictMethod));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001443 runtime->SetImtUnimplementedMethod(
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001444 image_header->GetImageMethod(ImageHeader::kImtUnimplementedMethod));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001445 runtime->SetCalleeSaveMethod(
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001446 image_header->GetImageMethod(ImageHeader::kCalleeSaveMethod), Runtime::kSaveAll);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001447 runtime->SetCalleeSaveMethod(
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001448 image_header->GetImageMethod(ImageHeader::kRefsOnlySaveMethod), Runtime::kRefsOnly);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001449 runtime->SetCalleeSaveMethod(
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001450 image_header->GetImageMethod(ImageHeader::kRefsAndArgsSaveMethod), Runtime::kRefsAndArgs);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001451 }
Vladimir Marko7624d252014-05-02 14:40:15 +01001452
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001453 VLOG(image) << "ImageSpace::Init exiting " << *space.get();
1454 if (VLOG_IS_ON(image)) {
1455 logger.Dump(LOG(INFO));
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001456 }
1457 return space.release();
1458}
1459
Nicolas Geoffray9583fbc2014-02-28 15:21:07 +00001460OatFile* ImageSpace::OpenOatFile(const char* image_path, std::string* error_msg) const {
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001461 const ImageHeader& image_header = GetImageHeader();
Nicolas Geoffray9583fbc2014-02-28 15:21:07 +00001462 std::string oat_filename = ImageHeader::GetOatLocationFromImageLocation(image_path);
1463
Igor Murashkin46774762014-10-22 11:37:02 -07001464 CHECK(image_header.GetOatDataBegin() != nullptr);
1465
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -07001466 OatFile* oat_file = OatFile::Open(oat_filename,
1467 oat_filename,
1468 image_header.GetOatDataBegin(),
Igor Murashkin46774762014-10-22 11:37:02 -07001469 image_header.GetOatFileBegin(),
Richard Uhlere5fed032015-03-18 08:21:11 -07001470 !Runtime::Current()->IsAotCompiler(),
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001471 /*low_4gb*/false,
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -07001472 nullptr,
1473 error_msg);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001474 if (oat_file == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001475 *error_msg = StringPrintf("Failed to open oat file '%s' referenced from image %s: %s",
1476 oat_filename.c_str(), GetName(), error_msg->c_str());
1477 return nullptr;
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001478 }
1479 uint32_t oat_checksum = oat_file->GetOatHeader().GetChecksum();
1480 uint32_t image_oat_checksum = image_header.GetOatChecksum();
1481 if (oat_checksum != image_oat_checksum) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001482 *error_msg = StringPrintf("Failed to match oat file checksum 0x%x to expected oat checksum 0x%x"
1483 " in image %s", oat_checksum, image_oat_checksum, GetName());
1484 return nullptr;
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001485 }
Alex Lighta59dd802014-07-02 16:28:08 -07001486 int32_t image_patch_delta = image_header.GetPatchDelta();
1487 int32_t oat_patch_delta = oat_file->GetOatHeader().GetImagePatchDelta();
Igor Murashkin46774762014-10-22 11:37:02 -07001488 if (oat_patch_delta != image_patch_delta && !image_header.CompilePic()) {
Alex Lighta59dd802014-07-02 16:28:08 -07001489 // We should have already relocated by this point. Bail out.
1490 *error_msg = StringPrintf("Failed to match oat file patch delta %d to expected patch delta %d "
1491 "in image %s", oat_patch_delta, image_patch_delta, GetName());
1492 return nullptr;
1493 }
1494
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001495 return oat_file;
1496}
1497
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001498bool ImageSpace::ValidateOatFile(std::string* error_msg) const {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001499 CHECK(oat_file_.get() != nullptr);
Mathieu Chartier31e89252013-08-28 11:29:12 -07001500 for (const OatFile::OatDexFile* oat_dex_file : oat_file_->GetOatDexFiles()) {
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001501 const std::string& dex_file_location = oat_dex_file->GetDexFileLocation();
1502 uint32_t dex_file_location_checksum;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001503 if (!DexFile::GetChecksum(dex_file_location.c_str(), &dex_file_location_checksum, error_msg)) {
1504 *error_msg = StringPrintf("Failed to get checksum of dex file '%s' referenced by image %s: "
1505 "%s", dex_file_location.c_str(), GetName(), error_msg->c_str());
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001506 return false;
1507 }
1508 if (dex_file_location_checksum != oat_dex_file->GetDexFileLocationChecksum()) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001509 *error_msg = StringPrintf("ValidateOatFile found checksum mismatch between oat file '%s' and "
1510 "dex file '%s' (0x%x != 0x%x)",
1511 oat_file_->GetLocation().c_str(), dex_file_location.c_str(),
1512 oat_dex_file->GetDexFileLocationChecksum(),
1513 dex_file_location_checksum);
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001514 return false;
1515 }
1516 }
1517 return true;
1518}
1519
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001520const OatFile* ImageSpace::GetOatFile() const {
Andreas Gampe88da3b02015-06-12 20:38:49 -07001521 return oat_file_non_owned_;
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001522}
1523
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -07001524std::unique_ptr<const OatFile> ImageSpace::ReleaseOatFile() {
1525 CHECK(oat_file_ != nullptr);
1526 return std::move(oat_file_);
Ian Rogers1d54e732013-05-02 21:10:01 -07001527}
1528
Ian Rogers1d54e732013-05-02 21:10:01 -07001529void ImageSpace::Dump(std::ostream& os) const {
1530 os << GetType()
Mathieu Chartier590fee92013-09-13 13:46:47 -07001531 << " begin=" << reinterpret_cast<void*>(Begin())
Ian Rogers1d54e732013-05-02 21:10:01 -07001532 << ",end=" << reinterpret_cast<void*>(End())
1533 << ",size=" << PrettySize(Size())
1534 << ",name=\"" << GetName() << "\"]";
1535}
1536
Andreas Gampe8994a042015-12-30 19:03:17 +00001537void ImageSpace::CreateMultiImageLocations(const std::string& input_image_file_name,
1538 const std::string& boot_classpath,
1539 std::vector<std::string>* image_file_names) {
1540 DCHECK(image_file_names != nullptr);
1541
1542 std::vector<std::string> images;
1543 Split(boot_classpath, ':', &images);
1544
1545 // Add the rest into the list. We have to adjust locations, possibly:
1546 //
1547 // For example, image_file_name is /a/b/c/d/e.art
1548 // images[0] is f/c/d/e.art
1549 // ----------------------------------------------
1550 // images[1] is g/h/i/j.art -> /a/b/h/i/j.art
Mathieu Chartier8b8f6d62016-03-08 16:50:20 -08001551 const std::string& first_image = images[0];
1552 // Length of common suffix.
1553 size_t common = 0;
1554 while (common < input_image_file_name.size() &&
1555 common < first_image.size() &&
1556 *(input_image_file_name.end() - common - 1) == *(first_image.end() - common - 1)) {
1557 ++common;
Andreas Gampe8994a042015-12-30 19:03:17 +00001558 }
Mathieu Chartier8b8f6d62016-03-08 16:50:20 -08001559 // We want to replace the prefix of the input image with the prefix of the boot class path.
1560 // This handles the case where the image file contains @ separators.
1561 // Example image_file_name is oats/system@framework@boot.art
1562 // images[0] is .../arm/boot.art
1563 // means that the image name prefix will be oats/system@framework@
1564 // so that the other images are openable.
1565 const size_t old_prefix_length = first_image.size() - common;
1566 const std::string new_prefix = input_image_file_name.substr(
1567 0,
1568 input_image_file_name.size() - common);
Andreas Gampe8994a042015-12-30 19:03:17 +00001569
1570 // Apply pattern to images[1] .. images[n].
1571 for (size_t i = 1; i < images.size(); ++i) {
Mathieu Chartier8b8f6d62016-03-08 16:50:20 -08001572 const std::string& image = images[i];
1573 CHECK_GT(image.length(), old_prefix_length);
1574 std::string suffix = image.substr(old_prefix_length);
1575 image_file_names->push_back(new_prefix + suffix);
Andreas Gampe8994a042015-12-30 19:03:17 +00001576 }
1577}
1578
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001579ImageSpace* ImageSpace::CreateFromAppImage(const char* image,
1580 const OatFile* oat_file,
1581 std::string* error_msg) {
1582 return gc::space::ImageSpace::Init(image,
1583 image,
1584 /*validate_oat_file*/false,
1585 oat_file,
1586 /*out*/error_msg);
1587}
1588
Mathieu Chartierd5f3f322016-03-21 14:05:56 -07001589void ImageSpace::DumpSections(std::ostream& os) const {
1590 const uint8_t* base = Begin();
1591 const ImageHeader& header = GetImageHeader();
1592 for (size_t i = 0; i < ImageHeader::kSectionCount; ++i) {
1593 auto section_type = static_cast<ImageHeader::ImageSections>(i);
1594 const ImageSection& section = header.GetImageSection(section_type);
1595 os << section_type << " " << reinterpret_cast<const void*>(base + section.Offset())
1596 << "-" << reinterpret_cast<const void*>(base + section.End()) << "\n";
1597 }
1598}
1599
Ian Rogers1d54e732013-05-02 21:10:01 -07001600} // namespace space
1601} // namespace gc
1602} // namespace art