blob: 0936a53f99653a36b5ab701932373ffff71c140b [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>
Andreas Gampe70be1fb2014-10-31 16:45:19 -070020#include <sys/statvfs.h>
Alex Light25396132014-08-27 15:37:23 -070021#include <sys/types.h>
Narayan Kamath5a2be3f2015-02-16 13:51:51 +000022#include <unistd.h>
Alex Light25396132014-08-27 15:37:23 -070023
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070024#include <random>
25
Andreas Gampe46ee31b2016-12-14 10:11:49 -080026#include "android-base/stringprintf.h"
Andreas Gampe9186ced2016-12-12 14:28:21 -080027#include "android-base/strings.h"
28
Andreas Gampea1d2f952017-04-20 22:53:58 -070029#include "art_field-inl.h"
Andreas Gampec6ea7d02017-02-01 16:46:28 -080030#include "art_method-inl.h"
Andreas Gampe8228cdf2017-05-30 15:03:54 -070031#include "base/callee_save_type.h"
Andreas Gampe542451c2016-07-26 09:02:02 -070032#include "base/enums.h"
David Sehr891a50e2017-10-27 17:01:07 -070033#include "base/file_utils.h"
Ian Rogersc7dd2952014-10-21 23:31:19 -070034#include "base/macros.h"
David Sehrc431b9d2018-03-02 12:01:51 -080035#include "base/os.h"
Narayan Kamathd1c606f2014-06-09 16:50:19 +010036#include "base/scoped_flock.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070037#include "base/stl_util.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080038#include "base/systrace.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010039#include "base/time_utils.h"
David Sehrc431b9d2018-03-02 12:01:51 -080040#include "base/utils.h"
David Sehr013fd802018-01-11 22:55:24 -080041#include "dex/art_dex_file_loader.h"
David Sehr9e734c72018-01-04 17:56:19 -080042#include "dex/dex_file_loader.h"
David Sehr97c381e2017-02-01 15:09:58 -080043#include "exec_utils.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070044#include "gc/accounting/space_bitmap-inl.h"
Mathieu Chartier4a26f172016-01-26 14:26:18 -080045#include "image-inl.h"
Andreas Gampebec63582015-11-20 19:26:51 -080046#include "image_space_fs.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070047#include "mirror/class-inl.h"
48#include "mirror/object-inl.h"
Andreas Gampec6ea7d02017-02-01 16:46:28 -080049#include "mirror/object-refvisitor-inl.h"
Brian Carlstrom56d947f2013-07-15 13:14:23 -070050#include "oat_file.h"
Andreas Gamped482e732017-04-24 17:59:09 -070051#include "runtime.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070052#include "space-inl.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070053
54namespace art {
55namespace gc {
56namespace space {
57
Andreas Gampe46ee31b2016-12-14 10:11:49 -080058using android::base::StringAppendF;
59using android::base::StringPrintf;
60
Ian Rogersef7d42f2014-01-06 12:55:46 -080061Atomic<uint32_t> ImageSpace::bitmap_index_(0);
Ian Rogers1d54e732013-05-02 21:10:01 -070062
Jeff Haodcdc85b2015-12-04 14:06:18 -080063ImageSpace::ImageSpace(const std::string& image_filename,
64 const char* image_location,
65 MemMap* mem_map,
66 accounting::ContinuousSpaceBitmap* live_bitmap,
Mathieu Chartier2d124ec2016-01-05 18:03:15 -080067 uint8_t* end)
68 : MemMapSpace(image_filename,
69 mem_map,
70 mem_map->Begin(),
71 end,
72 end,
Narayan Kamath52f84882014-05-02 10:10:39 +010073 kGcRetentionPolicyNeverCollect),
Jeff Haodcdc85b2015-12-04 14:06:18 -080074 oat_file_non_owned_(nullptr),
Mathieu Chartier2d124ec2016-01-05 18:03:15 -080075 image_location_(image_location) {
Mathieu Chartier590fee92013-09-13 13:46:47 -070076 DCHECK(live_bitmap != nullptr);
Mathieu Chartier31e89252013-08-28 11:29:12 -070077 live_bitmap_.reset(live_bitmap);
Ian Rogers1d54e732013-05-02 21:10:01 -070078}
79
Alex Lightcf4bf382014-07-24 11:29:14 -070080static int32_t ChooseRelocationOffsetDelta(int32_t min_delta, int32_t max_delta) {
81 CHECK_ALIGNED(min_delta, kPageSize);
82 CHECK_ALIGNED(max_delta, kPageSize);
83 CHECK_LT(min_delta, max_delta);
84
Alex Light15324762015-11-19 11:03:10 -080085 int32_t r = GetRandomNumber<int32_t>(min_delta, max_delta);
Alex Lightcf4bf382014-07-24 11:29:14 -070086 if (r % 2 == 0) {
87 r = RoundUp(r, kPageSize);
88 } else {
89 r = RoundDown(r, kPageSize);
90 }
91 CHECK_LE(min_delta, r);
92 CHECK_GE(max_delta, r);
93 CHECK_ALIGNED(r, kPageSize);
94 return r;
95}
96
Andreas Gampea463b6a2016-08-12 21:53:32 -070097static int32_t ChooseRelocationOffsetDelta() {
98 return ChooseRelocationOffsetDelta(ART_BASE_ADDRESS_MIN_DELTA, ART_BASE_ADDRESS_MAX_DELTA);
99}
100
101static bool GenerateImage(const std::string& image_filename,
102 InstructionSet image_isa,
Alex Light25396132014-08-27 15:37:23 -0700103 std::string* error_msg) {
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700104 const std::string boot_class_path_string(Runtime::Current()->GetBootClassPathString());
105 std::vector<std::string> boot_class_path;
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700106 Split(boot_class_path_string, ':', &boot_class_path);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700107 if (boot_class_path.empty()) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700108 *error_msg = "Failed to generate image because no boot class path specified";
109 return false;
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700110 }
Alex Light25396132014-08-27 15:37:23 -0700111 // We should clean up so we are more likely to have room for the image.
112 if (Runtime::Current()->IsZygote()) {
Andreas Gampe3c13a792014-09-18 20:56:04 -0700113 LOG(INFO) << "Pruning dalvik-cache since we are generating an image and will need to recompile";
Narayan Kamath28bc9872014-11-07 17:46:28 +0000114 PruneDalvikCache(image_isa);
Alex Light25396132014-08-27 15:37:23 -0700115 }
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700116
Mathieu Chartier8bbc8c02013-07-31 16:27:01 -0700117 std::vector<std::string> arg_vector;
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700118
Tsu Chiang Chuang12e6d742014-05-22 10:22:25 -0700119 std::string dex2oat(Runtime::Current()->GetCompilerExecutable());
Mathieu Chartier08d7d442013-07-31 18:08:51 -0700120 arg_vector.push_back(dex2oat);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700121
122 std::string image_option_string("--image=");
Narayan Kamath52f84882014-05-02 10:10:39 +0100123 image_option_string += image_filename;
Mathieu Chartier8bbc8c02013-07-31 16:27:01 -0700124 arg_vector.push_back(image_option_string);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700125
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700126 for (size_t i = 0; i < boot_class_path.size(); i++) {
Mathieu Chartier8bbc8c02013-07-31 16:27:01 -0700127 arg_vector.push_back(std::string("--dex-file=") + boot_class_path[i]);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700128 }
129
130 std::string oat_file_option_string("--oat-file=");
Brian Carlstrom2f1e15c2014-10-27 16:27:06 -0700131 oat_file_option_string += ImageHeader::GetOatLocationFromImageLocation(image_filename);
Mathieu Chartier8bbc8c02013-07-31 16:27:01 -0700132 arg_vector.push_back(oat_file_option_string);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700133
Sebastien Hertz0de11332015-05-13 12:14:05 +0200134 // Note: we do not generate a fully debuggable boot image so we do not pass the
135 // compiler flag --debuggable here.
136
Igor Murashkinb1d8c312015-08-04 11:18:43 -0700137 Runtime::Current()->AddCurrentRuntimeFeaturesAsDex2OatArguments(&arg_vector);
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700138 CHECK_EQ(image_isa, kRuntimeISA)
139 << "We should always be generating an image for the current isa.";
Ian Rogers8afeb852014-04-02 14:55:49 -0700140
Andreas Gampea463b6a2016-08-12 21:53:32 -0700141 int32_t base_offset = ChooseRelocationOffsetDelta();
Alex Lightcf4bf382014-07-24 11:29:14 -0700142 LOG(INFO) << "Using an offset of 0x" << std::hex << base_offset << " from default "
143 << "art base address of 0x" << std::hex << ART_BASE_ADDRESS;
144 arg_vector.push_back(StringPrintf("--base=0x%x", ART_BASE_ADDRESS + base_offset));
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700145
Brian Carlstrom57309db2014-07-30 15:13:25 -0700146 if (!kIsTargetBuild) {
Mathieu Chartier8bbc8c02013-07-31 16:27:01 -0700147 arg_vector.push_back("--host");
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700148 }
149
Brian Carlstrom6449c622014-02-10 23:48:36 -0800150 const std::vector<std::string>& compiler_options = Runtime::Current()->GetImageCompilerOptions();
Brian Carlstrom2ec65202014-03-03 15:16:37 -0800151 for (size_t i = 0; i < compiler_options.size(); ++i) {
Brian Carlstrom6449c622014-02-10 23:48:36 -0800152 arg_vector.push_back(compiler_options[i].c_str());
153 }
154
Andreas Gampe9186ced2016-12-12 14:28:21 -0800155 std::string command_line(android::base::Join(arg_vector, ' '));
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700156 LOG(INFO) << "GenerateImage: " << command_line;
Brian Carlstrom6449c622014-02-10 23:48:36 -0800157 return Exec(arg_vector, error_msg);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700158}
159
Andreas Gampea463b6a2016-08-12 21:53:32 -0700160static bool FindImageFilenameImpl(const char* image_location,
161 const InstructionSet image_isa,
162 bool* has_system,
163 std::string* system_filename,
164 bool* dalvik_cache_exists,
165 std::string* dalvik_cache,
166 bool* is_global_cache,
167 bool* has_cache,
168 std::string* cache_filename) {
169 DCHECK(dalvik_cache != nullptr);
170
Alex Lighta59dd802014-07-02 16:28:08 -0700171 *has_system = false;
172 *has_cache = false;
Brian Carlstrom0e12bdc2014-05-14 17:44:28 -0700173 // image_location = /system/framework/boot.art
174 // system_image_location = /system/framework/<image_isa>/boot.art
175 std::string system_image_filename(GetSystemImageFilename(image_location, image_isa));
176 if (OS::FileExists(system_image_filename.c_str())) {
Alex Lighta59dd802014-07-02 16:28:08 -0700177 *system_filename = system_image_filename;
178 *has_system = true;
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700179 }
Narayan Kamath52f84882014-05-02 10:10:39 +0100180
Alex Lighta59dd802014-07-02 16:28:08 -0700181 bool have_android_data = false;
182 *dalvik_cache_exists = false;
Andreas Gampea463b6a2016-08-12 21:53:32 -0700183 GetDalvikCache(GetInstructionSetString(image_isa),
184 true,
185 dalvik_cache,
186 &have_android_data,
187 dalvik_cache_exists,
188 is_global_cache);
Narayan Kamath52f84882014-05-02 10:10:39 +0100189
Alex Lighta59dd802014-07-02 16:28:08 -0700190 if (have_android_data && *dalvik_cache_exists) {
191 // Always set output location even if it does not exist,
192 // so that the caller knows where to create the image.
193 //
194 // image_location = /system/framework/boot.art
195 // *image_filename = /data/dalvik-cache/<image_isa>/boot.art
196 std::string error_msg;
Andreas Gampea463b6a2016-08-12 21:53:32 -0700197 if (!GetDalvikCacheFilename(image_location,
198 dalvik_cache->c_str(),
199 cache_filename,
200 &error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -0700201 LOG(WARNING) << error_msg;
202 return *has_system;
203 }
204 *has_cache = OS::FileExists(cache_filename->c_str());
205 }
206 return *has_system || *has_cache;
207}
208
Andreas Gampea463b6a2016-08-12 21:53:32 -0700209bool ImageSpace::FindImageFilename(const char* image_location,
210 const InstructionSet image_isa,
211 std::string* system_filename,
212 bool* has_system,
213 std::string* cache_filename,
214 bool* dalvik_cache_exists,
215 bool* has_cache,
216 bool* is_global_cache) {
217 std::string dalvik_cache_unused;
218 return FindImageFilenameImpl(image_location,
219 image_isa,
220 has_system,
221 system_filename,
222 dalvik_cache_exists,
223 &dalvik_cache_unused,
224 is_global_cache,
225 has_cache,
226 cache_filename);
227}
228
Alex Lighta59dd802014-07-02 16:28:08 -0700229static bool ReadSpecificImageHeader(const char* filename, ImageHeader* image_header) {
230 std::unique_ptr<File> image_file(OS::OpenFileForReading(filename));
231 if (image_file.get() == nullptr) {
232 return false;
233 }
234 const bool success = image_file->ReadFully(image_header, sizeof(ImageHeader));
235 if (!success || !image_header->IsValid()) {
236 return false;
237 }
238 return true;
239}
240
Alex Light6e183f22014-07-18 14:57:04 -0700241// Relocate the image at image_location to dest_filename and relocate it by a random amount.
Andreas Gampea463b6a2016-08-12 21:53:32 -0700242static bool RelocateImage(const char* image_location,
Chris Morin88c6d262018-02-13 15:26:21 -0800243 const char* dest_directory,
Andreas Gampea463b6a2016-08-12 21:53:32 -0700244 InstructionSet isa,
245 std::string* error_msg) {
Alex Light25396132014-08-27 15:37:23 -0700246 // We should clean up so we are more likely to have room for the image.
247 if (Runtime::Current()->IsZygote()) {
248 LOG(INFO) << "Pruning dalvik-cache since we are relocating an image and will need to recompile";
Narayan Kamath28bc9872014-11-07 17:46:28 +0000249 PruneDalvikCache(isa);
Alex Light25396132014-08-27 15:37:23 -0700250 }
251
Alex Lighta59dd802014-07-02 16:28:08 -0700252 std::string patchoat(Runtime::Current()->GetPatchoatExecutable());
253
254 std::string input_image_location_arg("--input-image-location=");
255 input_image_location_arg += image_location;
256
Chris Morin88c6d262018-02-13 15:26:21 -0800257 std::string output_image_directory_arg("--output-image-directory=");
258 output_image_directory_arg += dest_directory;
Alex Lighta59dd802014-07-02 16:28:08 -0700259
Alex Lighta59dd802014-07-02 16:28:08 -0700260 std::string instruction_set_arg("--instruction-set=");
261 instruction_set_arg += GetInstructionSetString(isa);
262
263 std::string base_offset_arg("--base-offset-delta=");
Andreas Gampea463b6a2016-08-12 21:53:32 -0700264 StringAppendF(&base_offset_arg, "%d", ChooseRelocationOffsetDelta());
Alex Lighta59dd802014-07-02 16:28:08 -0700265
266 std::vector<std::string> argv;
267 argv.push_back(patchoat);
268
269 argv.push_back(input_image_location_arg);
Chris Morin88c6d262018-02-13 15:26:21 -0800270 argv.push_back(output_image_directory_arg);
Alex Lighta59dd802014-07-02 16:28:08 -0700271
Alex Lighta59dd802014-07-02 16:28:08 -0700272 argv.push_back(instruction_set_arg);
273 argv.push_back(base_offset_arg);
274
Andreas Gampe9186ced2016-12-12 14:28:21 -0800275 std::string command_line(android::base::Join(argv, ' '));
Alex Lighta59dd802014-07-02 16:28:08 -0700276 LOG(INFO) << "RelocateImage: " << command_line;
277 return Exec(argv, error_msg);
278}
279
Chris Morine5fac732018-02-05 14:27:40 -0800280static bool VerifyImage(const char* image_location,
Chris Morin88c6d262018-02-13 15:26:21 -0800281 const char* dest_directory,
Chris Morine5fac732018-02-05 14:27:40 -0800282 InstructionSet isa,
283 std::string* error_msg) {
284 std::string patchoat(Runtime::Current()->GetPatchoatExecutable());
285
286 std::string input_image_location_arg("--input-image-location=");
287 input_image_location_arg += image_location;
288
Chris Morin88c6d262018-02-13 15:26:21 -0800289 std::string output_image_directory_arg("--output-image-directory=");
290 output_image_directory_arg += dest_directory;
Chris Morine5fac732018-02-05 14:27:40 -0800291
292 std::string instruction_set_arg("--instruction-set=");
293 instruction_set_arg += GetInstructionSetString(isa);
294
295 std::vector<std::string> argv;
296 argv.push_back(patchoat);
297
298 argv.push_back(input_image_location_arg);
Chris Morin88c6d262018-02-13 15:26:21 -0800299 argv.push_back(output_image_directory_arg);
Chris Morine5fac732018-02-05 14:27:40 -0800300
301 argv.push_back(instruction_set_arg);
302
303 argv.push_back("--verify");
304
305 std::string command_line(android::base::Join(argv, ' '));
306 LOG(INFO) << "VerifyImage: " << command_line;
307 return Exec(argv, error_msg);
308}
309
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700310static ImageHeader* ReadSpecificImageHeader(const char* filename, std::string* error_msg) {
Alex Lighta59dd802014-07-02 16:28:08 -0700311 std::unique_ptr<ImageHeader> hdr(new ImageHeader);
312 if (!ReadSpecificImageHeader(filename, hdr.get())) {
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700313 *error_msg = StringPrintf("Unable to read image header for %s", filename);
Alex Lighta59dd802014-07-02 16:28:08 -0700314 return nullptr;
315 }
316 return hdr.release();
Narayan Kamath52f84882014-05-02 10:10:39 +0100317}
318
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700319ImageHeader* ImageSpace::ReadImageHeader(const char* image_location,
320 const InstructionSet image_isa,
321 std::string* error_msg) {
Alex Lighta59dd802014-07-02 16:28:08 -0700322 std::string system_filename;
323 bool has_system = false;
324 std::string cache_filename;
325 bool has_cache = false;
326 bool dalvik_cache_exists = false;
Andreas Gampe3c13a792014-09-18 20:56:04 -0700327 bool is_global_cache = false;
Alex Lighta59dd802014-07-02 16:28:08 -0700328 if (FindImageFilename(image_location, image_isa, &system_filename, &has_system,
Andreas Gampe3c13a792014-09-18 20:56:04 -0700329 &cache_filename, &dalvik_cache_exists, &has_cache, &is_global_cache)) {
Alex Lighta59dd802014-07-02 16:28:08 -0700330 if (Runtime::Current()->ShouldRelocate()) {
331 if (has_system && has_cache) {
332 std::unique_ptr<ImageHeader> sys_hdr(new ImageHeader);
333 std::unique_ptr<ImageHeader> cache_hdr(new ImageHeader);
334 if (!ReadSpecificImageHeader(system_filename.c_str(), sys_hdr.get())) {
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700335 *error_msg = StringPrintf("Unable to read image header for %s at %s",
336 image_location, system_filename.c_str());
Alex Lighta59dd802014-07-02 16:28:08 -0700337 return nullptr;
338 }
339 if (!ReadSpecificImageHeader(cache_filename.c_str(), cache_hdr.get())) {
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700340 *error_msg = StringPrintf("Unable to read image header for %s at %s",
341 image_location, cache_filename.c_str());
Alex Lighta59dd802014-07-02 16:28:08 -0700342 return nullptr;
343 }
344 if (sys_hdr->GetOatChecksum() != cache_hdr->GetOatChecksum()) {
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700345 *error_msg = StringPrintf("Unable to find a relocated version of image file %s",
346 image_location);
Alex Lighta59dd802014-07-02 16:28:08 -0700347 return nullptr;
348 }
349 return cache_hdr.release();
350 } else if (!has_cache) {
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700351 *error_msg = StringPrintf("Unable to find a relocated version of image file %s",
352 image_location);
Alex Lighta59dd802014-07-02 16:28:08 -0700353 return nullptr;
354 } else if (!has_system && has_cache) {
355 // This can probably just use the cache one.
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700356 return ReadSpecificImageHeader(cache_filename.c_str(), error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -0700357 }
358 } else {
359 // We don't want to relocate, Just pick the appropriate one if we have it and return.
360 if (has_system && has_cache) {
361 // We want the cache if the checksum matches, otherwise the system.
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700362 std::unique_ptr<ImageHeader> system(ReadSpecificImageHeader(system_filename.c_str(),
363 error_msg));
364 std::unique_ptr<ImageHeader> cache(ReadSpecificImageHeader(cache_filename.c_str(),
365 error_msg));
Alex Lighta59dd802014-07-02 16:28:08 -0700366 if (system.get() == nullptr ||
367 (cache.get() != nullptr && cache->GetOatChecksum() == system->GetOatChecksum())) {
368 return cache.release();
369 } else {
370 return system.release();
371 }
372 } else if (has_system) {
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700373 return ReadSpecificImageHeader(system_filename.c_str(), error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -0700374 } else if (has_cache) {
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700375 return ReadSpecificImageHeader(cache_filename.c_str(), error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -0700376 }
Narayan Kamath52f84882014-05-02 10:10:39 +0100377 }
Narayan Kamath52f84882014-05-02 10:10:39 +0100378 }
379
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700380 *error_msg = StringPrintf("Unable to find image file for %s", image_location);
Narayan Kamath52f84882014-05-02 10:10:39 +0100381 return nullptr;
382}
383
Andreas Gampea463b6a2016-08-12 21:53:32 -0700384static bool ChecksumsMatch(const char* image_a, const char* image_b, std::string* error_msg) {
385 DCHECK(error_msg != nullptr);
386
Alex Lighta59dd802014-07-02 16:28:08 -0700387 ImageHeader hdr_a;
388 ImageHeader hdr_b;
Andreas Gampea463b6a2016-08-12 21:53:32 -0700389
390 if (!ReadSpecificImageHeader(image_a, &hdr_a)) {
391 *error_msg = StringPrintf("Cannot read header of %s", image_a);
392 return false;
393 }
394 if (!ReadSpecificImageHeader(image_b, &hdr_b)) {
395 *error_msg = StringPrintf("Cannot read header of %s", image_b);
396 return false;
397 }
398
399 if (hdr_a.GetOatChecksum() != hdr_b.GetOatChecksum()) {
400 *error_msg = StringPrintf("Checksum mismatch: %u(%s) vs %u(%s)",
401 hdr_a.GetOatChecksum(),
402 image_a,
403 hdr_b.GetOatChecksum(),
404 image_b);
405 return false;
406 }
407
408 return true;
Alex Lighta59dd802014-07-02 16:28:08 -0700409}
410
Robert Sesekbfa1f8d2016-08-15 15:21:09 -0400411static bool CanWriteToDalvikCache(const InstructionSet isa) {
412 const std::string dalvik_cache = GetDalvikCache(GetInstructionSetString(isa));
413 if (access(dalvik_cache.c_str(), O_RDWR) == 0) {
414 return true;
415 } else if (errno != EACCES) {
416 PLOG(WARNING) << "CanWriteToDalvikCache returned error other than EACCES";
417 }
418 return false;
419}
420
421static bool ImageCreationAllowed(bool is_global_cache,
422 const InstructionSet isa,
423 std::string* error_msg) {
Andreas Gampe3c13a792014-09-18 20:56:04 -0700424 // Anyone can write into a "local" cache.
425 if (!is_global_cache) {
426 return true;
427 }
428
Robert Sesekbfa1f8d2016-08-15 15:21:09 -0400429 // Only the zygote running as root is allowed to create the global boot image.
430 // If the zygote is running as non-root (and cannot write to the dalvik-cache),
431 // then image creation is not allowed..
Andreas Gampe3c13a792014-09-18 20:56:04 -0700432 if (Runtime::Current()->IsZygote()) {
Robert Sesekbfa1f8d2016-08-15 15:21:09 -0400433 return CanWriteToDalvikCache(isa);
Andreas Gampe3c13a792014-09-18 20:56:04 -0700434 }
435
436 *error_msg = "Only the zygote can create the global boot image.";
437 return false;
438}
439
Mathieu Chartier31e89252013-08-28 11:29:12 -0700440void ImageSpace::VerifyImageAllocations() {
Ian Rogers13735952014-10-08 12:43:28 -0700441 uint8_t* current = Begin() + RoundUp(sizeof(ImageHeader), kObjectAlignment);
Mathieu Chartier31e89252013-08-28 11:29:12 -0700442 while (current < End()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700443 CHECK_ALIGNED(current, kObjectAlignment);
444 auto* obj = reinterpret_cast<mirror::Object*>(current);
Mathieu Chartier31e89252013-08-28 11:29:12 -0700445 CHECK(obj->GetClass() != nullptr) << "Image object at address " << obj << " has null class";
David Sehr709b0702016-10-13 09:12:37 -0700446 CHECK(live_bitmap_->Test(obj)) << obj->PrettyTypeOf();
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700447 if (kUseBakerReadBarrier) {
448 obj->AssertReadBarrierState();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800449 }
Mathieu Chartier31e89252013-08-28 11:29:12 -0700450 current += RoundUp(obj->SizeOf(), kObjectAlignment);
451 }
452}
453
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800454// Helper class for relocating from one range of memory to another.
455class RelocationRange {
456 public:
457 RelocationRange() = default;
458 RelocationRange(const RelocationRange&) = default;
459 RelocationRange(uintptr_t source, uintptr_t dest, uintptr_t length)
460 : source_(source),
461 dest_(dest),
462 length_(length) {}
463
Mathieu Chartier91edc622016-02-16 17:16:01 -0800464 bool InSource(uintptr_t address) const {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800465 return address - source_ < length_;
466 }
467
Mathieu Chartier91edc622016-02-16 17:16:01 -0800468 bool InDest(uintptr_t address) const {
469 return address - dest_ < length_;
470 }
471
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800472 // Translate a source address to the destination space.
473 uintptr_t ToDest(uintptr_t address) const {
Mathieu Chartier91edc622016-02-16 17:16:01 -0800474 DCHECK(InSource(address));
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800475 return address + Delta();
476 }
477
478 // Returns the delta between the dest from the source.
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800479 uintptr_t Delta() const {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800480 return dest_ - source_;
481 }
482
483 uintptr_t Source() const {
484 return source_;
485 }
486
487 uintptr_t Dest() const {
488 return dest_;
489 }
490
491 uintptr_t Length() const {
492 return length_;
493 }
494
495 private:
496 const uintptr_t source_;
497 const uintptr_t dest_;
498 const uintptr_t length_;
499};
500
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800501std::ostream& operator<<(std::ostream& os, const RelocationRange& reloc) {
502 return os << "(" << reinterpret_cast<const void*>(reloc.Source()) << "-"
503 << reinterpret_cast<const void*>(reloc.Source() + reloc.Length()) << ")->("
504 << reinterpret_cast<const void*>(reloc.Dest()) << "-"
505 << reinterpret_cast<const void*>(reloc.Dest() + reloc.Length()) << ")";
506}
507
Andreas Gampea463b6a2016-08-12 21:53:32 -0700508// Helper class encapsulating loading, so we can access private ImageSpace members (this is a
509// friend class), but not declare functions in the header.
510class ImageSpaceLoader {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800511 public:
Andreas Gampea463b6a2016-08-12 21:53:32 -0700512 static std::unique_ptr<ImageSpace> Load(const char* image_location,
513 const std::string& image_filename,
514 bool is_zygote,
515 bool is_global_cache,
Andreas Gampe44c8ed62016-08-19 16:43:00 -0700516 bool validate_oat_file,
Andreas Gampea463b6a2016-08-12 21:53:32 -0700517 std::string* error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700518 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampea463b6a2016-08-12 21:53:32 -0700519 // Should this be a RDWR lock? This is only a defensive measure, as at
520 // this point the image should exist.
521 // However, only the zygote can write into the global dalvik-cache, so
522 // restrict to zygote processes, or any process that isn't using
523 // /data/dalvik-cache (which we assume to be allowed to write there).
524 const bool rw_lock = is_zygote || !is_global_cache;
Narayan Kamatha3d27eb2017-05-11 13:50:59 +0100525
526 // Note that we must not use the file descriptor associated with
527 // ScopedFlock::GetFile to Init the image file. We want the file
528 // descriptor (and the associated exclusive lock) to be released when
529 // we leave Create.
530 ScopedFlock image = LockedFile::Open(image_filename.c_str(),
531 rw_lock ? (O_CREAT | O_RDWR) : O_RDONLY /* flags */,
532 true /* block */,
533 error_msg);
534
Andreas Gampea463b6a2016-08-12 21:53:32 -0700535 VLOG(startup) << "Using image file " << image_filename.c_str() << " for image location "
536 << image_location;
537 // If we are in /system we can assume the image is good. We can also
538 // assume this if we are using a relocated image (i.e. image checksum
539 // matches) since this is only different by the offset. We need this to
540 // make sure that host tests continue to work.
541 // Since we are the boot image, pass null since we load the oat file from the boot image oat
542 // file name.
543 return Init(image_filename.c_str(),
544 image_location,
Andreas Gampe44c8ed62016-08-19 16:43:00 -0700545 validate_oat_file,
Andreas Gampea463b6a2016-08-12 21:53:32 -0700546 /* oat_file */nullptr,
547 error_msg);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800548 }
549
Andreas Gampea463b6a2016-08-12 21:53:32 -0700550 static std::unique_ptr<ImageSpace> Init(const char* image_filename,
551 const char* image_location,
552 bool validate_oat_file,
553 const OatFile* oat_file,
554 std::string* error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700555 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampea463b6a2016-08-12 21:53:32 -0700556 CHECK(image_filename != nullptr);
557 CHECK(image_location != nullptr);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800558
Andreas Gampea463b6a2016-08-12 21:53:32 -0700559 TimingLogger logger(__PRETTY_FUNCTION__, true, VLOG_IS_ON(image));
560 VLOG(image) << "ImageSpace::Init entering image_filename=" << image_filename;
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800561
Andreas Gampea463b6a2016-08-12 21:53:32 -0700562 std::unique_ptr<File> file;
Mathieu Chartier92ec5942016-04-11 12:03:48 -0700563 {
Andreas Gampea463b6a2016-08-12 21:53:32 -0700564 TimingLogger::ScopedTiming timing("OpenImageFile", &logger);
565 file.reset(OS::OpenFileForReading(image_filename));
566 if (file == nullptr) {
567 *error_msg = StringPrintf("Failed to open '%s'", image_filename);
568 return nullptr;
Mathieu Chartier92ec5942016-04-11 12:03:48 -0700569 }
Andreas Gampea463b6a2016-08-12 21:53:32 -0700570 }
571 ImageHeader temp_image_header;
572 ImageHeader* image_header = &temp_image_header;
573 {
574 TimingLogger::ScopedTiming timing("ReadImageHeader", &logger);
575 bool success = file->ReadFully(image_header, sizeof(*image_header));
576 if (!success || !image_header->IsValid()) {
577 *error_msg = StringPrintf("Invalid image header in '%s'", image_filename);
578 return nullptr;
579 }
580 }
581 // Check that the file is larger or equal to the header size + data size.
582 const uint64_t image_file_size = static_cast<uint64_t>(file->GetLength());
583 if (image_file_size < sizeof(ImageHeader) + image_header->GetDataSize()) {
584 *error_msg = StringPrintf("Image file truncated: %" PRIu64 " vs. %" PRIu64 ".",
585 image_file_size,
586 sizeof(ImageHeader) + image_header->GetDataSize());
587 return nullptr;
588 }
589
590 if (oat_file != nullptr) {
591 // If we have an oat file, check the oat file checksum. The oat file is only non-null for the
592 // app image case. Otherwise, we open the oat file after the image and check the checksum there.
593 const uint32_t oat_checksum = oat_file->GetOatHeader().GetChecksum();
594 const uint32_t image_oat_checksum = image_header->GetOatChecksum();
595 if (oat_checksum != image_oat_checksum) {
596 *error_msg = StringPrintf("Oat checksum 0x%x does not match the image one 0x%x in image %s",
597 oat_checksum,
598 image_oat_checksum,
599 image_filename);
600 return nullptr;
Mathieu Chartier92ec5942016-04-11 12:03:48 -0700601 }
602 }
603
Andreas Gampea463b6a2016-08-12 21:53:32 -0700604 if (VLOG_IS_ON(startup)) {
605 LOG(INFO) << "Dumping image sections";
606 for (size_t i = 0; i < ImageHeader::kSectionCount; ++i) {
607 const auto section_idx = static_cast<ImageHeader::ImageSections>(i);
608 auto& section = image_header->GetImageSection(section_idx);
609 LOG(INFO) << section_idx << " start="
610 << reinterpret_cast<void*>(image_header->GetImageBegin() + section.Offset()) << " "
611 << section;
Mathieu Chartier92ec5942016-04-11 12:03:48 -0700612 }
Andreas Gampea463b6a2016-08-12 21:53:32 -0700613 }
614
Vladimir Markocd87c3e2017-09-05 13:11:57 +0100615 const auto& bitmap_section = image_header->GetImageBitmapSection();
Andreas Gampea463b6a2016-08-12 21:53:32 -0700616 // The location we want to map from is the first aligned page after the end of the stored
617 // (possibly compressed) data.
618 const size_t image_bitmap_offset = RoundUp(sizeof(ImageHeader) + image_header->GetDataSize(),
619 kPageSize);
620 const size_t end_of_bitmap = image_bitmap_offset + bitmap_section.Size();
621 if (end_of_bitmap != image_file_size) {
622 *error_msg = StringPrintf(
623 "Image file size does not equal end of bitmap: size=%" PRIu64 " vs. %zu.", image_file_size,
624 end_of_bitmap);
625 return nullptr;
626 }
627
628 std::unique_ptr<MemMap> map;
Mathieu Chartier66b1d572017-02-10 18:41:39 -0800629
Andreas Gampea463b6a2016-08-12 21:53:32 -0700630 // GetImageBegin is the preferred address to map the image. If we manage to map the
631 // image at the image begin, the amount of fixup work required is minimized.
Mathieu Chartier66b1d572017-02-10 18:41:39 -0800632 // If it is pic we will retry with error_msg for the failure case. Pass a null error_msg to
633 // avoid reading proc maps for a mapping failure and slowing everything down.
Andreas Gampea463b6a2016-08-12 21:53:32 -0700634 map.reset(LoadImageFile(image_filename,
635 image_location,
636 *image_header,
637 image_header->GetImageBegin(),
638 file->Fd(),
639 logger,
Mathieu Chartier66b1d572017-02-10 18:41:39 -0800640 image_header->IsPic() ? nullptr : error_msg));
Andreas Gampea463b6a2016-08-12 21:53:32 -0700641 // If the header specifies PIC mode, we can also map at a random low_4gb address since we can
642 // relocate in-place.
643 if (map == nullptr && image_header->IsPic()) {
644 map.reset(LoadImageFile(image_filename,
645 image_location,
646 *image_header,
647 /* address */ nullptr,
648 file->Fd(),
649 logger,
650 error_msg));
651 }
652 // Were we able to load something and continue?
653 if (map == nullptr) {
654 DCHECK(!error_msg->empty());
655 return nullptr;
656 }
657 DCHECK_EQ(0, memcmp(image_header, map->Begin(), sizeof(ImageHeader)));
658
659 std::unique_ptr<MemMap> image_bitmap_map(MemMap::MapFileAtAddress(nullptr,
660 bitmap_section.Size(),
661 PROT_READ, MAP_PRIVATE,
662 file->Fd(),
663 image_bitmap_offset,
664 /*low_4gb*/false,
665 /*reuse*/false,
666 image_filename,
667 error_msg));
668 if (image_bitmap_map == nullptr) {
669 *error_msg = StringPrintf("Failed to map image bitmap: %s", error_msg->c_str());
670 return nullptr;
671 }
672 // Loaded the map, use the image header from the file now in case we patch it with
673 // RelocateInPlace.
674 image_header = reinterpret_cast<ImageHeader*>(map->Begin());
Orion Hodson88591fe2018-03-06 13:35:43 +0000675 const uint32_t bitmap_index = ImageSpace::bitmap_index_.fetch_add(1, std::memory_order_seq_cst);
Andreas Gampea463b6a2016-08-12 21:53:32 -0700676 std::string bitmap_name(StringPrintf("imagespace %s live-bitmap %u",
677 image_filename,
678 bitmap_index));
679 // Bitmap only needs to cover until the end of the mirror objects section.
Vladimir Markocd87c3e2017-09-05 13:11:57 +0100680 const ImageSection& image_objects = image_header->GetObjectsSection();
Andreas Gampea463b6a2016-08-12 21:53:32 -0700681 // We only want the mirror object, not the ArtFields and ArtMethods.
682 uint8_t* const image_end = map->Begin() + image_objects.End();
683 std::unique_ptr<accounting::ContinuousSpaceBitmap> bitmap;
684 {
685 TimingLogger::ScopedTiming timing("CreateImageBitmap", &logger);
686 bitmap.reset(
687 accounting::ContinuousSpaceBitmap::CreateFromMemMap(
688 bitmap_name,
689 image_bitmap_map.release(),
690 reinterpret_cast<uint8_t*>(map->Begin()),
Mathieu Chartier612ff542017-05-01 09:59:24 -0700691 // Make sure the bitmap is aligned to card size instead of just bitmap word size.
692 RoundUp(image_objects.End(), gc::accounting::CardTable::kCardSize)));
Andreas Gampea463b6a2016-08-12 21:53:32 -0700693 if (bitmap == nullptr) {
694 *error_msg = StringPrintf("Could not create bitmap '%s'", bitmap_name.c_str());
695 return nullptr;
696 }
697 }
698 {
699 TimingLogger::ScopedTiming timing("RelocateImage", &logger);
700 if (!RelocateInPlace(*image_header,
701 map->Begin(),
702 bitmap.get(),
703 oat_file,
704 error_msg)) {
705 return nullptr;
706 }
707 }
708 // We only want the mirror object, not the ArtFields and ArtMethods.
709 std::unique_ptr<ImageSpace> space(new ImageSpace(image_filename,
710 image_location,
711 map.release(),
712 bitmap.release(),
713 image_end));
714
715 // VerifyImageAllocations() will be called later in Runtime::Init()
716 // as some class roots like ArtMethod::java_lang_reflect_ArtMethod_
717 // and ArtField::java_lang_reflect_ArtField_, which are used from
718 // Object::SizeOf() which VerifyImageAllocations() calls, are not
719 // set yet at this point.
720 if (oat_file == nullptr) {
721 TimingLogger::ScopedTiming timing("OpenOatFile", &logger);
722 space->oat_file_ = OpenOatFile(*space, image_filename, error_msg);
723 if (space->oat_file_ == nullptr) {
724 DCHECK(!error_msg->empty());
725 return nullptr;
726 }
727 space->oat_file_non_owned_ = space->oat_file_.get();
728 } else {
729 space->oat_file_non_owned_ = oat_file;
730 }
731
732 if (validate_oat_file) {
733 TimingLogger::ScopedTiming timing("ValidateOatFile", &logger);
734 CHECK(space->oat_file_ != nullptr);
Richard Uhler84f50ae2017-02-06 15:12:45 +0000735 if (!ImageSpace::ValidateOatFile(*space->oat_file_, error_msg)) {
Andreas Gampea463b6a2016-08-12 21:53:32 -0700736 DCHECK(!error_msg->empty());
737 return nullptr;
738 }
739 }
740
741 Runtime* runtime = Runtime::Current();
742
743 // If oat_file is null, then it is the boot image space. Use oat_file_non_owned_ from the space
744 // to set the runtime methods.
745 CHECK_EQ(oat_file != nullptr, image_header->IsAppImage());
746 if (image_header->IsAppImage()) {
747 CHECK_EQ(runtime->GetResolutionMethod(),
748 image_header->GetImageMethod(ImageHeader::kResolutionMethod));
749 CHECK_EQ(runtime->GetImtConflictMethod(),
750 image_header->GetImageMethod(ImageHeader::kImtConflictMethod));
751 CHECK_EQ(runtime->GetImtUnimplementedMethod(),
752 image_header->GetImageMethod(ImageHeader::kImtUnimplementedMethod));
Andreas Gampe8228cdf2017-05-30 15:03:54 -0700753 CHECK_EQ(runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveAllCalleeSaves),
Andreas Gampea463b6a2016-08-12 21:53:32 -0700754 image_header->GetImageMethod(ImageHeader::kSaveAllCalleeSavesMethod));
Andreas Gampe8228cdf2017-05-30 15:03:54 -0700755 CHECK_EQ(runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveRefsOnly),
Andreas Gampea463b6a2016-08-12 21:53:32 -0700756 image_header->GetImageMethod(ImageHeader::kSaveRefsOnlyMethod));
Andreas Gampe8228cdf2017-05-30 15:03:54 -0700757 CHECK_EQ(runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveRefsAndArgs),
Andreas Gampea463b6a2016-08-12 21:53:32 -0700758 image_header->GetImageMethod(ImageHeader::kSaveRefsAndArgsMethod));
Andreas Gampe8228cdf2017-05-30 15:03:54 -0700759 CHECK_EQ(runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveEverything),
Andreas Gampea463b6a2016-08-12 21:53:32 -0700760 image_header->GetImageMethod(ImageHeader::kSaveEverythingMethod));
Mingyao Yang0a87a652017-04-12 13:43:15 -0700761 CHECK_EQ(runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveEverythingForClinit),
762 image_header->GetImageMethod(ImageHeader::kSaveEverythingMethodForClinit));
763 CHECK_EQ(runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveEverythingForSuspendCheck),
764 image_header->GetImageMethod(ImageHeader::kSaveEverythingMethodForSuspendCheck));
Andreas Gampea463b6a2016-08-12 21:53:32 -0700765 } else if (!runtime->HasResolutionMethod()) {
766 runtime->SetInstructionSet(space->oat_file_non_owned_->GetOatHeader().GetInstructionSet());
767 runtime->SetResolutionMethod(image_header->GetImageMethod(ImageHeader::kResolutionMethod));
768 runtime->SetImtConflictMethod(image_header->GetImageMethod(ImageHeader::kImtConflictMethod));
769 runtime->SetImtUnimplementedMethod(
770 image_header->GetImageMethod(ImageHeader::kImtUnimplementedMethod));
771 runtime->SetCalleeSaveMethod(
772 image_header->GetImageMethod(ImageHeader::kSaveAllCalleeSavesMethod),
Andreas Gampe8228cdf2017-05-30 15:03:54 -0700773 CalleeSaveType::kSaveAllCalleeSaves);
Andreas Gampea463b6a2016-08-12 21:53:32 -0700774 runtime->SetCalleeSaveMethod(
Andreas Gampe8228cdf2017-05-30 15:03:54 -0700775 image_header->GetImageMethod(ImageHeader::kSaveRefsOnlyMethod),
776 CalleeSaveType::kSaveRefsOnly);
Andreas Gampea463b6a2016-08-12 21:53:32 -0700777 runtime->SetCalleeSaveMethod(
778 image_header->GetImageMethod(ImageHeader::kSaveRefsAndArgsMethod),
Andreas Gampe8228cdf2017-05-30 15:03:54 -0700779 CalleeSaveType::kSaveRefsAndArgs);
Andreas Gampea463b6a2016-08-12 21:53:32 -0700780 runtime->SetCalleeSaveMethod(
Andreas Gampe8228cdf2017-05-30 15:03:54 -0700781 image_header->GetImageMethod(ImageHeader::kSaveEverythingMethod),
782 CalleeSaveType::kSaveEverything);
Mingyao Yang0a87a652017-04-12 13:43:15 -0700783 runtime->SetCalleeSaveMethod(
784 image_header->GetImageMethod(ImageHeader::kSaveEverythingMethodForClinit),
785 CalleeSaveType::kSaveEverythingForClinit);
786 runtime->SetCalleeSaveMethod(
787 image_header->GetImageMethod(ImageHeader::kSaveEverythingMethodForSuspendCheck),
788 CalleeSaveType::kSaveEverythingForSuspendCheck);
Andreas Gampea463b6a2016-08-12 21:53:32 -0700789 }
790
791 VLOG(image) << "ImageSpace::Init exiting " << *space.get();
792 if (VLOG_IS_ON(image)) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700793 logger.Dump(LOG_STREAM(INFO));
Andreas Gampea463b6a2016-08-12 21:53:32 -0700794 }
795 return space;
796 }
797
798 private:
799 static MemMap* LoadImageFile(const char* image_filename,
800 const char* image_location,
801 const ImageHeader& image_header,
802 uint8_t* address,
803 int fd,
804 TimingLogger& logger,
805 std::string* error_msg) {
806 TimingLogger::ScopedTiming timing("MapImageFile", &logger);
807 const ImageHeader::StorageMode storage_mode = image_header.GetStorageMode();
808 if (storage_mode == ImageHeader::kStorageModeUncompressed) {
809 return MemMap::MapFileAtAddress(address,
810 image_header.GetImageSize(),
811 PROT_READ | PROT_WRITE,
812 MAP_PRIVATE,
813 fd,
814 0,
815 /*low_4gb*/true,
816 /*reuse*/false,
817 image_filename,
818 error_msg);
819 }
820
821 if (storage_mode != ImageHeader::kStorageModeLZ4 &&
822 storage_mode != ImageHeader::kStorageModeLZ4HC) {
Mathieu Chartier66b1d572017-02-10 18:41:39 -0800823 if (error_msg != nullptr) {
824 *error_msg = StringPrintf("Invalid storage mode in image header %d",
825 static_cast<int>(storage_mode));
826 }
Andreas Gampea463b6a2016-08-12 21:53:32 -0700827 return nullptr;
828 }
829
830 // Reserve output and decompress into it.
831 std::unique_ptr<MemMap> map(MemMap::MapAnonymous(image_location,
832 address,
833 image_header.GetImageSize(),
834 PROT_READ | PROT_WRITE,
835 /*low_4gb*/true,
836 /*reuse*/false,
837 error_msg));
838 if (map != nullptr) {
839 const size_t stored_size = image_header.GetDataSize();
840 const size_t decompress_offset = sizeof(ImageHeader); // Skip the header.
841 std::unique_ptr<MemMap> temp_map(MemMap::MapFile(sizeof(ImageHeader) + stored_size,
842 PROT_READ,
843 MAP_PRIVATE,
844 fd,
845 /*offset*/0,
846 /*low_4gb*/false,
847 image_filename,
848 error_msg));
849 if (temp_map == nullptr) {
Mathieu Chartier66b1d572017-02-10 18:41:39 -0800850 DCHECK(error_msg == nullptr || !error_msg->empty());
Andreas Gampea463b6a2016-08-12 21:53:32 -0700851 return nullptr;
852 }
853 memcpy(map->Begin(), &image_header, sizeof(ImageHeader));
854 const uint64_t start = NanoTime();
855 // LZ4HC and LZ4 have same internal format, both use LZ4_decompress.
856 TimingLogger::ScopedTiming timing2("LZ4 decompress image", &logger);
857 const size_t decompressed_size = LZ4_decompress_safe(
858 reinterpret_cast<char*>(temp_map->Begin()) + sizeof(ImageHeader),
859 reinterpret_cast<char*>(map->Begin()) + decompress_offset,
860 stored_size,
861 map->Size() - decompress_offset);
Mathieu Chartier0d4d2912017-02-10 17:22:41 -0800862 const uint64_t time = NanoTime() - start;
863 // Add one 1 ns to prevent possible divide by 0.
864 VLOG(image) << "Decompressing image took " << PrettyDuration(time) << " ("
865 << PrettySize(static_cast<uint64_t>(map->Size()) * MsToNs(1000) / (time + 1))
866 << "/s)";
Andreas Gampea463b6a2016-08-12 21:53:32 -0700867 if (decompressed_size + sizeof(ImageHeader) != image_header.GetImageSize()) {
Mathieu Chartier66b1d572017-02-10 18:41:39 -0800868 if (error_msg != nullptr) {
869 *error_msg = StringPrintf(
870 "Decompressed size does not match expected image size %zu vs %zu",
871 decompressed_size + sizeof(ImageHeader),
872 image_header.GetImageSize());
873 }
Andreas Gampea463b6a2016-08-12 21:53:32 -0700874 return nullptr;
875 }
876 }
877
878 return map.release();
879 }
880
881 class FixupVisitor : public ValueObject {
882 public:
883 FixupVisitor(const RelocationRange& boot_image,
884 const RelocationRange& boot_oat,
885 const RelocationRange& app_image,
886 const RelocationRange& app_oat)
887 : boot_image_(boot_image),
888 boot_oat_(boot_oat),
889 app_image_(app_image),
890 app_oat_(app_oat) {}
891
892 // Return the relocated address of a heap object.
893 template <typename T>
894 ALWAYS_INLINE T* ForwardObject(T* src) const {
895 const uintptr_t uint_src = reinterpret_cast<uintptr_t>(src);
896 if (boot_image_.InSource(uint_src)) {
897 return reinterpret_cast<T*>(boot_image_.ToDest(uint_src));
898 }
899 if (app_image_.InSource(uint_src)) {
900 return reinterpret_cast<T*>(app_image_.ToDest(uint_src));
901 }
902 // Since we are fixing up the app image, there should only be pointers to the app image and
903 // boot image.
904 DCHECK(src == nullptr) << reinterpret_cast<const void*>(src);
905 return src;
906 }
907
908 // Return the relocated address of a code pointer (contained by an oat file).
909 ALWAYS_INLINE const void* ForwardCode(const void* src) const {
910 const uintptr_t uint_src = reinterpret_cast<uintptr_t>(src);
911 if (boot_oat_.InSource(uint_src)) {
912 return reinterpret_cast<const void*>(boot_oat_.ToDest(uint_src));
913 }
914 if (app_oat_.InSource(uint_src)) {
915 return reinterpret_cast<const void*>(app_oat_.ToDest(uint_src));
916 }
917 DCHECK(src == nullptr) << src;
918 return src;
919 }
920
921 // Must be called on pointers that already have been relocated to the destination relocation.
922 ALWAYS_INLINE bool IsInAppImage(mirror::Object* object) const {
923 return app_image_.InDest(reinterpret_cast<uintptr_t>(object));
924 }
925
926 protected:
927 // Source section.
928 const RelocationRange boot_image_;
929 const RelocationRange boot_oat_;
930 const RelocationRange app_image_;
931 const RelocationRange app_oat_;
932 };
933
934 // Adapt for mirror::Class::FixupNativePointers.
935 class FixupObjectAdapter : public FixupVisitor {
936 public:
937 template<typename... Args>
938 explicit FixupObjectAdapter(Args... args) : FixupVisitor(args...) {}
939
940 template <typename T>
Mathieu Chartier8c19d242017-03-06 12:35:10 -0800941 T* operator()(T* obj, void** dest_addr ATTRIBUTE_UNUSED = nullptr) const {
Andreas Gampea463b6a2016-08-12 21:53:32 -0700942 return ForwardObject(obj);
943 }
944 };
945
946 class FixupRootVisitor : public FixupVisitor {
947 public:
948 template<typename... Args>
949 explicit FixupRootVisitor(Args... args) : FixupVisitor(args...) {}
950
951 ALWAYS_INLINE void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700952 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampea463b6a2016-08-12 21:53:32 -0700953 if (!root->IsNull()) {
954 VisitRoot(root);
955 }
956 }
957
958 ALWAYS_INLINE void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700959 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampea463b6a2016-08-12 21:53:32 -0700960 mirror::Object* ref = root->AsMirrorPtr();
961 mirror::Object* new_ref = ForwardObject(ref);
962 if (ref != new_ref) {
963 root->Assign(new_ref);
964 }
965 }
966 };
967
968 class FixupObjectVisitor : public FixupVisitor {
969 public:
970 template<typename... Args>
971 explicit FixupObjectVisitor(gc::accounting::ContinuousSpaceBitmap* visited,
972 const PointerSize pointer_size,
973 Args... args)
974 : FixupVisitor(args...),
975 pointer_size_(pointer_size),
976 visited_(visited) {}
977
978 // Fix up separately since we also need to fix up method entrypoints.
979 ALWAYS_INLINE void VisitRootIfNonNull(
980 mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const {}
981
982 ALWAYS_INLINE void VisitRoot(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED)
983 const {}
984
Mathieu Chartier31e88222016-10-14 18:43:19 -0700985 ALWAYS_INLINE void operator()(ObjPtr<mirror::Object> obj,
Andreas Gampea463b6a2016-08-12 21:53:32 -0700986 MemberOffset offset,
987 bool is_static ATTRIBUTE_UNUSED) const
988 NO_THREAD_SAFETY_ANALYSIS {
989 // There could be overlap between ranges, we must avoid visiting the same reference twice.
990 // Avoid the class field since we already fixed it up in FixupClassVisitor.
991 if (offset.Uint32Value() != mirror::Object::ClassOffset().Uint32Value()) {
992 // Space is not yet added to the heap, don't do a read barrier.
993 mirror::Object* ref = obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(
994 offset);
995 // Use SetFieldObjectWithoutWriteBarrier to avoid card marking since we are writing to the
996 // image.
997 obj->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(offset, ForwardObject(ref));
998 }
999 }
1000
1001 // Visit a pointer array and forward corresponding native data. Ignores pointer arrays in the
1002 // boot image. Uses the bitmap to ensure the same array is not visited multiple times.
1003 template <typename Visitor>
1004 void UpdatePointerArrayContents(mirror::PointerArray* array, const Visitor& visitor) const
1005 NO_THREAD_SAFETY_ANALYSIS {
1006 DCHECK(array != nullptr);
1007 DCHECK(visitor.IsInAppImage(array));
1008 // The bit for the array contents is different than the bit for the array. Since we may have
1009 // already visited the array as a long / int array from walking the bitmap without knowing it
1010 // was a pointer array.
1011 static_assert(kObjectAlignment == 8u, "array bit may be in another object");
1012 mirror::Object* const contents_bit = reinterpret_cast<mirror::Object*>(
1013 reinterpret_cast<uintptr_t>(array) + kObjectAlignment);
1014 // If the bit is not set then the contents have not yet been updated.
1015 if (!visited_->Test(contents_bit)) {
1016 array->Fixup<kVerifyNone, kWithoutReadBarrier>(array, pointer_size_, visitor);
1017 visited_->Set(contents_bit);
1018 }
1019 }
1020
1021 // java.lang.ref.Reference visitor.
Mathieu Chartier31e88222016-10-14 18:43:19 -07001022 void operator()(ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
1023 ObjPtr<mirror::Reference> ref) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001024 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Andreas Gampea463b6a2016-08-12 21:53:32 -07001025 mirror::Object* obj = ref->GetReferent<kWithoutReadBarrier>();
1026 ref->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
1027 mirror::Reference::ReferentOffset(),
1028 ForwardObject(obj));
1029 }
1030
Mathieu Chartier8c19d242017-03-06 12:35:10 -08001031 void operator()(mirror::Object* obj) const
1032 NO_THREAD_SAFETY_ANALYSIS {
Andreas Gampea463b6a2016-08-12 21:53:32 -07001033 if (visited_->Test(obj)) {
1034 // Already visited.
1035 return;
1036 }
1037 visited_->Set(obj);
1038
1039 // Handle class specially first since we need it to be updated to properly visit the rest of
1040 // the instance fields.
1041 {
1042 mirror::Class* klass = obj->GetClass<kVerifyNone, kWithoutReadBarrier>();
1043 DCHECK(klass != nullptr) << "Null class in image";
1044 // No AsClass since our fields aren't quite fixed up yet.
1045 mirror::Class* new_klass = down_cast<mirror::Class*>(ForwardObject(klass));
1046 if (klass != new_klass) {
1047 obj->SetClass<kVerifyNone>(new_klass);
1048 }
1049 if (new_klass != klass && IsInAppImage(new_klass)) {
1050 // Make sure the klass contents are fixed up since we depend on it to walk the fields.
1051 operator()(new_klass);
1052 }
1053 }
1054
Chang Xing4be3e9b2017-07-10 15:03:22 -07001055 if (obj->IsClass()) {
1056 mirror::Class* klass = obj->AsClass<kVerifyNone, kWithoutReadBarrier>();
1057 // Fixup super class before visiting instance fields which require
1058 // information from their super class to calculate offsets.
Chang Xing6f54cf22017-07-14 09:59:01 -07001059 mirror::Class* super_class = klass->GetSuperClass<kVerifyNone, kWithoutReadBarrier>();
Chang Xing4be3e9b2017-07-10 15:03:22 -07001060 if (super_class != nullptr) {
1061 mirror::Class* new_super_class = down_cast<mirror::Class*>(ForwardObject(super_class));
1062 if (new_super_class != super_class && IsInAppImage(new_super_class)) {
1063 // Recursively fix all dependencies.
1064 operator()(new_super_class);
1065 }
1066 }
1067 }
1068
Andreas Gampea463b6a2016-08-12 21:53:32 -07001069 obj->VisitReferences</*visit native roots*/false, kVerifyNone, kWithoutReadBarrier>(
1070 *this,
1071 *this);
1072 // Note that this code relies on no circular dependencies.
1073 // We want to use our own class loader and not the one in the image.
1074 if (obj->IsClass<kVerifyNone, kWithoutReadBarrier>()) {
1075 mirror::Class* as_klass = obj->AsClass<kVerifyNone, kWithoutReadBarrier>();
1076 FixupObjectAdapter visitor(boot_image_, boot_oat_, app_image_, app_oat_);
1077 as_klass->FixupNativePointers<kVerifyNone, kWithoutReadBarrier>(as_klass,
1078 pointer_size_,
1079 visitor);
1080 // Deal with the pointer arrays. Use the helper function since multiple classes can reference
1081 // the same arrays.
1082 mirror::PointerArray* const vtable = as_klass->GetVTable<kVerifyNone, kWithoutReadBarrier>();
1083 if (vtable != nullptr && IsInAppImage(vtable)) {
1084 operator()(vtable);
1085 UpdatePointerArrayContents(vtable, visitor);
1086 }
1087 mirror::IfTable* iftable = as_klass->GetIfTable<kVerifyNone, kWithoutReadBarrier>();
1088 // Ensure iftable arrays are fixed up since we need GetMethodArray to return the valid
1089 // contents.
Mathieu Chartier6beced42016-11-15 15:51:31 -08001090 if (IsInAppImage(iftable)) {
Andreas Gampea463b6a2016-08-12 21:53:32 -07001091 operator()(iftable);
1092 for (int32_t i = 0, count = iftable->Count(); i < count; ++i) {
1093 if (iftable->GetMethodArrayCount<kVerifyNone, kWithoutReadBarrier>(i) > 0) {
1094 mirror::PointerArray* methods =
1095 iftable->GetMethodArray<kVerifyNone, kWithoutReadBarrier>(i);
1096 if (visitor.IsInAppImage(methods)) {
1097 operator()(methods);
1098 DCHECK(methods != nullptr);
1099 UpdatePointerArrayContents(methods, visitor);
1100 }
Mathieu Chartier92ec5942016-04-11 12:03:48 -07001101 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001102 }
1103 }
1104 }
1105 }
Mathieu Chartier91edc622016-02-16 17:16:01 -08001106
Andreas Gampea463b6a2016-08-12 21:53:32 -07001107 private:
1108 const PointerSize pointer_size_;
1109 gc::accounting::ContinuousSpaceBitmap* const visited_;
1110 };
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001111
Andreas Gampea463b6a2016-08-12 21:53:32 -07001112 class ForwardObjectAdapter {
1113 public:
1114 ALWAYS_INLINE explicit ForwardObjectAdapter(const FixupVisitor* visitor) : visitor_(visitor) {}
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001115
Andreas Gampea463b6a2016-08-12 21:53:32 -07001116 template <typename T>
1117 ALWAYS_INLINE T* operator()(T* src) const {
1118 return visitor_->ForwardObject(src);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001119 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001120
Andreas Gampea463b6a2016-08-12 21:53:32 -07001121 private:
1122 const FixupVisitor* const visitor_;
1123 };
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001124
Andreas Gampea463b6a2016-08-12 21:53:32 -07001125 class ForwardCodeAdapter {
1126 public:
1127 ALWAYS_INLINE explicit ForwardCodeAdapter(const FixupVisitor* visitor)
1128 : visitor_(visitor) {}
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001129
Andreas Gampea463b6a2016-08-12 21:53:32 -07001130 template <typename T>
1131 ALWAYS_INLINE T* operator()(T* src) const {
1132 return visitor_->ForwardCode(src);
1133 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001134
Andreas Gampea463b6a2016-08-12 21:53:32 -07001135 private:
1136 const FixupVisitor* const visitor_;
1137 };
1138
1139 class FixupArtMethodVisitor : public FixupVisitor, public ArtMethodVisitor {
1140 public:
1141 template<typename... Args>
1142 explicit FixupArtMethodVisitor(bool fixup_heap_objects, PointerSize pointer_size, Args... args)
1143 : FixupVisitor(args...),
1144 fixup_heap_objects_(fixup_heap_objects),
1145 pointer_size_(pointer_size) {}
1146
1147 virtual void Visit(ArtMethod* method) NO_THREAD_SAFETY_ANALYSIS {
1148 // TODO: Separate visitor for runtime vs normal methods.
1149 if (UNLIKELY(method->IsRuntimeMethod())) {
1150 ImtConflictTable* table = method->GetImtConflictTable(pointer_size_);
1151 if (table != nullptr) {
1152 ImtConflictTable* new_table = ForwardObject(table);
1153 if (table != new_table) {
1154 method->SetImtConflictTable(new_table, pointer_size_);
1155 }
1156 }
1157 const void* old_code = method->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size_);
1158 const void* new_code = ForwardCode(old_code);
1159 if (old_code != new_code) {
1160 method->SetEntryPointFromQuickCompiledCodePtrSize(new_code, pointer_size_);
1161 }
1162 } else {
1163 if (fixup_heap_objects_) {
Vladimir Marko5122e6b2017-08-17 16:10:09 +01001164 method->UpdateObjectsForImageRelocation(ForwardObjectAdapter(this));
Andreas Gampea463b6a2016-08-12 21:53:32 -07001165 }
Vladimir Markoc945e0d2018-07-18 17:26:45 +01001166 method->UpdateEntrypoints(ForwardCodeAdapter(this), pointer_size_);
Andreas Gampea463b6a2016-08-12 21:53:32 -07001167 }
1168 }
1169
1170 private:
1171 const bool fixup_heap_objects_;
1172 const PointerSize pointer_size_;
1173 };
1174
1175 class FixupArtFieldVisitor : public FixupVisitor, public ArtFieldVisitor {
1176 public:
1177 template<typename... Args>
1178 explicit FixupArtFieldVisitor(Args... args) : FixupVisitor(args...) {}
1179
1180 virtual void Visit(ArtField* field) NO_THREAD_SAFETY_ANALYSIS {
1181 field->UpdateObjects(ForwardObjectAdapter(this));
1182 }
1183 };
1184
1185 // Relocate an image space mapped at target_base which possibly used to be at a different base
1186 // address. Only needs a single image space, not one for both source and destination.
1187 // In place means modifying a single ImageSpace in place rather than relocating from one ImageSpace
1188 // to another.
1189 static bool RelocateInPlace(ImageHeader& image_header,
1190 uint8_t* target_base,
1191 accounting::ContinuousSpaceBitmap* bitmap,
1192 const OatFile* app_oat_file,
1193 std::string* error_msg) {
1194 DCHECK(error_msg != nullptr);
1195 if (!image_header.IsPic()) {
1196 if (image_header.GetImageBegin() == target_base) {
1197 return true;
1198 }
1199 *error_msg = StringPrintf("Cannot relocate non-pic image for oat file %s",
1200 (app_oat_file != nullptr) ? app_oat_file->GetLocation().c_str() : "");
1201 return false;
1202 }
1203 // Set up sections.
1204 uint32_t boot_image_begin = 0;
1205 uint32_t boot_image_end = 0;
1206 uint32_t boot_oat_begin = 0;
1207 uint32_t boot_oat_end = 0;
1208 const PointerSize pointer_size = image_header.GetPointerSize();
1209 gc::Heap* const heap = Runtime::Current()->GetHeap();
1210 heap->GetBootImagesSize(&boot_image_begin, &boot_image_end, &boot_oat_begin, &boot_oat_end);
1211 if (boot_image_begin == boot_image_end) {
1212 *error_msg = "Can not relocate app image without boot image space";
1213 return false;
1214 }
1215 if (boot_oat_begin == boot_oat_end) {
1216 *error_msg = "Can not relocate app image without boot oat file";
1217 return false;
1218 }
1219 const uint32_t boot_image_size = boot_image_end - boot_image_begin;
1220 const uint32_t boot_oat_size = boot_oat_end - boot_oat_begin;
1221 const uint32_t image_header_boot_image_size = image_header.GetBootImageSize();
1222 const uint32_t image_header_boot_oat_size = image_header.GetBootOatSize();
1223 if (boot_image_size != image_header_boot_image_size) {
1224 *error_msg = StringPrintf("Boot image size %" PRIu64 " does not match expected size %"
1225 PRIu64,
1226 static_cast<uint64_t>(boot_image_size),
1227 static_cast<uint64_t>(image_header_boot_image_size));
1228 return false;
1229 }
1230 if (boot_oat_size != image_header_boot_oat_size) {
1231 *error_msg = StringPrintf("Boot oat size %" PRIu64 " does not match expected size %"
1232 PRIu64,
1233 static_cast<uint64_t>(boot_oat_size),
1234 static_cast<uint64_t>(image_header_boot_oat_size));
1235 return false;
1236 }
1237 TimingLogger logger(__FUNCTION__, true, false);
1238 RelocationRange boot_image(image_header.GetBootImageBegin(),
1239 boot_image_begin,
1240 boot_image_size);
1241 RelocationRange boot_oat(image_header.GetBootOatBegin(),
1242 boot_oat_begin,
1243 boot_oat_size);
1244 RelocationRange app_image(reinterpret_cast<uintptr_t>(image_header.GetImageBegin()),
1245 reinterpret_cast<uintptr_t>(target_base),
1246 image_header.GetImageSize());
1247 // Use the oat data section since this is where the OatFile::Begin is.
1248 RelocationRange app_oat(reinterpret_cast<uintptr_t>(image_header.GetOatDataBegin()),
1249 // Not necessarily in low 4GB.
1250 reinterpret_cast<uintptr_t>(app_oat_file->Begin()),
1251 image_header.GetOatDataEnd() - image_header.GetOatDataBegin());
1252 VLOG(image) << "App image " << app_image;
1253 VLOG(image) << "App oat " << app_oat;
1254 VLOG(image) << "Boot image " << boot_image;
1255 VLOG(image) << "Boot oat " << boot_oat;
1256 // True if we need to fixup any heap pointers, otherwise only code pointers.
1257 const bool fixup_image = boot_image.Delta() != 0 || app_image.Delta() != 0;
1258 const bool fixup_code = boot_oat.Delta() != 0 || app_oat.Delta() != 0;
1259 if (!fixup_image && !fixup_code) {
1260 // Nothing to fix up.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001261 return true;
1262 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07001263 ScopedDebugDisallowReadBarriers sddrb(Thread::Current());
1264 // Need to update the image to be at the target base.
Vladimir Markocd87c3e2017-09-05 13:11:57 +01001265 const ImageSection& objects_section = image_header.GetObjectsSection();
Andreas Gampea463b6a2016-08-12 21:53:32 -07001266 uintptr_t objects_begin = reinterpret_cast<uintptr_t>(target_base + objects_section.Offset());
1267 uintptr_t objects_end = reinterpret_cast<uintptr_t>(target_base + objects_section.End());
1268 FixupObjectAdapter fixup_adapter(boot_image, boot_oat, app_image, app_oat);
1269 if (fixup_image) {
1270 // Two pass approach, fix up all classes first, then fix up non class-objects.
1271 // The visited bitmap is used to ensure that pointer arrays are not forwarded twice.
1272 std::unique_ptr<gc::accounting::ContinuousSpaceBitmap> visited_bitmap(
1273 gc::accounting::ContinuousSpaceBitmap::Create("Relocate bitmap",
1274 target_base,
1275 image_header.GetImageSize()));
1276 FixupObjectVisitor fixup_object_visitor(visited_bitmap.get(),
1277 pointer_size,
1278 boot_image,
1279 boot_oat,
1280 app_image,
1281 app_oat);
1282 TimingLogger::ScopedTiming timing("Fixup classes", &logger);
1283 // Fixup objects may read fields in the boot image, use the mutator lock here for sanity. Though
1284 // its probably not required.
1285 ScopedObjectAccess soa(Thread::Current());
1286 timing.NewTiming("Fixup objects");
1287 bitmap->VisitMarkedRange(objects_begin, objects_end, fixup_object_visitor);
1288 // Fixup image roots.
1289 CHECK(app_image.InSource(reinterpret_cast<uintptr_t>(
Vladimir Markoc13fbd82018-06-04 16:16:28 +01001290 image_header.GetImageRoots<kWithoutReadBarrier>().Ptr())));
Andreas Gampea463b6a2016-08-12 21:53:32 -07001291 image_header.RelocateImageObjects(app_image.Delta());
1292 CHECK_EQ(image_header.GetImageBegin(), target_base);
1293 // Fix up dex cache DexFile pointers.
1294 auto* dex_caches = image_header.GetImageRoot<kWithoutReadBarrier>(ImageHeader::kDexCaches)->
1295 AsObjectArray<mirror::DexCache, kVerifyNone, kWithoutReadBarrier>();
1296 for (int32_t i = 0, count = dex_caches->GetLength(); i < count; ++i) {
1297 mirror::DexCache* dex_cache = dex_caches->Get<kVerifyNone, kWithoutReadBarrier>(i);
1298 // Fix up dex cache pointers.
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07001299 mirror::StringDexCacheType* strings = dex_cache->GetStrings();
Andreas Gampea463b6a2016-08-12 21:53:32 -07001300 if (strings != nullptr) {
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07001301 mirror::StringDexCacheType* new_strings = fixup_adapter.ForwardObject(strings);
Andreas Gampea463b6a2016-08-12 21:53:32 -07001302 if (strings != new_strings) {
1303 dex_cache->SetStrings(new_strings);
1304 }
1305 dex_cache->FixupStrings<kWithoutReadBarrier>(new_strings, fixup_adapter);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001306 }
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001307 mirror::TypeDexCacheType* types = dex_cache->GetResolvedTypes();
Andreas Gampea463b6a2016-08-12 21:53:32 -07001308 if (types != nullptr) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001309 mirror::TypeDexCacheType* new_types = fixup_adapter.ForwardObject(types);
Andreas Gampea463b6a2016-08-12 21:53:32 -07001310 if (types != new_types) {
1311 dex_cache->SetResolvedTypes(new_types);
1312 }
1313 dex_cache->FixupResolvedTypes<kWithoutReadBarrier>(new_types, fixup_adapter);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001314 }
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001315 mirror::MethodDexCacheType* methods = dex_cache->GetResolvedMethods();
Andreas Gampea463b6a2016-08-12 21:53:32 -07001316 if (methods != nullptr) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001317 mirror::MethodDexCacheType* new_methods = fixup_adapter.ForwardObject(methods);
Andreas Gampea463b6a2016-08-12 21:53:32 -07001318 if (methods != new_methods) {
1319 dex_cache->SetResolvedMethods(new_methods);
1320 }
1321 for (size_t j = 0, num = dex_cache->NumResolvedMethods(); j != num; ++j) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001322 auto pair = mirror::DexCache::GetNativePairPtrSize(new_methods, j, pointer_size);
1323 ArtMethod* orig = pair.object;
Andreas Gampea463b6a2016-08-12 21:53:32 -07001324 ArtMethod* copy = fixup_adapter.ForwardObject(orig);
1325 if (orig != copy) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001326 pair.object = copy;
1327 mirror::DexCache::SetNativePairPtrSize(new_methods, j, pair, pointer_size);
Andreas Gampea463b6a2016-08-12 21:53:32 -07001328 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001329 }
1330 }
Vladimir Markof44d36c2017-03-14 14:18:46 +00001331 mirror::FieldDexCacheType* fields = dex_cache->GetResolvedFields();
Andreas Gampea463b6a2016-08-12 21:53:32 -07001332 if (fields != nullptr) {
Vladimir Markof44d36c2017-03-14 14:18:46 +00001333 mirror::FieldDexCacheType* new_fields = fixup_adapter.ForwardObject(fields);
Andreas Gampea463b6a2016-08-12 21:53:32 -07001334 if (fields != new_fields) {
1335 dex_cache->SetResolvedFields(new_fields);
1336 }
1337 for (size_t j = 0, num = dex_cache->NumResolvedFields(); j != num; ++j) {
Vladimir Markof44d36c2017-03-14 14:18:46 +00001338 mirror::FieldDexCachePair orig =
1339 mirror::DexCache::GetNativePairPtrSize(new_fields, j, pointer_size);
1340 mirror::FieldDexCachePair copy(fixup_adapter.ForwardObject(orig.object), orig.index);
1341 if (orig.object != copy.object) {
1342 mirror::DexCache::SetNativePairPtrSize(new_fields, j, copy, pointer_size);
Andreas Gampea463b6a2016-08-12 21:53:32 -07001343 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001344 }
1345 }
Narayan Kamath7fe56582016-10-14 18:49:12 +01001346
1347 mirror::MethodTypeDexCacheType* method_types = dex_cache->GetResolvedMethodTypes();
1348 if (method_types != nullptr) {
1349 mirror::MethodTypeDexCacheType* new_method_types =
1350 fixup_adapter.ForwardObject(method_types);
1351 if (method_types != new_method_types) {
1352 dex_cache->SetResolvedMethodTypes(new_method_types);
1353 }
1354 dex_cache->FixupResolvedMethodTypes<kWithoutReadBarrier>(new_method_types, fixup_adapter);
1355 }
Orion Hodsonc069a302017-01-18 09:23:12 +00001356 GcRoot<mirror::CallSite>* call_sites = dex_cache->GetResolvedCallSites();
1357 if (call_sites != nullptr) {
1358 GcRoot<mirror::CallSite>* new_call_sites = fixup_adapter.ForwardObject(call_sites);
1359 if (call_sites != new_call_sites) {
1360 dex_cache->SetResolvedCallSites(new_call_sites);
1361 }
1362 dex_cache->FixupResolvedCallSites<kWithoutReadBarrier>(new_call_sites, fixup_adapter);
1363 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001364 }
1365 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001366 {
1367 // Only touches objects in the app image, no need for mutator lock.
Andreas Gampea463b6a2016-08-12 21:53:32 -07001368 TimingLogger::ScopedTiming timing("Fixup methods", &logger);
1369 FixupArtMethodVisitor method_visitor(fixup_image,
1370 pointer_size,
1371 boot_image,
1372 boot_oat,
1373 app_image,
1374 app_oat);
1375 image_header.VisitPackedArtMethods(&method_visitor, target_base, pointer_size);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001376 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07001377 if (fixup_image) {
1378 {
1379 // Only touches objects in the app image, no need for mutator lock.
1380 TimingLogger::ScopedTiming timing("Fixup fields", &logger);
1381 FixupArtFieldVisitor field_visitor(boot_image, boot_oat, app_image, app_oat);
1382 image_header.VisitPackedArtFields(&field_visitor, target_base);
1383 }
1384 {
1385 TimingLogger::ScopedTiming timing("Fixup imt", &logger);
1386 image_header.VisitPackedImTables(fixup_adapter, target_base, pointer_size);
1387 }
1388 {
1389 TimingLogger::ScopedTiming timing("Fixup conflict tables", &logger);
1390 image_header.VisitPackedImtConflictTables(fixup_adapter, target_base, pointer_size);
1391 }
1392 // In the app image case, the image methods are actually in the boot image.
1393 image_header.RelocateImageMethods(boot_image.Delta());
Vladimir Markocd87c3e2017-09-05 13:11:57 +01001394 const auto& class_table_section = image_header.GetClassTableSection();
Andreas Gampea463b6a2016-08-12 21:53:32 -07001395 if (class_table_section.Size() > 0u) {
1396 // Note that we require that ReadFromMemory does not make an internal copy of the elements.
1397 // This also relies on visit roots not doing any verification which could fail after we update
1398 // the roots to be the image addresses.
1399 ScopedObjectAccess soa(Thread::Current());
1400 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
1401 ClassTable temp_table;
1402 temp_table.ReadFromMemory(target_base + class_table_section.Offset());
1403 FixupRootVisitor root_visitor(boot_image, boot_oat, app_image, app_oat);
1404 temp_table.VisitRoots(root_visitor);
1405 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001406 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07001407 if (VLOG_IS_ON(image)) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07001408 logger.Dump(LOG_STREAM(INFO));
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001409 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07001410 return true;
Andreas Gampe7fa55782016-06-15 17:45:01 -07001411 }
1412
Andreas Gampea463b6a2016-08-12 21:53:32 -07001413 static std::unique_ptr<OatFile> OpenOatFile(const ImageSpace& image,
1414 const char* image_path,
1415 std::string* error_msg) {
1416 const ImageHeader& image_header = image.GetImageHeader();
1417 std::string oat_filename = ImageHeader::GetOatLocationFromImageLocation(image_path);
Andreas Gampe7fa55782016-06-15 17:45:01 -07001418
Andreas Gampea463b6a2016-08-12 21:53:32 -07001419 CHECK(image_header.GetOatDataBegin() != nullptr);
1420
Nicolas Geoffray30025092018-04-19 14:43:29 +01001421 std::unique_ptr<OatFile> oat_file(OatFile::Open(/* zip_fd */ -1,
1422 oat_filename,
Andreas Gampea463b6a2016-08-12 21:53:32 -07001423 oat_filename,
1424 image_header.GetOatDataBegin(),
1425 image_header.GetOatFileBegin(),
1426 !Runtime::Current()->IsAotCompiler(),
1427 /*low_4gb*/false,
1428 nullptr,
1429 error_msg));
1430 if (oat_file == nullptr) {
1431 *error_msg = StringPrintf("Failed to open oat file '%s' referenced from image %s: %s",
1432 oat_filename.c_str(),
1433 image.GetName(),
1434 error_msg->c_str());
Andreas Gampe7fa55782016-06-15 17:45:01 -07001435 return nullptr;
1436 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07001437 uint32_t oat_checksum = oat_file->GetOatHeader().GetChecksum();
1438 uint32_t image_oat_checksum = image_header.GetOatChecksum();
Mathieu Chartier9ff84602016-01-29 12:22:17 -08001439 if (oat_checksum != image_oat_checksum) {
Andreas Gampea463b6a2016-08-12 21:53:32 -07001440 *error_msg = StringPrintf("Failed to match oat file checksum 0x%x to expected oat checksum 0x%x"
1441 " in image %s",
Mathieu Chartier9ff84602016-01-29 12:22:17 -08001442 oat_checksum,
1443 image_oat_checksum,
Andreas Gampea463b6a2016-08-12 21:53:32 -07001444 image.GetName());
Mathieu Chartier9ff84602016-01-29 12:22:17 -08001445 return nullptr;
1446 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07001447 int32_t image_patch_delta = image_header.GetPatchDelta();
1448 int32_t oat_patch_delta = oat_file->GetOatHeader().GetImagePatchDelta();
1449 if (oat_patch_delta != image_patch_delta && !image_header.CompilePic()) {
1450 // We should have already relocated by this point. Bail out.
1451 *error_msg = StringPrintf("Failed to match oat file patch delta %d to expected patch delta %d "
1452 "in image %s",
1453 oat_patch_delta,
1454 image_patch_delta,
1455 image.GetName());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001456 return nullptr;
1457 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07001458
1459 return oat_file;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001460 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07001461};
Hiroshi Yamauchibd0fb612014-05-20 13:46:00 -07001462
Andreas Gampea463b6a2016-08-12 21:53:32 -07001463static constexpr uint64_t kLowSpaceValue = 50 * MB;
1464static constexpr uint64_t kTmpFsSentinelValue = 384 * MB;
1465
1466// Read the free space of the cache partition and make a decision whether to keep the generated
1467// image. This is to try to mitigate situations where the system might run out of space later.
1468static bool CheckSpace(const std::string& cache_filename, std::string* error_msg) {
1469 // Using statvfs vs statvfs64 because of b/18207376, and it is enough for all practical purposes.
1470 struct statvfs buf;
1471
1472 int res = TEMP_FAILURE_RETRY(statvfs(cache_filename.c_str(), &buf));
1473 if (res != 0) {
1474 // Could not stat. Conservatively tell the system to delete the image.
1475 *error_msg = "Could not stat the filesystem, assuming low-memory situation.";
1476 return false;
Nicolas Geoffray1bc977c2016-01-23 14:15:49 +00001477 }
Nicolas Geoffray1bc977c2016-01-23 14:15:49 +00001478
Andreas Gampea463b6a2016-08-12 21:53:32 -07001479 uint64_t fs_overall_size = buf.f_bsize * static_cast<uint64_t>(buf.f_blocks);
1480 // Zygote is privileged, but other things are not. Use bavail.
1481 uint64_t fs_free_size = buf.f_bsize * static_cast<uint64_t>(buf.f_bavail);
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001482
Andreas Gampea463b6a2016-08-12 21:53:32 -07001483 // Take the overall size as an indicator for a tmpfs, which is being used for the decryption
1484 // environment. We do not want to fail quickening the boot image there, as it is beneficial
1485 // for time-to-UI.
1486 if (fs_overall_size > kTmpFsSentinelValue) {
1487 if (fs_free_size < kLowSpaceValue) {
1488 *error_msg = StringPrintf("Low-memory situation: only %4.2f megabytes available, need at "
1489 "least %" PRIu64 ".",
1490 static_cast<double>(fs_free_size) / MB,
1491 kLowSpaceValue / MB);
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001492 return false;
1493 }
1494 }
1495 return true;
1496}
1497
Andreas Gampea463b6a2016-08-12 21:53:32 -07001498std::unique_ptr<ImageSpace> ImageSpace::CreateBootImage(const char* image_location,
1499 const InstructionSet image_isa,
1500 bool secondary_image,
1501 std::string* error_msg) {
1502 ScopedTrace trace(__FUNCTION__);
1503
1504 // Step 0: Extra zygote work.
1505
1506 // Step 0.a: If we're the zygote, mark boot.
1507 const bool is_zygote = Runtime::Current()->IsZygote();
Robert Sesekbfa1f8d2016-08-15 15:21:09 -04001508 if (is_zygote && !secondary_image && CanWriteToDalvikCache(image_isa)) {
Andreas Gampea463b6a2016-08-12 21:53:32 -07001509 MarkZygoteStart(image_isa, Runtime::Current()->GetZygoteMaxFailedBoots());
1510 }
1511
1512 // Step 0.b: If we're the zygote, check for free space, and prune the cache preemptively,
1513 // if necessary. While the runtime may be fine (it is pretty tolerant to
1514 // out-of-disk-space situations), other parts of the platform are not.
1515 //
1516 // The advantage of doing this proactively is that the later steps are simplified,
1517 // i.e., we do not need to code retries.
1518 std::string system_filename;
1519 bool has_system = false;
1520 std::string cache_filename;
1521 bool has_cache = false;
1522 bool dalvik_cache_exists = false;
1523 bool is_global_cache = true;
1524 std::string dalvik_cache;
1525 bool found_image = FindImageFilenameImpl(image_location,
1526 image_isa,
1527 &has_system,
1528 &system_filename,
1529 &dalvik_cache_exists,
1530 &dalvik_cache,
1531 &is_global_cache,
1532 &has_cache,
1533 &cache_filename);
1534
Andreas Gampe6e74abb2018-03-01 17:33:19 -08001535 bool dex2oat_enabled = Runtime::Current()->IsImageDex2OatEnabled();
1536
1537 if (is_zygote && dalvik_cache_exists && !secondary_image) {
1538 // Extra checks for the zygote. These only apply when loading the first image, explained below.
Andreas Gampea463b6a2016-08-12 21:53:32 -07001539 DCHECK(!dalvik_cache.empty());
1540 std::string local_error_msg;
Chris Morine5fac732018-02-05 14:27:40 -08001541 // All secondary images are verified when the primary image is verified.
Andreas Gampe6e74abb2018-03-01 17:33:19 -08001542 bool verified = VerifyImage(image_location, dalvik_cache.c_str(), image_isa, &local_error_msg);
1543 // If we prune for space at a secondary image, we may end up in a crash loop with the _exit
1544 // path.
1545 bool check_space = CheckSpace(dalvik_cache, &local_error_msg);
1546 if (!verified || !check_space) {
1547 // Note: it is important to only prune for space on the primary image, or we will hit the
1548 // restart path.
Andreas Gampea463b6a2016-08-12 21:53:32 -07001549 LOG(WARNING) << local_error_msg << " Preemptively pruning the dalvik cache.";
1550 PruneDalvikCache(image_isa);
1551
1552 // Re-evaluate the image.
1553 found_image = FindImageFilenameImpl(image_location,
1554 image_isa,
1555 &has_system,
1556 &system_filename,
1557 &dalvik_cache_exists,
1558 &dalvik_cache,
1559 &is_global_cache,
1560 &has_cache,
1561 &cache_filename);
1562 }
Andreas Gampe6e74abb2018-03-01 17:33:19 -08001563 if (!check_space) {
1564 // Disable compilation/patching - we do not want to fill up the space again.
1565 dex2oat_enabled = false;
1566 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07001567 }
1568
1569 // Collect all the errors.
1570 std::vector<std::string> error_msgs;
1571
1572 // Step 1: Check if we have an existing and relocated image.
1573
1574 // Step 1.a: Have files in system and cache. Then they need to match.
1575 if (found_image && has_system && has_cache) {
1576 std::string local_error_msg;
1577 // Check that the files are matching.
1578 if (ChecksumsMatch(system_filename.c_str(), cache_filename.c_str(), &local_error_msg)) {
1579 std::unique_ptr<ImageSpace> relocated_space =
1580 ImageSpaceLoader::Load(image_location,
1581 cache_filename,
1582 is_zygote,
1583 is_global_cache,
Andreas Gampe44c8ed62016-08-19 16:43:00 -07001584 /* validate_oat_file */ false,
Andreas Gampea463b6a2016-08-12 21:53:32 -07001585 &local_error_msg);
1586 if (relocated_space != nullptr) {
1587 return relocated_space;
1588 }
1589 }
1590 error_msgs.push_back(local_error_msg);
1591 }
1592
1593 // Step 1.b: Only have a cache file.
1594 if (found_image && !has_system && has_cache) {
1595 std::string local_error_msg;
1596 std::unique_ptr<ImageSpace> cache_space =
1597 ImageSpaceLoader::Load(image_location,
1598 cache_filename,
1599 is_zygote,
1600 is_global_cache,
Andreas Gampe44c8ed62016-08-19 16:43:00 -07001601 /* validate_oat_file */ true,
Andreas Gampea463b6a2016-08-12 21:53:32 -07001602 &local_error_msg);
1603 if (cache_space != nullptr) {
1604 return cache_space;
1605 }
1606 error_msgs.push_back(local_error_msg);
1607 }
1608
1609 // Step 2: We have an existing image in /system.
1610
1611 // Step 2.a: We are not required to relocate it. Then we can use it directly.
1612 bool relocate = Runtime::Current()->ShouldRelocate();
1613
1614 if (found_image && has_system && !relocate) {
1615 std::string local_error_msg;
1616 std::unique_ptr<ImageSpace> system_space =
1617 ImageSpaceLoader::Load(image_location,
1618 system_filename,
1619 is_zygote,
1620 is_global_cache,
Andreas Gampe44c8ed62016-08-19 16:43:00 -07001621 /* validate_oat_file */ false,
Andreas Gampea463b6a2016-08-12 21:53:32 -07001622 &local_error_msg);
1623 if (system_space != nullptr) {
1624 return system_space;
1625 }
1626 error_msgs.push_back(local_error_msg);
1627 }
1628
1629 // Step 2.b: We require a relocated image. Then we must patch it. This step fails if this is a
1630 // secondary image.
1631 if (found_image && has_system && relocate) {
1632 std::string local_error_msg;
Andreas Gampe6e74abb2018-03-01 17:33:19 -08001633 if (!dex2oat_enabled) {
Andreas Gampea463b6a2016-08-12 21:53:32 -07001634 local_error_msg = "Patching disabled.";
1635 } else if (secondary_image) {
Andreas Gampe8d8a0052017-12-12 12:03:04 -08001636 // We really want a working image. Prune and restart.
1637 PruneDalvikCache(image_isa);
1638 _exit(1);
Robert Sesekbfa1f8d2016-08-15 15:21:09 -04001639 } else if (ImageCreationAllowed(is_global_cache, image_isa, &local_error_msg)) {
Andreas Gampea463b6a2016-08-12 21:53:32 -07001640 bool patch_success =
Chris Morin88c6d262018-02-13 15:26:21 -08001641 RelocateImage(image_location, dalvik_cache.c_str(), image_isa, &local_error_msg);
Andreas Gampea463b6a2016-08-12 21:53:32 -07001642 if (patch_success) {
1643 std::unique_ptr<ImageSpace> patched_space =
1644 ImageSpaceLoader::Load(image_location,
1645 cache_filename,
1646 is_zygote,
1647 is_global_cache,
Andreas Gampe44c8ed62016-08-19 16:43:00 -07001648 /* validate_oat_file */ false,
Andreas Gampea463b6a2016-08-12 21:53:32 -07001649 &local_error_msg);
1650 if (patched_space != nullptr) {
1651 return patched_space;
1652 }
1653 }
1654 }
1655 error_msgs.push_back(StringPrintf("Cannot relocate image %s to %s: %s",
1656 image_location,
1657 cache_filename.c_str(),
1658 local_error_msg.c_str()));
1659 }
1660
1661 // Step 3: We do not have an existing image in /system, so generate an image into the dalvik
1662 // cache. This step fails if this is a secondary image.
1663 if (!has_system) {
1664 std::string local_error_msg;
Andreas Gampe6e74abb2018-03-01 17:33:19 -08001665 if (!dex2oat_enabled) {
Andreas Gampea463b6a2016-08-12 21:53:32 -07001666 local_error_msg = "Image compilation disabled.";
1667 } else if (secondary_image) {
1668 local_error_msg = "Cannot compile a secondary image.";
Robert Sesekbfa1f8d2016-08-15 15:21:09 -04001669 } else if (ImageCreationAllowed(is_global_cache, image_isa, &local_error_msg)) {
Andreas Gampea463b6a2016-08-12 21:53:32 -07001670 bool compilation_success = GenerateImage(cache_filename, image_isa, &local_error_msg);
1671 if (compilation_success) {
1672 std::unique_ptr<ImageSpace> compiled_space =
1673 ImageSpaceLoader::Load(image_location,
1674 cache_filename,
1675 is_zygote,
1676 is_global_cache,
Andreas Gampe44c8ed62016-08-19 16:43:00 -07001677 /* validate_oat_file */ false,
Andreas Gampea463b6a2016-08-12 21:53:32 -07001678 &local_error_msg);
1679 if (compiled_space != nullptr) {
1680 return compiled_space;
1681 }
1682 }
1683 }
1684 error_msgs.push_back(StringPrintf("Cannot compile image to %s: %s",
1685 cache_filename.c_str(),
1686 local_error_msg.c_str()));
1687 }
1688
1689 // We failed. Prune the cache the free up space, create a compound error message and return no
1690 // image.
1691 PruneDalvikCache(image_isa);
1692
1693 std::ostringstream oss;
1694 bool first = true;
Andreas Gampe4c481a42016-11-03 08:21:59 -07001695 for (const auto& msg : error_msgs) {
Andreas Gampea463b6a2016-08-12 21:53:32 -07001696 if (!first) {
1697 oss << "\n ";
1698 }
1699 oss << msg;
1700 }
1701 *error_msg = oss.str();
1702
1703 return nullptr;
1704}
1705
Andreas Gampe2bd84282016-12-05 12:37:36 -08001706bool ImageSpace::LoadBootImage(const std::string& image_file_name,
1707 const InstructionSet image_instruction_set,
1708 std::vector<space::ImageSpace*>* boot_image_spaces,
1709 uint8_t** oat_file_end) {
1710 DCHECK(boot_image_spaces != nullptr);
1711 DCHECK(boot_image_spaces->empty());
1712 DCHECK(oat_file_end != nullptr);
1713 DCHECK_NE(image_instruction_set, InstructionSet::kNone);
1714
1715 if (image_file_name.empty()) {
1716 return false;
1717 }
1718
1719 // For code reuse, handle this like a work queue.
1720 std::vector<std::string> image_file_names;
1721 image_file_names.push_back(image_file_name);
1722
1723 bool error = false;
1724 uint8_t* oat_file_end_tmp = *oat_file_end;
1725
1726 for (size_t index = 0; index < image_file_names.size(); ++index) {
1727 std::string& image_name = image_file_names[index];
1728 std::string error_msg;
1729 std::unique_ptr<space::ImageSpace> boot_image_space_uptr = CreateBootImage(
1730 image_name.c_str(),
1731 image_instruction_set,
1732 index > 0,
1733 &error_msg);
1734 if (boot_image_space_uptr != nullptr) {
1735 space::ImageSpace* boot_image_space = boot_image_space_uptr.release();
1736 boot_image_spaces->push_back(boot_image_space);
1737 // Oat files referenced by image files immediately follow them in memory, ensure alloc space
1738 // isn't going to get in the middle
1739 uint8_t* oat_file_end_addr = boot_image_space->GetImageHeader().GetOatFileEnd();
1740 CHECK_GT(oat_file_end_addr, boot_image_space->End());
1741 oat_file_end_tmp = AlignUp(oat_file_end_addr, kPageSize);
1742
1743 if (index == 0) {
1744 // If this was the first space, check whether there are more images to load.
1745 const OatFile* boot_oat_file = boot_image_space->GetOatFile();
1746 if (boot_oat_file == nullptr) {
1747 continue;
1748 }
1749
1750 const OatHeader& boot_oat_header = boot_oat_file->GetOatHeader();
1751 const char* boot_classpath =
1752 boot_oat_header.GetStoreValueByKey(OatHeader::kBootClassPathKey);
1753 if (boot_classpath == nullptr) {
1754 continue;
1755 }
1756
1757 ExtractMultiImageLocations(image_file_name, boot_classpath, &image_file_names);
1758 }
1759 } else {
1760 error = true;
1761 LOG(ERROR) << "Could not create image space with image file '" << image_file_name << "'. "
1762 << "Attempting to fall back to imageless running. Error was: " << error_msg
1763 << "\nAttempted image: " << image_name;
1764 break;
1765 }
1766 }
1767
1768 if (error) {
1769 // Remove already loaded spaces.
1770 for (space::Space* loaded_space : *boot_image_spaces) {
1771 delete loaded_space;
1772 }
1773 boot_image_spaces->clear();
1774 return false;
1775 }
1776
1777 *oat_file_end = oat_file_end_tmp;
1778 return true;
1779}
1780
Igor Murashkin8275fba2017-05-02 15:58:02 -07001781ImageSpace::~ImageSpace() {
1782 Runtime* runtime = Runtime::Current();
1783 if (runtime == nullptr) {
1784 return;
1785 }
1786
1787 if (GetImageHeader().IsAppImage()) {
1788 // This image space did not modify resolution method then in Init.
1789 return;
1790 }
1791
1792 if (!runtime->HasResolutionMethod()) {
1793 // Another image space has already unloaded the below methods.
1794 return;
1795 }
1796
1797 runtime->ClearInstructionSet();
1798 runtime->ClearResolutionMethod();
1799 runtime->ClearImtConflictMethod();
1800 runtime->ClearImtUnimplementedMethod();
1801 runtime->ClearCalleeSaveMethods();
1802}
1803
Andreas Gampea463b6a2016-08-12 21:53:32 -07001804std::unique_ptr<ImageSpace> ImageSpace::CreateFromAppImage(const char* image,
1805 const OatFile* oat_file,
1806 std::string* error_msg) {
1807 return ImageSpaceLoader::Init(image,
1808 image,
1809 /*validate_oat_file*/false,
1810 oat_file,
1811 /*out*/error_msg);
1812}
1813
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001814const OatFile* ImageSpace::GetOatFile() const {
Andreas Gampe88da3b02015-06-12 20:38:49 -07001815 return oat_file_non_owned_;
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001816}
1817
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -07001818std::unique_ptr<const OatFile> ImageSpace::ReleaseOatFile() {
1819 CHECK(oat_file_ != nullptr);
1820 return std::move(oat_file_);
Ian Rogers1d54e732013-05-02 21:10:01 -07001821}
1822
Ian Rogers1d54e732013-05-02 21:10:01 -07001823void ImageSpace::Dump(std::ostream& os) const {
1824 os << GetType()
Mathieu Chartier590fee92013-09-13 13:46:47 -07001825 << " begin=" << reinterpret_cast<void*>(Begin())
Ian Rogers1d54e732013-05-02 21:10:01 -07001826 << ",end=" << reinterpret_cast<void*>(End())
1827 << ",size=" << PrettySize(Size())
1828 << ",name=\"" << GetName() << "\"]";
1829}
1830
Mathieu Chartier866d8742016-09-21 15:24:18 -07001831std::string ImageSpace::GetMultiImageBootClassPath(
1832 const std::vector<const char*>& dex_locations,
1833 const std::vector<const char*>& oat_filenames,
1834 const std::vector<const char*>& image_filenames) {
1835 DCHECK_GT(oat_filenames.size(), 1u);
1836 // If the image filename was adapted (e.g., for our tests), we need to change this here,
1837 // too, but need to strip all path components (they will be re-established when loading).
1838 std::ostringstream bootcp_oss;
1839 bool first_bootcp = true;
1840 for (size_t i = 0; i < dex_locations.size(); ++i) {
1841 if (!first_bootcp) {
1842 bootcp_oss << ":";
1843 }
1844
1845 std::string dex_loc = dex_locations[i];
1846 std::string image_filename = image_filenames[i];
1847
1848 // Use the dex_loc path, but the image_filename name (without path elements).
1849 size_t dex_last_slash = dex_loc.rfind('/');
1850
1851 // npos is max(size_t). That makes this a bit ugly.
1852 size_t image_last_slash = image_filename.rfind('/');
1853 size_t image_last_at = image_filename.rfind('@');
1854 size_t image_last_sep = (image_last_slash == std::string::npos)
1855 ? image_last_at
1856 : (image_last_at == std::string::npos)
1857 ? std::string::npos
1858 : std::max(image_last_slash, image_last_at);
1859 // Note: whenever image_last_sep == npos, +1 overflow means using the full string.
1860
1861 if (dex_last_slash == std::string::npos) {
1862 dex_loc = image_filename.substr(image_last_sep + 1);
1863 } else {
1864 dex_loc = dex_loc.substr(0, dex_last_slash + 1) +
1865 image_filename.substr(image_last_sep + 1);
1866 }
1867
1868 // Image filenames already end with .art, no need to replace.
1869
1870 bootcp_oss << dex_loc;
1871 first_bootcp = false;
1872 }
1873 return bootcp_oss.str();
1874}
1875
Richard Uhler84f50ae2017-02-06 15:12:45 +00001876bool ImageSpace::ValidateOatFile(const OatFile& oat_file, std::string* error_msg) {
David Sehr013fd802018-01-11 22:55:24 -08001877 const ArtDexFileLoader dex_file_loader;
Andreas Gampeb40d3612018-06-26 15:49:42 -07001878 for (const OatDexFile* oat_dex_file : oat_file.GetOatDexFiles()) {
Richard Uhler84f50ae2017-02-06 15:12:45 +00001879 const std::string& dex_file_location = oat_dex_file->GetDexFileLocation();
1880
1881 // Skip multidex locations - These will be checked when we visit their
1882 // corresponding primary non-multidex location.
Mathieu Chartier79c87da2017-10-10 11:54:29 -07001883 if (DexFileLoader::IsMultiDexLocation(dex_file_location.c_str())) {
Richard Uhler84f50ae2017-02-06 15:12:45 +00001884 continue;
1885 }
1886
1887 std::vector<uint32_t> checksums;
David Sehr013fd802018-01-11 22:55:24 -08001888 if (!dex_file_loader.GetMultiDexChecksums(dex_file_location.c_str(), &checksums, error_msg)) {
Richard Uhler84f50ae2017-02-06 15:12:45 +00001889 *error_msg = StringPrintf("ValidateOatFile failed to get checksums of dex file '%s' "
1890 "referenced by oat file %s: %s",
1891 dex_file_location.c_str(),
1892 oat_file.GetLocation().c_str(),
1893 error_msg->c_str());
1894 return false;
1895 }
1896 CHECK(!checksums.empty());
1897 if (checksums[0] != oat_dex_file->GetDexFileLocationChecksum()) {
1898 *error_msg = StringPrintf("ValidateOatFile found checksum mismatch between oat file "
1899 "'%s' and dex file '%s' (0x%x != 0x%x)",
1900 oat_file.GetLocation().c_str(),
1901 dex_file_location.c_str(),
1902 oat_dex_file->GetDexFileLocationChecksum(),
1903 checksums[0]);
1904 return false;
1905 }
1906
1907 // Verify checksums for any related multidex entries.
1908 for (size_t i = 1; i < checksums.size(); i++) {
Mathieu Chartier79c87da2017-10-10 11:54:29 -07001909 std::string multi_dex_location = DexFileLoader::GetMultiDexLocation(
1910 i,
1911 dex_file_location.c_str());
Andreas Gampeb40d3612018-06-26 15:49:42 -07001912 const OatDexFile* multi_dex = oat_file.GetOatDexFile(multi_dex_location.c_str(),
1913 nullptr,
1914 error_msg);
Richard Uhler84f50ae2017-02-06 15:12:45 +00001915 if (multi_dex == nullptr) {
1916 *error_msg = StringPrintf("ValidateOatFile oat file '%s' is missing entry '%s'",
1917 oat_file.GetLocation().c_str(),
1918 multi_dex_location.c_str());
1919 return false;
1920 }
1921
1922 if (checksums[i] != multi_dex->GetDexFileLocationChecksum()) {
1923 *error_msg = StringPrintf("ValidateOatFile found checksum mismatch between oat file "
1924 "'%s' and dex file '%s' (0x%x != 0x%x)",
1925 oat_file.GetLocation().c_str(),
1926 multi_dex_location.c_str(),
1927 multi_dex->GetDexFileLocationChecksum(),
1928 checksums[i]);
1929 return false;
1930 }
1931 }
1932 }
1933 return true;
1934}
1935
Mathieu Chartier866d8742016-09-21 15:24:18 -07001936void ImageSpace::ExtractMultiImageLocations(const std::string& input_image_file_name,
1937 const std::string& boot_classpath,
1938 std::vector<std::string>* image_file_names) {
Andreas Gampe8994a042015-12-30 19:03:17 +00001939 DCHECK(image_file_names != nullptr);
1940
1941 std::vector<std::string> images;
1942 Split(boot_classpath, ':', &images);
1943
1944 // Add the rest into the list. We have to adjust locations, possibly:
1945 //
1946 // For example, image_file_name is /a/b/c/d/e.art
1947 // images[0] is f/c/d/e.art
1948 // ----------------------------------------------
1949 // images[1] is g/h/i/j.art -> /a/b/h/i/j.art
Mathieu Chartier8b8f6d62016-03-08 16:50:20 -08001950 const std::string& first_image = images[0];
1951 // Length of common suffix.
1952 size_t common = 0;
1953 while (common < input_image_file_name.size() &&
1954 common < first_image.size() &&
1955 *(input_image_file_name.end() - common - 1) == *(first_image.end() - common - 1)) {
1956 ++common;
Andreas Gampe8994a042015-12-30 19:03:17 +00001957 }
Mathieu Chartier8b8f6d62016-03-08 16:50:20 -08001958 // We want to replace the prefix of the input image with the prefix of the boot class path.
1959 // This handles the case where the image file contains @ separators.
1960 // Example image_file_name is oats/system@framework@boot.art
1961 // images[0] is .../arm/boot.art
1962 // means that the image name prefix will be oats/system@framework@
1963 // so that the other images are openable.
1964 const size_t old_prefix_length = first_image.size() - common;
1965 const std::string new_prefix = input_image_file_name.substr(
1966 0,
1967 input_image_file_name.size() - common);
Andreas Gampe8994a042015-12-30 19:03:17 +00001968
1969 // Apply pattern to images[1] .. images[n].
1970 for (size_t i = 1; i < images.size(); ++i) {
Mathieu Chartier8b8f6d62016-03-08 16:50:20 -08001971 const std::string& image = images[i];
1972 CHECK_GT(image.length(), old_prefix_length);
1973 std::string suffix = image.substr(old_prefix_length);
1974 image_file_names->push_back(new_prefix + suffix);
Andreas Gampe8994a042015-12-30 19:03:17 +00001975 }
1976}
1977
Mathieu Chartierd5f3f322016-03-21 14:05:56 -07001978void ImageSpace::DumpSections(std::ostream& os) const {
1979 const uint8_t* base = Begin();
1980 const ImageHeader& header = GetImageHeader();
1981 for (size_t i = 0; i < ImageHeader::kSectionCount; ++i) {
1982 auto section_type = static_cast<ImageHeader::ImageSections>(i);
1983 const ImageSection& section = header.GetImageSection(section_type);
1984 os << section_type << " " << reinterpret_cast<const void*>(base + section.Offset())
1985 << "-" << reinterpret_cast<const void*>(base + section.End()) << "\n";
1986 }
1987}
1988
Ian Rogers1d54e732013-05-02 21:10:01 -07001989} // namespace space
1990} // namespace gc
1991} // namespace art