blob: 6fcad295bbb31d521839fc55d2447b84af4672cd [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
Andreas Gampebec63582015-11-20 19:26:51 -0800387 const bool is_zygote = Runtime::Current()->IsZygote();
Andreas Gampeacc1be32016-04-05 10:26:42 -0700388 if (is_zygote && !secondary_image) {
Narayan Kamath5a2be3f2015-02-16 13:51:51 +0000389 MarkZygoteStart(image_isa, Runtime::Current()->GetZygoteMaxFailedBoots());
Narayan Kamath28bc9872014-11-07 17:46:28 +0000390 }
391
Alex Lighta59dd802014-07-02 16:28:08 -0700392 ImageSpace* space;
393 bool relocate = Runtime::Current()->ShouldRelocate();
Alex Light64ad14d2014-08-19 14:23:13 -0700394 bool can_compile = Runtime::Current()->IsImageDex2OatEnabled();
Narayan Kamathd1c606f2014-06-09 16:50:19 +0100395 if (found_image) {
Alex Lighta59dd802014-07-02 16:28:08 -0700396 const std::string* image_filename;
397 bool is_system = false;
398 bool relocated_version_used = false;
399 if (relocate) {
Alex Light64ad14d2014-08-19 14:23:13 -0700400 if (!dalvik_cache_exists) {
401 *error_msg = StringPrintf("Requiring relocation for image '%s' at '%s' but we do not have "
402 "any dalvik_cache to find/place it in.",
403 image_location, system_filename.c_str());
404 return nullptr;
405 }
Alex Lighta59dd802014-07-02 16:28:08 -0700406 if (has_system) {
407 if (has_cache && ChecksumsMatch(system_filename.c_str(), cache_filename.c_str())) {
408 // We already have a relocated version
409 image_filename = &cache_filename;
410 relocated_version_used = true;
411 } else {
412 // We cannot have a relocated version, Relocate the system one and use it.
Andreas Gampe3c13a792014-09-18 20:56:04 -0700413
414 std::string reason;
415 bool success;
416
417 // Check whether we are allowed to relocate.
418 if (!can_compile) {
419 reason = "Image dex2oat disabled by -Xnoimage-dex2oat.";
420 success = false;
421 } else if (!ImageCreationAllowed(is_global_cache, &reason)) {
422 // Whether we can write to the cache.
423 success = false;
Andreas Gampe8994a042015-12-30 19:03:17 +0000424 } else if (secondary_image) {
Andreas Gampeacc1be32016-04-05 10:26:42 -0700425 if (is_zygote) {
Jeff Haoab4a4d22016-03-14 18:50:49 -0700426 // Secondary image is out of date. Clear cache and exit to let it retry from scratch.
427 LOG(ERROR) << "Cannot patch secondary image '" << image_location
428 << "', clearing dalvik_cache and restarting zygote.";
429 PruneDalvikCache(image_isa);
430 _exit(1);
431 } else {
432 reason = "Should not have to patch secondary image.";
433 success = false;
434 }
Andreas Gampe3c13a792014-09-18 20:56:04 -0700435 } else {
436 // Try to relocate.
437 success = RelocateImage(image_location, cache_filename.c_str(), image_isa, &reason);
438 }
439
440 if (success) {
Alex Lighta59dd802014-07-02 16:28:08 -0700441 relocated_version_used = true;
442 image_filename = &cache_filename;
443 } else {
Andreas Gampe3c13a792014-09-18 20:56:04 -0700444 *error_msg = StringPrintf("Unable to relocate image '%s' from '%s' to '%s': %s",
Alex Light64ad14d2014-08-19 14:23:13 -0700445 image_location, system_filename.c_str(),
446 cache_filename.c_str(), reason.c_str());
Brian Carlstrome9105f72014-10-28 15:53:43 -0700447 // We failed to create files, remove any possibly garbage output.
448 // Since ImageCreationAllowed was true above, we are the zygote
449 // and therefore the only process expected to generate these for
450 // the device.
Narayan Kamath28bc9872014-11-07 17:46:28 +0000451 PruneDalvikCache(image_isa);
Alex Lighta59dd802014-07-02 16:28:08 -0700452 return nullptr;
453 }
454 }
455 } else {
456 CHECK(has_cache);
457 // We can just use cache's since it should be fine. This might or might not be relocated.
458 image_filename = &cache_filename;
459 }
460 } else {
461 if (has_system && has_cache) {
462 // Check they have the same cksum. If they do use the cache. Otherwise system.
463 if (ChecksumsMatch(system_filename.c_str(), cache_filename.c_str())) {
464 image_filename = &cache_filename;
465 relocated_version_used = true;
466 } else {
467 image_filename = &system_filename;
Alex Light1a762132014-07-31 09:32:13 -0700468 is_system = true;
Alex Lighta59dd802014-07-02 16:28:08 -0700469 }
470 } else if (has_system) {
471 image_filename = &system_filename;
Alex Light1a762132014-07-31 09:32:13 -0700472 is_system = true;
Alex Lighta59dd802014-07-02 16:28:08 -0700473 } else {
474 CHECK(has_cache);
475 image_filename = &cache_filename;
476 }
477 }
478 {
479 // Note that we must not use the file descriptor associated with
480 // ScopedFlock::GetFile to Init the image file. We want the file
481 // descriptor (and the associated exclusive lock) to be released when
482 // we leave Create.
483 ScopedFlock image_lock;
Andreas Gampeacc1be32016-04-05 10:26:42 -0700484 // Should this be a RDWR lock? This is only a defensive measure, as at
485 // this point the image should exist.
486 // However, only the zygote can write into the global dalvik-cache, so
487 // restrict to zygote processes, or any process that isn't using
488 // /data/dalvik-cache (which we assume to be allowed to write there).
489 const bool rw_lock = is_zygote || !is_global_cache;
490 image_lock.Init(image_filename->c_str(),
491 rw_lock ? (O_CREAT | O_RDWR) : O_RDONLY /* flags */,
492 true /* block */,
493 error_msg);
Alex Lightb6cabc12014-08-21 09:45:00 -0700494 VLOG(startup) << "Using image file " << image_filename->c_str() << " for image location "
495 << image_location;
Alex Lightb93637a2014-07-31 10:48:46 -0700496 // If we are in /system we can assume the image is good. We can also
497 // assume this if we are using a relocated image (i.e. image checksum
498 // matches) since this is only different by the offset. We need this to
499 // make sure that host tests continue to work.
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800500 // Since we are the boot image, pass null since we load the oat file from the boot image oat
501 // file name.
502 space = ImageSpace::Init(image_filename->c_str(),
503 image_location,
504 !(is_system || relocated_version_used),
505 /* oat_file */nullptr,
506 error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -0700507 }
Narayan Kamath52f84882014-05-02 10:10:39 +0100508 if (space != nullptr) {
Andreas Gamped26b6ad2016-08-09 20:19:18 -0700509 // Check whether there is enough space left over in the data partition. Even if we can load
510 // the image, we need to be conservative, as some parts of the platform are not very tolerant
511 // of space constraints.
512 // ImageSpace doesn't know about the data partition per se, it relies on the FindImageFilename
513 // helper (which relies on GetDalvikCache). So for now, if we load an image out of /system,
514 // ignore the check (as it would test for free space in /system instead).
515 if (!is_system && !CheckSpace(*image_filename, error_msg)) {
516 // No. Delete the generated image and try to run out of the dex files.
517 PruneDalvikCache(image_isa);
518 return nullptr;
519 }
Narayan Kamath52f84882014-05-02 10:10:39 +0100520 return space;
521 }
522
Alex Lighta59dd802014-07-02 16:28:08 -0700523 if (relocated_version_used) {
Brian Carlstrome9105f72014-10-28 15:53:43 -0700524 // Something is wrong with the relocated copy (even though checksums match). Cleanup.
525 // This can happen if the .oat is corrupt, since the above only checks the .art checksums.
526 // TODO: Check the oat file validity earlier.
527 *error_msg = StringPrintf("Attempted to use relocated version of %s at %s generated from %s "
528 "but image failed to load: %s",
529 image_location, cache_filename.c_str(), system_filename.c_str(),
530 error_msg->c_str());
Narayan Kamath28bc9872014-11-07 17:46:28 +0000531 PruneDalvikCache(image_isa);
Alex Lighta59dd802014-07-02 16:28:08 -0700532 return nullptr;
533 } else if (is_system) {
Brian Carlstrome9105f72014-10-28 15:53:43 -0700534 // If the /system file exists, it should be up-to-date, don't try to generate it.
Alex Light64ad14d2014-08-19 14:23:13 -0700535 *error_msg = StringPrintf("Failed to load /system image '%s': %s",
536 image_filename->c_str(), error_msg->c_str());
Narayan Kamath52f84882014-05-02 10:10:39 +0100537 return nullptr;
Mathieu Chartierc7cb1902014-03-05 14:41:03 -0800538 } else {
Brian Carlstrome9105f72014-10-28 15:53:43 -0700539 // Otherwise, log a warning and fall through to GenerateImage.
Alex Light64ad14d2014-08-19 14:23:13 -0700540 LOG(WARNING) << *error_msg;
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700541 }
542 }
Narayan Kamath52f84882014-05-02 10:10:39 +0100543
Alex Light64ad14d2014-08-19 14:23:13 -0700544 if (!can_compile) {
545 *error_msg = "Not attempting to compile image because -Xnoimage-dex2oat";
546 return nullptr;
547 } else if (!dalvik_cache_exists) {
548 *error_msg = StringPrintf("No place to put generated image.");
549 return nullptr;
Andreas Gampe3c13a792014-09-18 20:56:04 -0700550 } else if (!ImageCreationAllowed(is_global_cache, error_msg)) {
551 return nullptr;
Andreas Gampe8994a042015-12-30 19:03:17 +0000552 } else if (secondary_image) {
553 *error_msg = "Cannot compile a secondary image.";
554 return nullptr;
Alex Light25396132014-08-27 15:37:23 -0700555 } else if (!GenerateImage(cache_filename, image_isa, error_msg)) {
Alex Light64ad14d2014-08-19 14:23:13 -0700556 *error_msg = StringPrintf("Failed to generate image '%s': %s",
557 cache_filename.c_str(), error_msg->c_str());
Brian Carlstrome9105f72014-10-28 15:53:43 -0700558 // We failed to create files, remove any possibly garbage output.
559 // Since ImageCreationAllowed was true above, we are the zygote
560 // and therefore the only process expected to generate these for
561 // the device.
Narayan Kamath28bc9872014-11-07 17:46:28 +0000562 PruneDalvikCache(image_isa);
Alex Light64ad14d2014-08-19 14:23:13 -0700563 return nullptr;
564 } else {
Andreas Gampe70be1fb2014-10-31 16:45:19 -0700565 // Check whether there is enough space left over after we have generated the image.
566 if (!CheckSpace(cache_filename, error_msg)) {
567 // No. Delete the generated image and try to run out of the dex files.
Narayan Kamath28bc9872014-11-07 17:46:28 +0000568 PruneDalvikCache(image_isa);
Andreas Gampe70be1fb2014-10-31 16:45:19 -0700569 return nullptr;
570 }
571
Alex Lighta59dd802014-07-02 16:28:08 -0700572 // Note that we must not use the file descriptor associated with
573 // ScopedFlock::GetFile to Init the image file. We want the file
574 // descriptor (and the associated exclusive lock) to be released when
575 // we leave Create.
576 ScopedFlock image_lock;
Alex Light64ad14d2014-08-19 14:23:13 -0700577 image_lock.Init(cache_filename.c_str(), error_msg);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800578 space = ImageSpace::Init(cache_filename.c_str(), image_location, true, nullptr, error_msg);
Alex Light64ad14d2014-08-19 14:23:13 -0700579 if (space == nullptr) {
580 *error_msg = StringPrintf("Failed to load generated image '%s': %s",
581 cache_filename.c_str(), error_msg->c_str());
582 }
583 return space;
Alex Lighta59dd802014-07-02 16:28:08 -0700584 }
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700585}
586
Mathieu Chartier31e89252013-08-28 11:29:12 -0700587void ImageSpace::VerifyImageAllocations() {
Ian Rogers13735952014-10-08 12:43:28 -0700588 uint8_t* current = Begin() + RoundUp(sizeof(ImageHeader), kObjectAlignment);
Mathieu Chartier31e89252013-08-28 11:29:12 -0700589 while (current < End()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700590 CHECK_ALIGNED(current, kObjectAlignment);
591 auto* obj = reinterpret_cast<mirror::Object*>(current);
Mathieu Chartier31e89252013-08-28 11:29:12 -0700592 CHECK(obj->GetClass() != nullptr) << "Image object at address " << obj << " has null class";
Mathieu Chartierc7853442015-03-27 14:35:38 -0700593 CHECK(live_bitmap_->Test(obj)) << PrettyTypeOf(obj);
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -0700594 if (kUseBakerOrBrooksReadBarrier) {
595 obj->AssertReadBarrierPointer();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800596 }
Mathieu Chartier31e89252013-08-28 11:29:12 -0700597 current += RoundUp(obj->SizeOf(), kObjectAlignment);
598 }
599}
600
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800601// Helper class for relocating from one range of memory to another.
602class RelocationRange {
603 public:
604 RelocationRange() = default;
605 RelocationRange(const RelocationRange&) = default;
606 RelocationRange(uintptr_t source, uintptr_t dest, uintptr_t length)
607 : source_(source),
608 dest_(dest),
609 length_(length) {}
610
Mathieu Chartier91edc622016-02-16 17:16:01 -0800611 bool InSource(uintptr_t address) const {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800612 return address - source_ < length_;
613 }
614
Mathieu Chartier91edc622016-02-16 17:16:01 -0800615 bool InDest(uintptr_t address) const {
616 return address - dest_ < length_;
617 }
618
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800619 // Translate a source address to the destination space.
620 uintptr_t ToDest(uintptr_t address) const {
Mathieu Chartier91edc622016-02-16 17:16:01 -0800621 DCHECK(InSource(address));
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800622 return address + Delta();
623 }
624
625 // Returns the delta between the dest from the source.
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800626 uintptr_t Delta() const {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800627 return dest_ - source_;
628 }
629
630 uintptr_t Source() const {
631 return source_;
632 }
633
634 uintptr_t Dest() const {
635 return dest_;
636 }
637
638 uintptr_t Length() const {
639 return length_;
640 }
641
642 private:
643 const uintptr_t source_;
644 const uintptr_t dest_;
645 const uintptr_t length_;
646};
647
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800648std::ostream& operator<<(std::ostream& os, const RelocationRange& reloc) {
649 return os << "(" << reinterpret_cast<const void*>(reloc.Source()) << "-"
650 << reinterpret_cast<const void*>(reloc.Source() + reloc.Length()) << ")->("
651 << reinterpret_cast<const void*>(reloc.Dest()) << "-"
652 << reinterpret_cast<const void*>(reloc.Dest() + reloc.Length()) << ")";
653}
654
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800655class FixupVisitor : public ValueObject {
656 public:
657 FixupVisitor(const RelocationRange& boot_image,
658 const RelocationRange& boot_oat,
659 const RelocationRange& app_image,
660 const RelocationRange& app_oat)
661 : boot_image_(boot_image),
662 boot_oat_(boot_oat),
663 app_image_(app_image),
664 app_oat_(app_oat) {}
665
666 // Return the relocated address of a heap object.
667 template <typename T>
668 ALWAYS_INLINE T* ForwardObject(T* src) const {
669 const uintptr_t uint_src = reinterpret_cast<uintptr_t>(src);
Mathieu Chartier91edc622016-02-16 17:16:01 -0800670 if (boot_image_.InSource(uint_src)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800671 return reinterpret_cast<T*>(boot_image_.ToDest(uint_src));
672 }
Mathieu Chartier91edc622016-02-16 17:16:01 -0800673 if (app_image_.InSource(uint_src)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800674 return reinterpret_cast<T*>(app_image_.ToDest(uint_src));
675 }
Mathieu Chartier91edc622016-02-16 17:16:01 -0800676 // Since we are fixing up the app image, there should only be pointers to the app image and
677 // boot image.
678 DCHECK(src == nullptr) << reinterpret_cast<const void*>(src);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800679 return src;
680 }
681
682 // Return the relocated address of a code pointer (contained by an oat file).
683 ALWAYS_INLINE const void* ForwardCode(const void* src) const {
684 const uintptr_t uint_src = reinterpret_cast<uintptr_t>(src);
Mathieu Chartier91edc622016-02-16 17:16:01 -0800685 if (boot_oat_.InSource(uint_src)) {
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800686 return reinterpret_cast<const void*>(boot_oat_.ToDest(uint_src));
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800687 }
Mathieu Chartier91edc622016-02-16 17:16:01 -0800688 if (app_oat_.InSource(uint_src)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800689 return reinterpret_cast<const void*>(app_oat_.ToDest(uint_src));
690 }
Mathieu Chartier91edc622016-02-16 17:16:01 -0800691 DCHECK(src == nullptr) << src;
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800692 return src;
693 }
694
Mathieu Chartier92ec5942016-04-11 12:03:48 -0700695 // Must be called on pointers that already have been relocated to the destination relocation.
696 ALWAYS_INLINE bool IsInAppImage(mirror::Object* object) const {
697 return app_image_.InDest(reinterpret_cast<uintptr_t>(object));
698 }
699
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800700 protected:
701 // Source section.
702 const RelocationRange boot_image_;
703 const RelocationRange boot_oat_;
704 const RelocationRange app_image_;
705 const RelocationRange app_oat_;
706};
707
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800708// Adapt for mirror::Class::FixupNativePointers.
709class FixupObjectAdapter : public FixupVisitor {
710 public:
711 template<typename... Args>
712 explicit FixupObjectAdapter(Args... args) : FixupVisitor(args...) {}
713
714 template <typename T>
715 T* operator()(T* obj) const {
716 return ForwardObject(obj);
717 }
718};
719
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800720class FixupRootVisitor : public FixupVisitor {
721 public:
722 template<typename... Args>
723 explicit FixupRootVisitor(Args... args) : FixupVisitor(args...) {}
724
725 ALWAYS_INLINE void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
726 SHARED_REQUIRES(Locks::mutator_lock_) {
727 if (!root->IsNull()) {
728 VisitRoot(root);
729 }
730 }
731
732 ALWAYS_INLINE void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
733 SHARED_REQUIRES(Locks::mutator_lock_) {
734 mirror::Object* ref = root->AsMirrorPtr();
735 mirror::Object* new_ref = ForwardObject(ref);
736 if (ref != new_ref) {
737 root->Assign(new_ref);
738 }
739 }
740};
741
742class FixupObjectVisitor : public FixupVisitor {
743 public:
744 template<typename... Args>
Mathieu Chartier92ec5942016-04-11 12:03:48 -0700745 explicit FixupObjectVisitor(gc::accounting::ContinuousSpaceBitmap* visited,
Andreas Gampe542451c2016-07-26 09:02:02 -0700746 const PointerSize pointer_size,
Mathieu Chartier91edc622016-02-16 17:16:01 -0800747 Args... args)
748 : FixupVisitor(args...),
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800749 pointer_size_(pointer_size),
Mathieu Chartier92ec5942016-04-11 12:03:48 -0700750 visited_(visited) {}
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800751
752 // Fix up separately since we also need to fix up method entrypoints.
753 ALWAYS_INLINE void VisitRootIfNonNull(
754 mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const {}
755
756 ALWAYS_INLINE void VisitRoot(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED)
757 const {}
758
759 ALWAYS_INLINE void operator()(mirror::Object* obj,
760 MemberOffset offset,
761 bool is_static ATTRIBUTE_UNUSED) const
762 NO_THREAD_SAFETY_ANALYSIS {
763 // There could be overlap between ranges, we must avoid visiting the same reference twice.
764 // Avoid the class field since we already fixed it up in FixupClassVisitor.
765 if (offset.Uint32Value() != mirror::Object::ClassOffset().Uint32Value()) {
766 // Space is not yet added to the heap, don't do a read barrier.
767 mirror::Object* ref = obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(
768 offset);
769 // Use SetFieldObjectWithoutWriteBarrier to avoid card marking since we are writing to the
770 // image.
771 obj->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(offset, ForwardObject(ref));
772 }
773 }
774
Mathieu Chartier91edc622016-02-16 17:16:01 -0800775 // Visit a pointer array and forward corresponding native data. Ignores pointer arrays in the
776 // boot image. Uses the bitmap to ensure the same array is not visited multiple times.
777 template <typename Visitor>
Mathieu Chartier92ec5942016-04-11 12:03:48 -0700778 void UpdatePointerArrayContents(mirror::PointerArray* array, const Visitor& visitor) const
Mathieu Chartier91edc622016-02-16 17:16:01 -0800779 NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier92ec5942016-04-11 12:03:48 -0700780 DCHECK(array != nullptr);
781 DCHECK(visitor.IsInAppImage(array));
782 // The bit for the array contents is different than the bit for the array. Since we may have
783 // already visited the array as a long / int array from walking the bitmap without knowing it
784 // was a pointer array.
785 static_assert(kObjectAlignment == 8u, "array bit may be in another object");
786 mirror::Object* const contents_bit = reinterpret_cast<mirror::Object*>(
787 reinterpret_cast<uintptr_t>(array) + kObjectAlignment);
788 // If the bit is not set then the contents have not yet been updated.
789 if (!visited_->Test(contents_bit)) {
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800790 array->Fixup<kVerifyNone, kWithoutReadBarrier>(array, pointer_size_, visitor);
Mathieu Chartier92ec5942016-04-11 12:03:48 -0700791 visited_->Set(contents_bit);
Mathieu Chartier91edc622016-02-16 17:16:01 -0800792 }
793 }
794
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800795 // java.lang.ref.Reference visitor.
796 void operator()(mirror::Class* klass ATTRIBUTE_UNUSED, mirror::Reference* ref) const
797 SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
798 mirror::Object* obj = ref->GetReferent<kWithoutReadBarrier>();
799 ref->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
800 mirror::Reference::ReferentOffset(),
801 ForwardObject(obj));
802 }
803
Goran Jakovljevic0dfb30d2016-04-12 13:11:16 +0200804 void operator()(mirror::Object* obj) const NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier92ec5942016-04-11 12:03:48 -0700805 if (visited_->Test(obj)) {
806 // Already visited.
807 return;
808 }
809 visited_->Set(obj);
810
811 // Handle class specially first since we need it to be updated to properly visit the rest of
812 // the instance fields.
813 {
814 mirror::Class* klass = obj->GetClass<kVerifyNone, kWithoutReadBarrier>();
815 DCHECK(klass != nullptr) << "Null class in image";
816 // No AsClass since our fields aren't quite fixed up yet.
817 mirror::Class* new_klass = down_cast<mirror::Class*>(ForwardObject(klass));
818 if (klass != new_klass) {
819 obj->SetClass<kVerifyNone>(new_klass);
820 }
821 if (new_klass != klass && IsInAppImage(new_klass)) {
822 // Make sure the klass contents are fixed up since we depend on it to walk the fields.
823 operator()(new_klass);
824 }
825 }
826
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800827 obj->VisitReferences</*visit native roots*/false, kVerifyNone, kWithoutReadBarrier>(
828 *this,
829 *this);
Mathieu Chartier92ec5942016-04-11 12:03:48 -0700830 // Note that this code relies on no circular dependencies.
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800831 // We want to use our own class loader and not the one in the image.
832 if (obj->IsClass<kVerifyNone, kWithoutReadBarrier>()) {
Mathieu Chartier92ec5942016-04-11 12:03:48 -0700833 mirror::Class* as_klass = obj->AsClass<kVerifyNone, kWithoutReadBarrier>();
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800834 FixupObjectAdapter visitor(boot_image_, boot_oat_, app_image_, app_oat_);
Mathieu Chartier92ec5942016-04-11 12:03:48 -0700835 as_klass->FixupNativePointers<kVerifyNone, kWithoutReadBarrier>(as_klass,
836 pointer_size_,
837 visitor);
Mathieu Chartier91edc622016-02-16 17:16:01 -0800838 // Deal with the pointer arrays. Use the helper function since multiple classes can reference
839 // the same arrays.
Mathieu Chartier92ec5942016-04-11 12:03:48 -0700840 mirror::PointerArray* const vtable = as_klass->GetVTable<kVerifyNone, kWithoutReadBarrier>();
841 if (vtable != nullptr && IsInAppImage(vtable)) {
842 operator()(vtable);
843 UpdatePointerArrayContents(vtable, visitor);
844 }
845 mirror::IfTable* iftable = as_klass->GetIfTable<kVerifyNone, kWithoutReadBarrier>();
846 // Ensure iftable arrays are fixed up since we need GetMethodArray to return the valid
847 // contents.
848 if (iftable != nullptr && IsInAppImage(iftable)) {
849 operator()(iftable);
Mathieu Chartierdfe02f62016-02-01 20:15:11 -0800850 for (int32_t i = 0, count = iftable->Count(); i < count; ++i) {
851 if (iftable->GetMethodArrayCount<kVerifyNone, kWithoutReadBarrier>(i) > 0) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800852 mirror::PointerArray* methods =
853 iftable->GetMethodArray<kVerifyNone, kWithoutReadBarrier>(i);
Mathieu Chartier92ec5942016-04-11 12:03:48 -0700854 if (visitor.IsInAppImage(methods)) {
855 operator()(methods);
856 DCHECK(methods != nullptr);
857 UpdatePointerArrayContents(methods, visitor);
858 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800859 }
860 }
861 }
862 }
863 }
Mathieu Chartier91edc622016-02-16 17:16:01 -0800864
865 private:
Andreas Gampe542451c2016-07-26 09:02:02 -0700866 const PointerSize pointer_size_;
Mathieu Chartier92ec5942016-04-11 12:03:48 -0700867 gc::accounting::ContinuousSpaceBitmap* const visited_;
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800868};
869
870class ForwardObjectAdapter {
871 public:
Chih-Hung Hsieh471118e2016-04-29 14:27:41 -0700872 ALWAYS_INLINE explicit ForwardObjectAdapter(const FixupVisitor* visitor) : visitor_(visitor) {}
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800873
874 template <typename T>
875 ALWAYS_INLINE T* operator()(T* src) const {
876 return visitor_->ForwardObject(src);
877 }
878
879 private:
880 const FixupVisitor* const visitor_;
881};
882
883class ForwardCodeAdapter {
884 public:
Chih-Hung Hsieh471118e2016-04-29 14:27:41 -0700885 ALWAYS_INLINE explicit ForwardCodeAdapter(const FixupVisitor* visitor)
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800886 : visitor_(visitor) {}
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800887
888 template <typename T>
889 ALWAYS_INLINE T* operator()(T* src) const {
890 return visitor_->ForwardCode(src);
891 }
892
893 private:
894 const FixupVisitor* const visitor_;
895};
896
897class FixupArtMethodVisitor : public FixupVisitor, public ArtMethodVisitor {
898 public:
899 template<typename... Args>
Andreas Gampe542451c2016-07-26 09:02:02 -0700900 explicit FixupArtMethodVisitor(bool fixup_heap_objects, PointerSize pointer_size, Args... args)
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800901 : FixupVisitor(args...),
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800902 fixup_heap_objects_(fixup_heap_objects),
903 pointer_size_(pointer_size) {}
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800904
905 virtual void Visit(ArtMethod* method) NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartiere42888f2016-04-14 10:49:19 -0700906 // TODO: Separate visitor for runtime vs normal methods.
907 if (UNLIKELY(method->IsRuntimeMethod())) {
908 ImtConflictTable* table = method->GetImtConflictTable(pointer_size_);
909 if (table != nullptr) {
910 ImtConflictTable* new_table = ForwardObject(table);
911 if (table != new_table) {
912 method->SetImtConflictTable(new_table, pointer_size_);
913 }
914 }
915 const void* old_code = method->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size_);
916 const void* new_code = ForwardCode(old_code);
917 if (old_code != new_code) {
918 method->SetEntryPointFromQuickCompiledCodePtrSize(new_code, pointer_size_);
919 }
920 } else {
921 if (fixup_heap_objects_) {
922 method->UpdateObjectsForImageRelocation(ForwardObjectAdapter(this), pointer_size_);
923 }
924 method->UpdateEntrypoints<kWithoutReadBarrier>(ForwardCodeAdapter(this), pointer_size_);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800925 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800926 }
927
928 private:
929 const bool fixup_heap_objects_;
Andreas Gampe542451c2016-07-26 09:02:02 -0700930 const PointerSize pointer_size_;
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800931};
932
933class FixupArtFieldVisitor : public FixupVisitor, public ArtFieldVisitor {
934 public:
935 template<typename... Args>
936 explicit FixupArtFieldVisitor(Args... args) : FixupVisitor(args...) {}
937
938 virtual void Visit(ArtField* field) NO_THREAD_SAFETY_ANALYSIS {
939 field->UpdateObjects(ForwardObjectAdapter(this));
940 }
941};
942
943// Relocate an image space mapped at target_base which possibly used to be at a different base
944// address. Only needs a single image space, not one for both source and destination.
945// In place means modifying a single ImageSpace in place rather than relocating from one ImageSpace
946// to another.
947static bool RelocateInPlace(ImageHeader& image_header,
948 uint8_t* target_base,
949 accounting::ContinuousSpaceBitmap* bitmap,
950 const OatFile* app_oat_file,
951 std::string* error_msg) {
952 DCHECK(error_msg != nullptr);
953 if (!image_header.IsPic()) {
954 if (image_header.GetImageBegin() == target_base) {
955 return true;
956 }
957 *error_msg = StringPrintf("Cannot relocate non-pic image for oat file %s",
958 (app_oat_file != nullptr) ? app_oat_file->GetLocation().c_str() : "");
959 return false;
960 }
961 // Set up sections.
962 uint32_t boot_image_begin = 0;
963 uint32_t boot_image_end = 0;
964 uint32_t boot_oat_begin = 0;
965 uint32_t boot_oat_end = 0;
Andreas Gampe542451c2016-07-26 09:02:02 -0700966 const PointerSize pointer_size = image_header.GetPointerSize();
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800967 gc::Heap* const heap = Runtime::Current()->GetHeap();
968 heap->GetBootImagesSize(&boot_image_begin, &boot_image_end, &boot_oat_begin, &boot_oat_end);
Mathieu Chartiere7199262016-04-11 13:56:45 -0700969 if (boot_image_begin == boot_image_end) {
970 *error_msg = "Can not relocate app image without boot image space";
971 return false;
972 }
973 if (boot_oat_begin == boot_oat_end) {
974 *error_msg = "Can not relocate app image without boot oat file";
975 return false;
976 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800977 const uint32_t boot_image_size = boot_image_end - boot_image_begin;
978 const uint32_t boot_oat_size = boot_oat_end - boot_oat_begin;
979 const uint32_t image_header_boot_image_size = image_header.GetBootImageSize();
980 const uint32_t image_header_boot_oat_size = image_header.GetBootOatSize();
981 if (boot_image_size != image_header_boot_image_size) {
982 *error_msg = StringPrintf("Boot image size %" PRIu64 " does not match expected size %"
983 PRIu64,
984 static_cast<uint64_t>(boot_image_size),
985 static_cast<uint64_t>(image_header_boot_image_size));
986 return false;
987 }
988 if (boot_oat_size != image_header_boot_oat_size) {
989 *error_msg = StringPrintf("Boot oat size %" PRIu64 " does not match expected size %"
990 PRIu64,
991 static_cast<uint64_t>(boot_oat_size),
992 static_cast<uint64_t>(image_header_boot_oat_size));
993 return false;
994 }
995 TimingLogger logger(__FUNCTION__, true, false);
996 RelocationRange boot_image(image_header.GetBootImageBegin(),
997 boot_image_begin,
998 boot_image_size);
999 RelocationRange boot_oat(image_header.GetBootOatBegin(),
1000 boot_oat_begin,
1001 boot_oat_size);
1002 RelocationRange app_image(reinterpret_cast<uintptr_t>(image_header.GetImageBegin()),
1003 reinterpret_cast<uintptr_t>(target_base),
1004 image_header.GetImageSize());
1005 // Use the oat data section since this is where the OatFile::Begin is.
1006 RelocationRange app_oat(reinterpret_cast<uintptr_t>(image_header.GetOatDataBegin()),
1007 // Not necessarily in low 4GB.
1008 reinterpret_cast<uintptr_t>(app_oat_file->Begin()),
1009 image_header.GetOatDataEnd() - image_header.GetOatDataBegin());
1010 VLOG(image) << "App image " << app_image;
1011 VLOG(image) << "App oat " << app_oat;
1012 VLOG(image) << "Boot image " << boot_image;
1013 VLOG(image) << "Boot oat " << boot_oat;
1014 // True if we need to fixup any heap pointers, otherwise only code pointers.
1015 const bool fixup_image = boot_image.Delta() != 0 || app_image.Delta() != 0;
1016 const bool fixup_code = boot_oat.Delta() != 0 || app_oat.Delta() != 0;
1017 if (!fixup_image && !fixup_code) {
1018 // Nothing to fix up.
1019 return true;
1020 }
Mathieu Chartierdfe02f62016-02-01 20:15:11 -08001021 ScopedDebugDisallowReadBarriers sddrb(Thread::Current());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001022 // Need to update the image to be at the target base.
1023 const ImageSection& objects_section = image_header.GetImageSection(ImageHeader::kSectionObjects);
1024 uintptr_t objects_begin = reinterpret_cast<uintptr_t>(target_base + objects_section.Offset());
1025 uintptr_t objects_end = reinterpret_cast<uintptr_t>(target_base + objects_section.End());
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001026 FixupObjectAdapter fixup_adapter(boot_image, boot_oat, app_image, app_oat);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001027 if (fixup_image) {
Mathieu Chartier91edc622016-02-16 17:16:01 -08001028 // Two pass approach, fix up all classes first, then fix up non class-objects.
1029 // The visited bitmap is used to ensure that pointer arrays are not forwarded twice.
1030 std::unique_ptr<gc::accounting::ContinuousSpaceBitmap> visited_bitmap(
Mathieu Chartier92ec5942016-04-11 12:03:48 -07001031 gc::accounting::ContinuousSpaceBitmap::Create("Relocate bitmap",
Mathieu Chartier91edc622016-02-16 17:16:01 -08001032 target_base,
1033 image_header.GetImageSize()));
1034 FixupObjectVisitor fixup_object_visitor(visited_bitmap.get(),
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001035 pointer_size,
Mathieu Chartier91edc622016-02-16 17:16:01 -08001036 boot_image,
1037 boot_oat,
1038 app_image,
1039 app_oat);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001040 TimingLogger::ScopedTiming timing("Fixup classes", &logger);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001041 // Fixup objects may read fields in the boot image, use the mutator lock here for sanity. Though
1042 // its probably not required.
1043 ScopedObjectAccess soa(Thread::Current());
1044 timing.NewTiming("Fixup objects");
1045 bitmap->VisitMarkedRange(objects_begin, objects_end, fixup_object_visitor);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001046 // Fixup image roots.
Mathieu Chartier91edc622016-02-16 17:16:01 -08001047 CHECK(app_image.InSource(reinterpret_cast<uintptr_t>(
Mathieu Chartier4a26f172016-01-26 14:26:18 -08001048 image_header.GetImageRoots<kWithoutReadBarrier>())));
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001049 image_header.RelocateImageObjects(app_image.Delta());
1050 CHECK_EQ(image_header.GetImageBegin(), target_base);
1051 // Fix up dex cache DexFile pointers.
Mathieu Chartier4a26f172016-01-26 14:26:18 -08001052 auto* dex_caches = image_header.GetImageRoot<kWithoutReadBarrier>(ImageHeader::kDexCaches)->
Mathieu Chartierdfe02f62016-02-01 20:15:11 -08001053 AsObjectArray<mirror::DexCache, kVerifyNone, kWithoutReadBarrier>();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001054 for (int32_t i = 0, count = dex_caches->GetLength(); i < count; ++i) {
Mathieu Chartier60bc39c2016-01-27 18:37:48 -08001055 mirror::DexCache* dex_cache = dex_caches->Get<kVerifyNone, kWithoutReadBarrier>(i);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001056 // Fix up dex cache pointers.
1057 GcRoot<mirror::String>* strings = dex_cache->GetStrings();
1058 if (strings != nullptr) {
1059 GcRoot<mirror::String>* new_strings = fixup_adapter.ForwardObject(strings);
1060 if (strings != new_strings) {
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001061 dex_cache->SetStrings(new_strings);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001062 }
Mathieu Chartier60bc39c2016-01-27 18:37:48 -08001063 dex_cache->FixupStrings<kWithoutReadBarrier>(new_strings, fixup_adapter);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001064 }
1065 GcRoot<mirror::Class>* types = dex_cache->GetResolvedTypes();
1066 if (types != nullptr) {
1067 GcRoot<mirror::Class>* new_types = fixup_adapter.ForwardObject(types);
1068 if (types != new_types) {
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001069 dex_cache->SetResolvedTypes(new_types);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001070 }
Mathieu Chartier60bc39c2016-01-27 18:37:48 -08001071 dex_cache->FixupResolvedTypes<kWithoutReadBarrier>(new_types, fixup_adapter);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001072 }
1073 ArtMethod** methods = dex_cache->GetResolvedMethods();
1074 if (methods != nullptr) {
1075 ArtMethod** new_methods = fixup_adapter.ForwardObject(methods);
1076 if (methods != new_methods) {
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001077 dex_cache->SetResolvedMethods(new_methods);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001078 }
1079 for (size_t j = 0, num = dex_cache->NumResolvedMethods(); j != num; ++j) {
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001080 ArtMethod* orig = mirror::DexCache::GetElementPtrSize(new_methods, j, pointer_size);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001081 ArtMethod* copy = fixup_adapter.ForwardObject(orig);
1082 if (orig != copy) {
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001083 mirror::DexCache::SetElementPtrSize(new_methods, j, copy, pointer_size);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001084 }
1085 }
1086 }
1087 ArtField** fields = dex_cache->GetResolvedFields();
1088 if (fields != nullptr) {
1089 ArtField** new_fields = fixup_adapter.ForwardObject(fields);
1090 if (fields != new_fields) {
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -08001091 dex_cache->SetResolvedFields(new_fields);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001092 }
1093 for (size_t j = 0, num = dex_cache->NumResolvedFields(); j != num; ++j) {
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001094 ArtField* orig = mirror::DexCache::GetElementPtrSize(new_fields, j, pointer_size);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001095 ArtField* copy = fixup_adapter.ForwardObject(orig);
1096 if (orig != copy) {
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001097 mirror::DexCache::SetElementPtrSize(new_fields, j, copy, pointer_size);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001098 }
1099 }
1100 }
1101 }
1102 }
1103 {
1104 // Only touches objects in the app image, no need for mutator lock.
1105 TimingLogger::ScopedTiming timing("Fixup methods", &logger);
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001106 FixupArtMethodVisitor method_visitor(fixup_image,
1107 pointer_size,
1108 boot_image,
1109 boot_oat,
1110 app_image,
1111 app_oat);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001112 image_header.VisitPackedArtMethods(&method_visitor, target_base, pointer_size);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001113 }
1114 if (fixup_image) {
1115 {
1116 // Only touches objects in the app image, no need for mutator lock.
1117 TimingLogger::ScopedTiming timing("Fixup fields", &logger);
1118 FixupArtFieldVisitor field_visitor(boot_image, boot_oat, app_image, app_oat);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001119 image_header.VisitPackedArtFields(&field_visitor, target_base);
1120 }
1121 {
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001122 TimingLogger::ScopedTiming timing("Fixup imt", &logger);
1123 image_header.VisitPackedImTables(fixup_adapter, target_base, pointer_size);
1124 }
1125 {
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001126 TimingLogger::ScopedTiming timing("Fixup conflict tables", &logger);
1127 image_header.VisitPackedImtConflictTables(fixup_adapter, target_base, pointer_size);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001128 }
1129 // In the app image case, the image methods are actually in the boot image.
1130 image_header.RelocateImageMethods(boot_image.Delta());
1131 const auto& class_table_section = image_header.GetImageSection(ImageHeader::kSectionClassTable);
1132 if (class_table_section.Size() > 0u) {
1133 // Note that we require that ReadFromMemory does not make an internal copy of the elements.
1134 // This also relies on visit roots not doing any verification which could fail after we update
1135 // the roots to be the image addresses.
1136 ScopedObjectAccess soa(Thread::Current());
1137 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
1138 ClassTable temp_table;
1139 temp_table.ReadFromMemory(target_base + class_table_section.Offset());
1140 FixupRootVisitor root_visitor(boot_image, boot_oat, app_image, app_oat);
1141 temp_table.VisitRoots(root_visitor);
1142 }
1143 }
1144 if (VLOG_IS_ON(image)) {
1145 logger.Dump(LOG(INFO));
1146 }
1147 return true;
1148}
1149
Andreas Gampe7fa55782016-06-15 17:45:01 -07001150static MemMap* LoadImageFile(const char* image_filename,
1151 const char* image_location,
1152 const ImageHeader& image_header,
1153 uint8_t* address,
1154 int fd,
1155 TimingLogger& logger,
1156 std::string* error_msg) {
1157 TimingLogger::ScopedTiming timing("MapImageFile", &logger);
1158 const ImageHeader::StorageMode storage_mode = image_header.GetStorageMode();
1159 if (storage_mode == ImageHeader::kStorageModeUncompressed) {
1160 return MemMap::MapFileAtAddress(address,
1161 image_header.GetImageSize(),
1162 PROT_READ | PROT_WRITE,
1163 MAP_PRIVATE,
1164 fd,
1165 0,
1166 /*low_4gb*/true,
1167 /*reuse*/false,
1168 image_filename,
1169 error_msg);
1170 }
1171
1172 if (storage_mode != ImageHeader::kStorageModeLZ4 &&
1173 storage_mode != ImageHeader::kStorageModeLZ4HC) {
1174 *error_msg = StringPrintf("Invalid storage mode in image header %d",
1175 static_cast<int>(storage_mode));
1176 return nullptr;
1177 }
1178
1179 // Reserve output and decompress into it.
1180 std::unique_ptr<MemMap> map(MemMap::MapAnonymous(image_location,
1181 address,
1182 image_header.GetImageSize(),
1183 PROT_READ | PROT_WRITE,
1184 /*low_4gb*/true,
1185 /*reuse*/false,
1186 error_msg));
1187 if (map != nullptr) {
1188 const size_t stored_size = image_header.GetDataSize();
1189 const size_t decompress_offset = sizeof(ImageHeader); // Skip the header.
1190 std::unique_ptr<MemMap> temp_map(MemMap::MapFile(sizeof(ImageHeader) + stored_size,
1191 PROT_READ,
1192 MAP_PRIVATE,
1193 fd,
1194 /*offset*/0,
1195 /*low_4gb*/false,
1196 image_filename,
1197 error_msg));
1198 if (temp_map == nullptr) {
1199 DCHECK(!error_msg->empty());
1200 return nullptr;
1201 }
1202 memcpy(map->Begin(), &image_header, sizeof(ImageHeader));
1203 const uint64_t start = NanoTime();
1204 // LZ4HC and LZ4 have same internal format, both use LZ4_decompress.
1205 TimingLogger::ScopedTiming timing2("LZ4 decompress image", &logger);
1206 const size_t decompressed_size = LZ4_decompress_safe(
1207 reinterpret_cast<char*>(temp_map->Begin()) + sizeof(ImageHeader),
1208 reinterpret_cast<char*>(map->Begin()) + decompress_offset,
1209 stored_size,
1210 map->Size() - decompress_offset);
1211 VLOG(image) << "Decompressing image took " << PrettyDuration(NanoTime() - start);
1212 if (decompressed_size + sizeof(ImageHeader) != image_header.GetImageSize()) {
1213 *error_msg = StringPrintf(
1214 "Decompressed size does not match expected image size %zu vs %zu",
1215 decompressed_size + sizeof(ImageHeader),
1216 image_header.GetImageSize());
1217 return nullptr;
1218 }
1219 }
1220
1221 return map.release();
1222}
1223
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001224ImageSpace* ImageSpace::Init(const char* image_filename,
1225 const char* image_location,
1226 bool validate_oat_file,
1227 const OatFile* oat_file,
1228 std::string* error_msg) {
Narayan Kamath52f84882014-05-02 10:10:39 +01001229 CHECK(image_filename != nullptr);
1230 CHECK(image_location != nullptr);
Ian Rogers1d54e732013-05-02 21:10:01 -07001231
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001232 TimingLogger logger(__PRETTY_FUNCTION__, true, VLOG_IS_ON(image));
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001233 VLOG(image) << "ImageSpace::Init entering image_filename=" << image_filename;
Nicolas Geoffray1bc977c2016-01-23 14:15:49 +00001234
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001235 std::unique_ptr<File> file;
1236 {
1237 TimingLogger::ScopedTiming timing("OpenImageFile", &logger);
1238 file.reset(OS::OpenFileForReading(image_filename));
1239 if (file == nullptr) {
1240 *error_msg = StringPrintf("Failed to open '%s'", image_filename);
1241 return nullptr;
1242 }
Nicolas Geoffray1bc977c2016-01-23 14:15:49 +00001243 }
Andreas Gampe9e276662016-06-15 17:44:21 -07001244 ImageHeader temp_image_header;
1245 ImageHeader* image_header = &temp_image_header;
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001246 {
1247 TimingLogger::ScopedTiming timing("ReadImageHeader", &logger);
1248 bool success = file->ReadFully(image_header, sizeof(*image_header));
1249 if (!success || !image_header->IsValid()) {
1250 *error_msg = StringPrintf("Invalid image header in '%s'", image_filename);
1251 return nullptr;
1252 }
Ian Rogers1d54e732013-05-02 21:10:01 -07001253 }
Mathieu Chartierceb07b32015-12-10 09:33:21 -08001254 // Check that the file is larger or equal to the header size + data size.
1255 const uint64_t image_file_size = static_cast<uint64_t>(file->GetLength());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001256 if (image_file_size < sizeof(ImageHeader) + image_header->GetDataSize()) {
Mathieu Chartierceb07b32015-12-10 09:33:21 -08001257 *error_msg = StringPrintf("Image file truncated: %" PRIu64 " vs. %" PRIu64 ".",
1258 image_file_size,
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001259 sizeof(ImageHeader) + image_header->GetDataSize());
Andreas Gampe6c8b49f2015-02-19 11:42:36 -08001260 return nullptr;
1261 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001262
Mathieu Chartier9ff84602016-01-29 12:22:17 -08001263 if (oat_file != nullptr) {
1264 // If we have an oat file, check the oat file checksum. The oat file is only non-null for the
1265 // app image case. Otherwise, we open the oat file after the image and check the checksum there.
1266 const uint32_t oat_checksum = oat_file->GetOatHeader().GetChecksum();
1267 const uint32_t image_oat_checksum = image_header->GetOatChecksum();
1268 if (oat_checksum != image_oat_checksum) {
1269 *error_msg = StringPrintf("Oat checksum 0x%x does not match the image one 0x%x in image %s",
1270 oat_checksum,
1271 image_oat_checksum,
1272 image_filename);
1273 return nullptr;
1274 }
1275 }
1276
Jeff Haodcdc85b2015-12-04 14:06:18 -08001277 if (VLOG_IS_ON(startup)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001278 LOG(INFO) << "Dumping image sections";
1279 for (size_t i = 0; i < ImageHeader::kSectionCount; ++i) {
1280 const auto section_idx = static_cast<ImageHeader::ImageSections>(i);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001281 auto& section = image_header->GetImageSection(section_idx);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001282 LOG(INFO) << section_idx << " start="
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001283 << reinterpret_cast<void*>(image_header->GetImageBegin() + section.Offset()) << " "
1284 << section;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001285 }
1286 }
1287
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001288 const auto& bitmap_section = image_header->GetImageSection(ImageHeader::kSectionImageBitmap);
Mathieu Chartierceb07b32015-12-10 09:33:21 -08001289 // The location we want to map from is the first aligned page after the end of the stored
1290 // (possibly compressed) data.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001291 const size_t image_bitmap_offset = RoundUp(sizeof(ImageHeader) + image_header->GetDataSize(),
Mathieu Chartierceb07b32015-12-10 09:33:21 -08001292 kPageSize);
1293 const size_t end_of_bitmap = image_bitmap_offset + bitmap_section.Size();
Mathieu Chartierc7853442015-03-27 14:35:38 -07001294 if (end_of_bitmap != image_file_size) {
1295 *error_msg = StringPrintf(
1296 "Image file size does not equal end of bitmap: size=%" PRIu64 " vs. %zu.", image_file_size,
1297 end_of_bitmap);
Andreas Gampe6c8b49f2015-02-19 11:42:36 -08001298 return nullptr;
1299 }
1300
Mathieu Chartierceb07b32015-12-10 09:33:21 -08001301 std::unique_ptr<MemMap> map;
Andreas Gampe7fa55782016-06-15 17:45:01 -07001302 // GetImageBegin is the preferred address to map the image. If we manage to map the
1303 // image at the image begin, the amount of fixup work required is minimized.
1304 map.reset(LoadImageFile(image_filename,
1305 image_location,
1306 *image_header,
1307 image_header->GetImageBegin(),
1308 file->Fd(),
1309 logger,
1310 error_msg));
1311 // If the header specifies PIC mode, we can also map at a random low_4gb address since we can
1312 // relocate in-place.
1313 if (map == nullptr && image_header->IsPic()) {
1314 map.reset(LoadImageFile(image_filename,
1315 image_location,
1316 *image_header,
1317 /* address */ nullptr,
1318 file->Fd(),
1319 logger,
1320 error_msg));
Mathieu Chartierceb07b32015-12-10 09:33:21 -08001321 }
Andreas Gampe7fa55782016-06-15 17:45:01 -07001322 // Were we able to load something and continue?
Mathieu Chartier42bddce2015-11-09 15:16:56 -08001323 if (map == nullptr) {
Andreas Gampe7fa55782016-06-15 17:45:01 -07001324 DCHECK(!error_msg->empty());
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001325 return nullptr;
Ian Rogers1d54e732013-05-02 21:10:01 -07001326 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001327 DCHECK_EQ(0, memcmp(image_header, map->Begin(), sizeof(ImageHeader)));
Ian Rogers1d54e732013-05-02 21:10:01 -07001328
Mathieu Chartierceb07b32015-12-10 09:33:21 -08001329 std::unique_ptr<MemMap> image_bitmap_map(MemMap::MapFileAtAddress(nullptr,
1330 bitmap_section.Size(),
1331 PROT_READ, MAP_PRIVATE,
1332 file->Fd(),
1333 image_bitmap_offset,
1334 /*low_4gb*/false,
1335 /*reuse*/false,
1336 image_filename,
1337 error_msg));
1338 if (image_bitmap_map == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001339 *error_msg = StringPrintf("Failed to map image bitmap: %s", error_msg->c_str());
1340 return nullptr;
1341 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001342 // Loaded the map, use the image header from the file now in case we patch it with
1343 // RelocateInPlace.
1344 image_header = reinterpret_cast<ImageHeader*>(map->Begin());
1345 const uint32_t bitmap_index = bitmap_index_.FetchAndAddSequentiallyConsistent(1);
1346 std::string bitmap_name(StringPrintf("imagespace %s live-bitmap %u",
1347 image_filename,
Mathieu Chartier31e89252013-08-28 11:29:12 -07001348 bitmap_index));
Mathieu Chartier2d124ec2016-01-05 18:03:15 -08001349 // Bitmap only needs to cover until the end of the mirror objects section.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001350 const ImageSection& image_objects = image_header->GetImageSection(ImageHeader::kSectionObjects);
1351 // We only want the mirror object, not the ArtFields and ArtMethods.
1352 uint8_t* const image_end = map->Begin() + image_objects.End();
1353 std::unique_ptr<accounting::ContinuousSpaceBitmap> bitmap;
1354 {
1355 TimingLogger::ScopedTiming timing("CreateImageBitmap", &logger);
1356 bitmap.reset(
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001357 accounting::ContinuousSpaceBitmap::CreateFromMemMap(
Mathieu Chartierceb07b32015-12-10 09:33:21 -08001358 bitmap_name,
1359 image_bitmap_map.release(),
1360 reinterpret_cast<uint8_t*>(map->Begin()),
Mathieu Chartier2d124ec2016-01-05 18:03:15 -08001361 image_objects.End()));
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001362 if (bitmap == nullptr) {
1363 *error_msg = StringPrintf("Could not create bitmap '%s'", bitmap_name.c_str());
1364 return nullptr;
1365 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001366 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001367 {
1368 TimingLogger::ScopedTiming timing("RelocateImage", &logger);
1369 if (!RelocateInPlace(*image_header,
1370 map->Begin(),
1371 bitmap.get(),
1372 oat_file,
1373 error_msg)) {
1374 return nullptr;
1375 }
1376 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001377 // We only want the mirror object, not the ArtFields and ArtMethods.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001378 std::unique_ptr<ImageSpace> space(new ImageSpace(image_filename,
1379 image_location,
1380 map.release(),
1381 bitmap.release(),
Mathieu Chartier2d124ec2016-01-05 18:03:15 -08001382 image_end));
Hiroshi Yamauchibd0fb612014-05-20 13:46:00 -07001383
1384 // VerifyImageAllocations() will be called later in Runtime::Init()
1385 // as some class roots like ArtMethod::java_lang_reflect_ArtMethod_
1386 // and ArtField::java_lang_reflect_ArtField_, which are used from
1387 // Object::SizeOf() which VerifyImageAllocations() calls, are not
1388 // set yet at this point.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001389 if (oat_file == nullptr) {
1390 TimingLogger::ScopedTiming timing("OpenOatFile", &logger);
1391 space->oat_file_.reset(space->OpenOatFile(image_filename, error_msg));
1392 if (space->oat_file_ == nullptr) {
1393 DCHECK(!error_msg->empty());
1394 return nullptr;
1395 }
1396 space->oat_file_non_owned_ = space->oat_file_.get();
1397 } else {
1398 space->oat_file_non_owned_ = oat_file;
Nicolas Geoffray1bc977c2016-01-23 14:15:49 +00001399 }
Nicolas Geoffray1bc977c2016-01-23 14:15:49 +00001400
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001401 if (validate_oat_file) {
1402 TimingLogger::ScopedTiming timing("ValidateOatFile", &logger);
1403 if (!space->ValidateOatFile(error_msg)) {
1404 DCHECK(!error_msg->empty());
1405 return nullptr;
1406 }
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001407 }
1408
Vladimir Marko7624d252014-05-02 14:40:15 +01001409 Runtime* runtime = Runtime::Current();
Vladimir Marko7624d252014-05-02 14:40:15 +01001410
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001411 // If oat_file is null, then it is the boot image space. Use oat_file_non_owned_ from the space
1412 // to set the runtime methods.
1413 CHECK_EQ(oat_file != nullptr, image_header->IsAppImage());
1414 if (image_header->IsAppImage()) {
1415 CHECK_EQ(runtime->GetResolutionMethod(),
1416 image_header->GetImageMethod(ImageHeader::kResolutionMethod));
1417 CHECK_EQ(runtime->GetImtConflictMethod(),
1418 image_header->GetImageMethod(ImageHeader::kImtConflictMethod));
1419 CHECK_EQ(runtime->GetImtUnimplementedMethod(),
1420 image_header->GetImageMethod(ImageHeader::kImtUnimplementedMethod));
Vladimir Markofd36f1f2016-08-03 18:49:58 +01001421 CHECK_EQ(runtime->GetCalleeSaveMethod(Runtime::kSaveAllCalleeSaves),
1422 image_header->GetImageMethod(ImageHeader::kSaveAllCalleeSavesMethod));
1423 CHECK_EQ(runtime->GetCalleeSaveMethod(Runtime::kSaveRefsOnly),
1424 image_header->GetImageMethod(ImageHeader::kSaveRefsOnlyMethod));
1425 CHECK_EQ(runtime->GetCalleeSaveMethod(Runtime::kSaveRefsAndArgs),
1426 image_header->GetImageMethod(ImageHeader::kSaveRefsAndArgsMethod));
Vladimir Marko952dbb12016-07-28 12:01:51 +01001427 CHECK_EQ(runtime->GetCalleeSaveMethod(Runtime::kSaveEverything),
1428 image_header->GetImageMethod(ImageHeader::kSaveEverythingMethod));
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001429 } else if (!runtime->HasResolutionMethod()) {
1430 runtime->SetInstructionSet(space->oat_file_non_owned_->GetOatHeader().GetInstructionSet());
1431 runtime->SetResolutionMethod(image_header->GetImageMethod(ImageHeader::kResolutionMethod));
1432 runtime->SetImtConflictMethod(image_header->GetImageMethod(ImageHeader::kImtConflictMethod));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001433 runtime->SetImtUnimplementedMethod(
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001434 image_header->GetImageMethod(ImageHeader::kImtUnimplementedMethod));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001435 runtime->SetCalleeSaveMethod(
Vladimir Markofd36f1f2016-08-03 18:49:58 +01001436 image_header->GetImageMethod(ImageHeader::kSaveAllCalleeSavesMethod),
1437 Runtime::kSaveAllCalleeSaves);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001438 runtime->SetCalleeSaveMethod(
Vladimir Markofd36f1f2016-08-03 18:49:58 +01001439 image_header->GetImageMethod(ImageHeader::kSaveRefsOnlyMethod), Runtime::kSaveRefsOnly);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001440 runtime->SetCalleeSaveMethod(
Vladimir Markofd36f1f2016-08-03 18:49:58 +01001441 image_header->GetImageMethod(ImageHeader::kSaveRefsAndArgsMethod),
1442 Runtime::kSaveRefsAndArgs);
Vladimir Marko952dbb12016-07-28 12:01:51 +01001443 runtime->SetCalleeSaveMethod(
1444 image_header->GetImageMethod(ImageHeader::kSaveEverythingMethod), Runtime::kSaveEverything);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001445 }
Vladimir Marko7624d252014-05-02 14:40:15 +01001446
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001447 VLOG(image) << "ImageSpace::Init exiting " << *space.get();
1448 if (VLOG_IS_ON(image)) {
1449 logger.Dump(LOG(INFO));
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001450 }
1451 return space.release();
1452}
1453
Nicolas Geoffray9583fbc2014-02-28 15:21:07 +00001454OatFile* ImageSpace::OpenOatFile(const char* image_path, std::string* error_msg) const {
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001455 const ImageHeader& image_header = GetImageHeader();
Nicolas Geoffray9583fbc2014-02-28 15:21:07 +00001456 std::string oat_filename = ImageHeader::GetOatLocationFromImageLocation(image_path);
1457
Igor Murashkin46774762014-10-22 11:37:02 -07001458 CHECK(image_header.GetOatDataBegin() != nullptr);
1459
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -07001460 OatFile* oat_file = OatFile::Open(oat_filename,
1461 oat_filename,
1462 image_header.GetOatDataBegin(),
Igor Murashkin46774762014-10-22 11:37:02 -07001463 image_header.GetOatFileBegin(),
Richard Uhlere5fed032015-03-18 08:21:11 -07001464 !Runtime::Current()->IsAotCompiler(),
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001465 /*low_4gb*/false,
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -07001466 nullptr,
1467 error_msg);
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001468 if (oat_file == nullptr) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001469 *error_msg = StringPrintf("Failed to open oat file '%s' referenced from image %s: %s",
1470 oat_filename.c_str(), GetName(), error_msg->c_str());
1471 return nullptr;
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001472 }
1473 uint32_t oat_checksum = oat_file->GetOatHeader().GetChecksum();
1474 uint32_t image_oat_checksum = image_header.GetOatChecksum();
1475 if (oat_checksum != image_oat_checksum) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001476 *error_msg = StringPrintf("Failed to match oat file checksum 0x%x to expected oat checksum 0x%x"
1477 " in image %s", oat_checksum, image_oat_checksum, GetName());
1478 return nullptr;
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001479 }
Alex Lighta59dd802014-07-02 16:28:08 -07001480 int32_t image_patch_delta = image_header.GetPatchDelta();
1481 int32_t oat_patch_delta = oat_file->GetOatHeader().GetImagePatchDelta();
Igor Murashkin46774762014-10-22 11:37:02 -07001482 if (oat_patch_delta != image_patch_delta && !image_header.CompilePic()) {
Alex Lighta59dd802014-07-02 16:28:08 -07001483 // We should have already relocated by this point. Bail out.
1484 *error_msg = StringPrintf("Failed to match oat file patch delta %d to expected patch delta %d "
1485 "in image %s", oat_patch_delta, image_patch_delta, GetName());
1486 return nullptr;
1487 }
1488
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001489 return oat_file;
1490}
1491
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001492bool ImageSpace::ValidateOatFile(std::string* error_msg) const {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001493 CHECK(oat_file_.get() != nullptr);
Mathieu Chartier31e89252013-08-28 11:29:12 -07001494 for (const OatFile::OatDexFile* oat_dex_file : oat_file_->GetOatDexFiles()) {
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001495 const std::string& dex_file_location = oat_dex_file->GetDexFileLocation();
1496 uint32_t dex_file_location_checksum;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001497 if (!DexFile::GetChecksum(dex_file_location.c_str(), &dex_file_location_checksum, error_msg)) {
1498 *error_msg = StringPrintf("Failed to get checksum of dex file '%s' referenced by image %s: "
1499 "%s", dex_file_location.c_str(), GetName(), error_msg->c_str());
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001500 return false;
1501 }
1502 if (dex_file_location_checksum != oat_dex_file->GetDexFileLocationChecksum()) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001503 *error_msg = StringPrintf("ValidateOatFile found checksum mismatch between oat file '%s' and "
1504 "dex file '%s' (0x%x != 0x%x)",
1505 oat_file_->GetLocation().c_str(), dex_file_location.c_str(),
1506 oat_dex_file->GetDexFileLocationChecksum(),
1507 dex_file_location_checksum);
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001508 return false;
1509 }
1510 }
1511 return true;
1512}
1513
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001514const OatFile* ImageSpace::GetOatFile() const {
Andreas Gampe88da3b02015-06-12 20:38:49 -07001515 return oat_file_non_owned_;
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001516}
1517
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -07001518std::unique_ptr<const OatFile> ImageSpace::ReleaseOatFile() {
1519 CHECK(oat_file_ != nullptr);
1520 return std::move(oat_file_);
Ian Rogers1d54e732013-05-02 21:10:01 -07001521}
1522
Ian Rogers1d54e732013-05-02 21:10:01 -07001523void ImageSpace::Dump(std::ostream& os) const {
1524 os << GetType()
Mathieu Chartier590fee92013-09-13 13:46:47 -07001525 << " begin=" << reinterpret_cast<void*>(Begin())
Ian Rogers1d54e732013-05-02 21:10:01 -07001526 << ",end=" << reinterpret_cast<void*>(End())
1527 << ",size=" << PrettySize(Size())
1528 << ",name=\"" << GetName() << "\"]";
1529}
1530
Andreas Gampe8994a042015-12-30 19:03:17 +00001531void ImageSpace::CreateMultiImageLocations(const std::string& input_image_file_name,
1532 const std::string& boot_classpath,
1533 std::vector<std::string>* image_file_names) {
1534 DCHECK(image_file_names != nullptr);
1535
1536 std::vector<std::string> images;
1537 Split(boot_classpath, ':', &images);
1538
1539 // Add the rest into the list. We have to adjust locations, possibly:
1540 //
1541 // For example, image_file_name is /a/b/c/d/e.art
1542 // images[0] is f/c/d/e.art
1543 // ----------------------------------------------
1544 // images[1] is g/h/i/j.art -> /a/b/h/i/j.art
Mathieu Chartier8b8f6d62016-03-08 16:50:20 -08001545 const std::string& first_image = images[0];
1546 // Length of common suffix.
1547 size_t common = 0;
1548 while (common < input_image_file_name.size() &&
1549 common < first_image.size() &&
1550 *(input_image_file_name.end() - common - 1) == *(first_image.end() - common - 1)) {
1551 ++common;
Andreas Gampe8994a042015-12-30 19:03:17 +00001552 }
Mathieu Chartier8b8f6d62016-03-08 16:50:20 -08001553 // We want to replace the prefix of the input image with the prefix of the boot class path.
1554 // This handles the case where the image file contains @ separators.
1555 // Example image_file_name is oats/system@framework@boot.art
1556 // images[0] is .../arm/boot.art
1557 // means that the image name prefix will be oats/system@framework@
1558 // so that the other images are openable.
1559 const size_t old_prefix_length = first_image.size() - common;
1560 const std::string new_prefix = input_image_file_name.substr(
1561 0,
1562 input_image_file_name.size() - common);
Andreas Gampe8994a042015-12-30 19:03:17 +00001563
1564 // Apply pattern to images[1] .. images[n].
1565 for (size_t i = 1; i < images.size(); ++i) {
Mathieu Chartier8b8f6d62016-03-08 16:50:20 -08001566 const std::string& image = images[i];
1567 CHECK_GT(image.length(), old_prefix_length);
1568 std::string suffix = image.substr(old_prefix_length);
1569 image_file_names->push_back(new_prefix + suffix);
Andreas Gampe8994a042015-12-30 19:03:17 +00001570 }
1571}
1572
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001573ImageSpace* ImageSpace::CreateFromAppImage(const char* image,
1574 const OatFile* oat_file,
1575 std::string* error_msg) {
1576 return gc::space::ImageSpace::Init(image,
1577 image,
1578 /*validate_oat_file*/false,
1579 oat_file,
1580 /*out*/error_msg);
1581}
1582
Mathieu Chartierd5f3f322016-03-21 14:05:56 -07001583void ImageSpace::DumpSections(std::ostream& os) const {
1584 const uint8_t* base = Begin();
1585 const ImageHeader& header = GetImageHeader();
1586 for (size_t i = 0; i < ImageHeader::kSectionCount; ++i) {
1587 auto section_type = static_cast<ImageHeader::ImageSections>(i);
1588 const ImageSection& section = header.GetImageSection(section_type);
1589 os << section_type << " " << reinterpret_cast<const void*>(base + section.Offset())
1590 << "-" << reinterpret_cast<const void*>(base + section.End()) << "\n";
1591 }
1592}
1593
Ian Rogers1d54e732013-05-02 21:10:01 -07001594} // namespace space
1595} // namespace gc
1596} // namespace art