blob: ca5a3eeb176e0bc4bdc03604d0a67e67e2ab8c4d [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"
Narayan Kamathd1c606f2014-06-09 16:50:19 +010035#include "base/scoped_flock.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070036#include "base/stl_util.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080037#include "base/systrace.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010038#include "base/time_utils.h"
David Sehr013fd802018-01-11 22:55:24 -080039#include "dex/art_dex_file_loader.h"
David Sehr9e734c72018-01-04 17:56:19 -080040#include "dex/dex_file_loader.h"
David Sehr97c381e2017-02-01 15:09:58 -080041#include "exec_utils.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070042#include "gc/accounting/space_bitmap-inl.h"
Mathieu Chartier4a26f172016-01-26 14:26:18 -080043#include "image-inl.h"
Andreas Gampebec63582015-11-20 19:26:51 -080044#include "image_space_fs.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070045#include "mirror/class-inl.h"
46#include "mirror/object-inl.h"
Andreas Gampec6ea7d02017-02-01 16:46:28 -080047#include "mirror/object-refvisitor-inl.h"
Brian Carlstrom56d947f2013-07-15 13:14:23 -070048#include "oat_file.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070049#include "os.h"
Andreas Gamped482e732017-04-24 17:59:09 -070050#include "runtime.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070051#include "space-inl.h"
52#include "utils.h"
53
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,
243 const char* dest_filename,
244 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
257 std::string output_image_filename_arg("--output-image-file=");
258 output_image_filename_arg += dest_filename;
259
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);
270 argv.push_back(output_image_filename_arg);
271
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
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700280static ImageHeader* ReadSpecificImageHeader(const char* filename, std::string* error_msg) {
Alex Lighta59dd802014-07-02 16:28:08 -0700281 std::unique_ptr<ImageHeader> hdr(new ImageHeader);
282 if (!ReadSpecificImageHeader(filename, hdr.get())) {
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700283 *error_msg = StringPrintf("Unable to read image header for %s", filename);
Alex Lighta59dd802014-07-02 16:28:08 -0700284 return nullptr;
285 }
286 return hdr.release();
Narayan Kamath52f84882014-05-02 10:10:39 +0100287}
288
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700289ImageHeader* ImageSpace::ReadImageHeader(const char* image_location,
290 const InstructionSet image_isa,
291 std::string* error_msg) {
Alex Lighta59dd802014-07-02 16:28:08 -0700292 std::string system_filename;
293 bool has_system = false;
294 std::string cache_filename;
295 bool has_cache = false;
296 bool dalvik_cache_exists = false;
Andreas Gampe3c13a792014-09-18 20:56:04 -0700297 bool is_global_cache = false;
Alex Lighta59dd802014-07-02 16:28:08 -0700298 if (FindImageFilename(image_location, image_isa, &system_filename, &has_system,
Andreas Gampe3c13a792014-09-18 20:56:04 -0700299 &cache_filename, &dalvik_cache_exists, &has_cache, &is_global_cache)) {
Alex Lighta59dd802014-07-02 16:28:08 -0700300 if (Runtime::Current()->ShouldRelocate()) {
301 if (has_system && has_cache) {
302 std::unique_ptr<ImageHeader> sys_hdr(new ImageHeader);
303 std::unique_ptr<ImageHeader> cache_hdr(new ImageHeader);
304 if (!ReadSpecificImageHeader(system_filename.c_str(), sys_hdr.get())) {
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700305 *error_msg = StringPrintf("Unable to read image header for %s at %s",
306 image_location, system_filename.c_str());
Alex Lighta59dd802014-07-02 16:28:08 -0700307 return nullptr;
308 }
309 if (!ReadSpecificImageHeader(cache_filename.c_str(), cache_hdr.get())) {
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700310 *error_msg = StringPrintf("Unable to read image header for %s at %s",
311 image_location, cache_filename.c_str());
Alex Lighta59dd802014-07-02 16:28:08 -0700312 return nullptr;
313 }
314 if (sys_hdr->GetOatChecksum() != cache_hdr->GetOatChecksum()) {
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700315 *error_msg = StringPrintf("Unable to find a relocated version of image file %s",
316 image_location);
Alex Lighta59dd802014-07-02 16:28:08 -0700317 return nullptr;
318 }
319 return cache_hdr.release();
320 } else if (!has_cache) {
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700321 *error_msg = StringPrintf("Unable to find a relocated version of image file %s",
322 image_location);
Alex Lighta59dd802014-07-02 16:28:08 -0700323 return nullptr;
324 } else if (!has_system && has_cache) {
325 // This can probably just use the cache one.
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700326 return ReadSpecificImageHeader(cache_filename.c_str(), error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -0700327 }
328 } else {
329 // We don't want to relocate, Just pick the appropriate one if we have it and return.
330 if (has_system && has_cache) {
331 // We want the cache if the checksum matches, otherwise the system.
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700332 std::unique_ptr<ImageHeader> system(ReadSpecificImageHeader(system_filename.c_str(),
333 error_msg));
334 std::unique_ptr<ImageHeader> cache(ReadSpecificImageHeader(cache_filename.c_str(),
335 error_msg));
Alex Lighta59dd802014-07-02 16:28:08 -0700336 if (system.get() == nullptr ||
337 (cache.get() != nullptr && cache->GetOatChecksum() == system->GetOatChecksum())) {
338 return cache.release();
339 } else {
340 return system.release();
341 }
342 } else if (has_system) {
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700343 return ReadSpecificImageHeader(system_filename.c_str(), error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -0700344 } else if (has_cache) {
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700345 return ReadSpecificImageHeader(cache_filename.c_str(), error_msg);
Alex Lighta59dd802014-07-02 16:28:08 -0700346 }
Narayan Kamath52f84882014-05-02 10:10:39 +0100347 }
Narayan Kamath52f84882014-05-02 10:10:39 +0100348 }
349
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700350 *error_msg = StringPrintf("Unable to find image file for %s", image_location);
Narayan Kamath52f84882014-05-02 10:10:39 +0100351 return nullptr;
352}
353
Andreas Gampea463b6a2016-08-12 21:53:32 -0700354static bool ChecksumsMatch(const char* image_a, const char* image_b, std::string* error_msg) {
355 DCHECK(error_msg != nullptr);
356
Alex Lighta59dd802014-07-02 16:28:08 -0700357 ImageHeader hdr_a;
358 ImageHeader hdr_b;
Andreas Gampea463b6a2016-08-12 21:53:32 -0700359
360 if (!ReadSpecificImageHeader(image_a, &hdr_a)) {
361 *error_msg = StringPrintf("Cannot read header of %s", image_a);
362 return false;
363 }
364 if (!ReadSpecificImageHeader(image_b, &hdr_b)) {
365 *error_msg = StringPrintf("Cannot read header of %s", image_b);
366 return false;
367 }
368
369 if (hdr_a.GetOatChecksum() != hdr_b.GetOatChecksum()) {
370 *error_msg = StringPrintf("Checksum mismatch: %u(%s) vs %u(%s)",
371 hdr_a.GetOatChecksum(),
372 image_a,
373 hdr_b.GetOatChecksum(),
374 image_b);
375 return false;
376 }
377
378 return true;
Alex Lighta59dd802014-07-02 16:28:08 -0700379}
380
Robert Sesekbfa1f8d2016-08-15 15:21:09 -0400381static bool CanWriteToDalvikCache(const InstructionSet isa) {
382 const std::string dalvik_cache = GetDalvikCache(GetInstructionSetString(isa));
383 if (access(dalvik_cache.c_str(), O_RDWR) == 0) {
384 return true;
385 } else if (errno != EACCES) {
386 PLOG(WARNING) << "CanWriteToDalvikCache returned error other than EACCES";
387 }
388 return false;
389}
390
391static bool ImageCreationAllowed(bool is_global_cache,
392 const InstructionSet isa,
393 std::string* error_msg) {
Andreas Gampe3c13a792014-09-18 20:56:04 -0700394 // Anyone can write into a "local" cache.
395 if (!is_global_cache) {
396 return true;
397 }
398
Robert Sesekbfa1f8d2016-08-15 15:21:09 -0400399 // Only the zygote running as root is allowed to create the global boot image.
400 // If the zygote is running as non-root (and cannot write to the dalvik-cache),
401 // then image creation is not allowed..
Andreas Gampe3c13a792014-09-18 20:56:04 -0700402 if (Runtime::Current()->IsZygote()) {
Robert Sesekbfa1f8d2016-08-15 15:21:09 -0400403 return CanWriteToDalvikCache(isa);
Andreas Gampe3c13a792014-09-18 20:56:04 -0700404 }
405
406 *error_msg = "Only the zygote can create the global boot image.";
407 return false;
408}
409
Mathieu Chartier31e89252013-08-28 11:29:12 -0700410void ImageSpace::VerifyImageAllocations() {
Ian Rogers13735952014-10-08 12:43:28 -0700411 uint8_t* current = Begin() + RoundUp(sizeof(ImageHeader), kObjectAlignment);
Mathieu Chartier31e89252013-08-28 11:29:12 -0700412 while (current < End()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700413 CHECK_ALIGNED(current, kObjectAlignment);
414 auto* obj = reinterpret_cast<mirror::Object*>(current);
Mathieu Chartier31e89252013-08-28 11:29:12 -0700415 CHECK(obj->GetClass() != nullptr) << "Image object at address " << obj << " has null class";
David Sehr709b0702016-10-13 09:12:37 -0700416 CHECK(live_bitmap_->Test(obj)) << obj->PrettyTypeOf();
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700417 if (kUseBakerReadBarrier) {
418 obj->AssertReadBarrierState();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800419 }
Mathieu Chartier31e89252013-08-28 11:29:12 -0700420 current += RoundUp(obj->SizeOf(), kObjectAlignment);
421 }
422}
423
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800424// Helper class for relocating from one range of memory to another.
425class RelocationRange {
426 public:
427 RelocationRange() = default;
428 RelocationRange(const RelocationRange&) = default;
429 RelocationRange(uintptr_t source, uintptr_t dest, uintptr_t length)
430 : source_(source),
431 dest_(dest),
432 length_(length) {}
433
Mathieu Chartier91edc622016-02-16 17:16:01 -0800434 bool InSource(uintptr_t address) const {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800435 return address - source_ < length_;
436 }
437
Mathieu Chartier91edc622016-02-16 17:16:01 -0800438 bool InDest(uintptr_t address) const {
439 return address - dest_ < length_;
440 }
441
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800442 // Translate a source address to the destination space.
443 uintptr_t ToDest(uintptr_t address) const {
Mathieu Chartier91edc622016-02-16 17:16:01 -0800444 DCHECK(InSource(address));
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800445 return address + Delta();
446 }
447
448 // Returns the delta between the dest from the source.
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800449 uintptr_t Delta() const {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800450 return dest_ - source_;
451 }
452
453 uintptr_t Source() const {
454 return source_;
455 }
456
457 uintptr_t Dest() const {
458 return dest_;
459 }
460
461 uintptr_t Length() const {
462 return length_;
463 }
464
465 private:
466 const uintptr_t source_;
467 const uintptr_t dest_;
468 const uintptr_t length_;
469};
470
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800471std::ostream& operator<<(std::ostream& os, const RelocationRange& reloc) {
472 return os << "(" << reinterpret_cast<const void*>(reloc.Source()) << "-"
473 << reinterpret_cast<const void*>(reloc.Source() + reloc.Length()) << ")->("
474 << reinterpret_cast<const void*>(reloc.Dest()) << "-"
475 << reinterpret_cast<const void*>(reloc.Dest() + reloc.Length()) << ")";
476}
477
Andreas Gampea463b6a2016-08-12 21:53:32 -0700478// Helper class encapsulating loading, so we can access private ImageSpace members (this is a
479// friend class), but not declare functions in the header.
480class ImageSpaceLoader {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800481 public:
Andreas Gampea463b6a2016-08-12 21:53:32 -0700482 static std::unique_ptr<ImageSpace> Load(const char* image_location,
483 const std::string& image_filename,
484 bool is_zygote,
485 bool is_global_cache,
Andreas Gampe44c8ed62016-08-19 16:43:00 -0700486 bool validate_oat_file,
Andreas Gampea463b6a2016-08-12 21:53:32 -0700487 std::string* error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700488 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampea463b6a2016-08-12 21:53:32 -0700489 // Should this be a RDWR lock? This is only a defensive measure, as at
490 // this point the image should exist.
491 // However, only the zygote can write into the global dalvik-cache, so
492 // restrict to zygote processes, or any process that isn't using
493 // /data/dalvik-cache (which we assume to be allowed to write there).
494 const bool rw_lock = is_zygote || !is_global_cache;
Narayan Kamatha3d27eb2017-05-11 13:50:59 +0100495
496 // Note that we must not use the file descriptor associated with
497 // ScopedFlock::GetFile to Init the image file. We want the file
498 // descriptor (and the associated exclusive lock) to be released when
499 // we leave Create.
500 ScopedFlock image = LockedFile::Open(image_filename.c_str(),
501 rw_lock ? (O_CREAT | O_RDWR) : O_RDONLY /* flags */,
502 true /* block */,
503 error_msg);
504
Andreas Gampea463b6a2016-08-12 21:53:32 -0700505 VLOG(startup) << "Using image file " << image_filename.c_str() << " for image location "
506 << image_location;
507 // If we are in /system we can assume the image is good. We can also
508 // assume this if we are using a relocated image (i.e. image checksum
509 // matches) since this is only different by the offset. We need this to
510 // make sure that host tests continue to work.
511 // Since we are the boot image, pass null since we load the oat file from the boot image oat
512 // file name.
513 return Init(image_filename.c_str(),
514 image_location,
Andreas Gampe44c8ed62016-08-19 16:43:00 -0700515 validate_oat_file,
Andreas Gampea463b6a2016-08-12 21:53:32 -0700516 /* oat_file */nullptr,
517 error_msg);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800518 }
519
Andreas Gampea463b6a2016-08-12 21:53:32 -0700520 static std::unique_ptr<ImageSpace> Init(const char* image_filename,
521 const char* image_location,
522 bool validate_oat_file,
523 const OatFile* oat_file,
524 std::string* error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700525 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampea463b6a2016-08-12 21:53:32 -0700526 CHECK(image_filename != nullptr);
527 CHECK(image_location != nullptr);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800528
Andreas Gampea463b6a2016-08-12 21:53:32 -0700529 TimingLogger logger(__PRETTY_FUNCTION__, true, VLOG_IS_ON(image));
530 VLOG(image) << "ImageSpace::Init entering image_filename=" << image_filename;
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800531
Andreas Gampea463b6a2016-08-12 21:53:32 -0700532 std::unique_ptr<File> file;
Mathieu Chartier92ec5942016-04-11 12:03:48 -0700533 {
Andreas Gampea463b6a2016-08-12 21:53:32 -0700534 TimingLogger::ScopedTiming timing("OpenImageFile", &logger);
535 file.reset(OS::OpenFileForReading(image_filename));
536 if (file == nullptr) {
537 *error_msg = StringPrintf("Failed to open '%s'", image_filename);
538 return nullptr;
Mathieu Chartier92ec5942016-04-11 12:03:48 -0700539 }
Andreas Gampea463b6a2016-08-12 21:53:32 -0700540 }
541 ImageHeader temp_image_header;
542 ImageHeader* image_header = &temp_image_header;
543 {
544 TimingLogger::ScopedTiming timing("ReadImageHeader", &logger);
545 bool success = file->ReadFully(image_header, sizeof(*image_header));
546 if (!success || !image_header->IsValid()) {
547 *error_msg = StringPrintf("Invalid image header in '%s'", image_filename);
548 return nullptr;
549 }
550 }
551 // Check that the file is larger or equal to the header size + data size.
552 const uint64_t image_file_size = static_cast<uint64_t>(file->GetLength());
553 if (image_file_size < sizeof(ImageHeader) + image_header->GetDataSize()) {
554 *error_msg = StringPrintf("Image file truncated: %" PRIu64 " vs. %" PRIu64 ".",
555 image_file_size,
556 sizeof(ImageHeader) + image_header->GetDataSize());
557 return nullptr;
558 }
559
560 if (oat_file != nullptr) {
561 // If we have an oat file, check the oat file checksum. The oat file is only non-null for the
562 // app image case. Otherwise, we open the oat file after the image and check the checksum there.
563 const uint32_t oat_checksum = oat_file->GetOatHeader().GetChecksum();
564 const uint32_t image_oat_checksum = image_header->GetOatChecksum();
565 if (oat_checksum != image_oat_checksum) {
566 *error_msg = StringPrintf("Oat checksum 0x%x does not match the image one 0x%x in image %s",
567 oat_checksum,
568 image_oat_checksum,
569 image_filename);
570 return nullptr;
Mathieu Chartier92ec5942016-04-11 12:03:48 -0700571 }
572 }
573
Andreas Gampea463b6a2016-08-12 21:53:32 -0700574 if (VLOG_IS_ON(startup)) {
575 LOG(INFO) << "Dumping image sections";
576 for (size_t i = 0; i < ImageHeader::kSectionCount; ++i) {
577 const auto section_idx = static_cast<ImageHeader::ImageSections>(i);
578 auto& section = image_header->GetImageSection(section_idx);
579 LOG(INFO) << section_idx << " start="
580 << reinterpret_cast<void*>(image_header->GetImageBegin() + section.Offset()) << " "
581 << section;
Mathieu Chartier92ec5942016-04-11 12:03:48 -0700582 }
Andreas Gampea463b6a2016-08-12 21:53:32 -0700583 }
584
Vladimir Markocd87c3e2017-09-05 13:11:57 +0100585 const auto& bitmap_section = image_header->GetImageBitmapSection();
Andreas Gampea463b6a2016-08-12 21:53:32 -0700586 // The location we want to map from is the first aligned page after the end of the stored
587 // (possibly compressed) data.
588 const size_t image_bitmap_offset = RoundUp(sizeof(ImageHeader) + image_header->GetDataSize(),
589 kPageSize);
590 const size_t end_of_bitmap = image_bitmap_offset + bitmap_section.Size();
591 if (end_of_bitmap != image_file_size) {
592 *error_msg = StringPrintf(
593 "Image file size does not equal end of bitmap: size=%" PRIu64 " vs. %zu.", image_file_size,
594 end_of_bitmap);
595 return nullptr;
596 }
597
598 std::unique_ptr<MemMap> map;
Mathieu Chartier66b1d572017-02-10 18:41:39 -0800599
Andreas Gampea463b6a2016-08-12 21:53:32 -0700600 // GetImageBegin is the preferred address to map the image. If we manage to map the
601 // image at the image begin, the amount of fixup work required is minimized.
Mathieu Chartier66b1d572017-02-10 18:41:39 -0800602 // If it is pic we will retry with error_msg for the failure case. Pass a null error_msg to
603 // avoid reading proc maps for a mapping failure and slowing everything down.
Andreas Gampea463b6a2016-08-12 21:53:32 -0700604 map.reset(LoadImageFile(image_filename,
605 image_location,
606 *image_header,
607 image_header->GetImageBegin(),
608 file->Fd(),
609 logger,
Mathieu Chartier66b1d572017-02-10 18:41:39 -0800610 image_header->IsPic() ? nullptr : error_msg));
Andreas Gampea463b6a2016-08-12 21:53:32 -0700611 // If the header specifies PIC mode, we can also map at a random low_4gb address since we can
612 // relocate in-place.
613 if (map == nullptr && image_header->IsPic()) {
614 map.reset(LoadImageFile(image_filename,
615 image_location,
616 *image_header,
617 /* address */ nullptr,
618 file->Fd(),
619 logger,
620 error_msg));
621 }
622 // Were we able to load something and continue?
623 if (map == nullptr) {
624 DCHECK(!error_msg->empty());
625 return nullptr;
626 }
627 DCHECK_EQ(0, memcmp(image_header, map->Begin(), sizeof(ImageHeader)));
628
629 std::unique_ptr<MemMap> image_bitmap_map(MemMap::MapFileAtAddress(nullptr,
630 bitmap_section.Size(),
631 PROT_READ, MAP_PRIVATE,
632 file->Fd(),
633 image_bitmap_offset,
634 /*low_4gb*/false,
635 /*reuse*/false,
636 image_filename,
637 error_msg));
638 if (image_bitmap_map == nullptr) {
639 *error_msg = StringPrintf("Failed to map image bitmap: %s", error_msg->c_str());
640 return nullptr;
641 }
642 // Loaded the map, use the image header from the file now in case we patch it with
643 // RelocateInPlace.
644 image_header = reinterpret_cast<ImageHeader*>(map->Begin());
645 const uint32_t bitmap_index = ImageSpace::bitmap_index_.FetchAndAddSequentiallyConsistent(1);
646 std::string bitmap_name(StringPrintf("imagespace %s live-bitmap %u",
647 image_filename,
648 bitmap_index));
649 // Bitmap only needs to cover until the end of the mirror objects section.
Vladimir Markocd87c3e2017-09-05 13:11:57 +0100650 const ImageSection& image_objects = image_header->GetObjectsSection();
Andreas Gampea463b6a2016-08-12 21:53:32 -0700651 // We only want the mirror object, not the ArtFields and ArtMethods.
652 uint8_t* const image_end = map->Begin() + image_objects.End();
653 std::unique_ptr<accounting::ContinuousSpaceBitmap> bitmap;
654 {
655 TimingLogger::ScopedTiming timing("CreateImageBitmap", &logger);
656 bitmap.reset(
657 accounting::ContinuousSpaceBitmap::CreateFromMemMap(
658 bitmap_name,
659 image_bitmap_map.release(),
660 reinterpret_cast<uint8_t*>(map->Begin()),
Mathieu Chartier612ff542017-05-01 09:59:24 -0700661 // Make sure the bitmap is aligned to card size instead of just bitmap word size.
662 RoundUp(image_objects.End(), gc::accounting::CardTable::kCardSize)));
Andreas Gampea463b6a2016-08-12 21:53:32 -0700663 if (bitmap == nullptr) {
664 *error_msg = StringPrintf("Could not create bitmap '%s'", bitmap_name.c_str());
665 return nullptr;
666 }
667 }
668 {
669 TimingLogger::ScopedTiming timing("RelocateImage", &logger);
670 if (!RelocateInPlace(*image_header,
671 map->Begin(),
672 bitmap.get(),
673 oat_file,
674 error_msg)) {
675 return nullptr;
676 }
677 }
678 // We only want the mirror object, not the ArtFields and ArtMethods.
679 std::unique_ptr<ImageSpace> space(new ImageSpace(image_filename,
680 image_location,
681 map.release(),
682 bitmap.release(),
683 image_end));
684
685 // VerifyImageAllocations() will be called later in Runtime::Init()
686 // as some class roots like ArtMethod::java_lang_reflect_ArtMethod_
687 // and ArtField::java_lang_reflect_ArtField_, which are used from
688 // Object::SizeOf() which VerifyImageAllocations() calls, are not
689 // set yet at this point.
690 if (oat_file == nullptr) {
691 TimingLogger::ScopedTiming timing("OpenOatFile", &logger);
692 space->oat_file_ = OpenOatFile(*space, image_filename, error_msg);
693 if (space->oat_file_ == nullptr) {
694 DCHECK(!error_msg->empty());
695 return nullptr;
696 }
697 space->oat_file_non_owned_ = space->oat_file_.get();
698 } else {
699 space->oat_file_non_owned_ = oat_file;
700 }
701
702 if (validate_oat_file) {
703 TimingLogger::ScopedTiming timing("ValidateOatFile", &logger);
704 CHECK(space->oat_file_ != nullptr);
Richard Uhler84f50ae2017-02-06 15:12:45 +0000705 if (!ImageSpace::ValidateOatFile(*space->oat_file_, error_msg)) {
Andreas Gampea463b6a2016-08-12 21:53:32 -0700706 DCHECK(!error_msg->empty());
707 return nullptr;
708 }
709 }
710
711 Runtime* runtime = Runtime::Current();
712
713 // If oat_file is null, then it is the boot image space. Use oat_file_non_owned_ from the space
714 // to set the runtime methods.
715 CHECK_EQ(oat_file != nullptr, image_header->IsAppImage());
716 if (image_header->IsAppImage()) {
717 CHECK_EQ(runtime->GetResolutionMethod(),
718 image_header->GetImageMethod(ImageHeader::kResolutionMethod));
719 CHECK_EQ(runtime->GetImtConflictMethod(),
720 image_header->GetImageMethod(ImageHeader::kImtConflictMethod));
721 CHECK_EQ(runtime->GetImtUnimplementedMethod(),
722 image_header->GetImageMethod(ImageHeader::kImtUnimplementedMethod));
Andreas Gampe8228cdf2017-05-30 15:03:54 -0700723 CHECK_EQ(runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveAllCalleeSaves),
Andreas Gampea463b6a2016-08-12 21:53:32 -0700724 image_header->GetImageMethod(ImageHeader::kSaveAllCalleeSavesMethod));
Andreas Gampe8228cdf2017-05-30 15:03:54 -0700725 CHECK_EQ(runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveRefsOnly),
Andreas Gampea463b6a2016-08-12 21:53:32 -0700726 image_header->GetImageMethod(ImageHeader::kSaveRefsOnlyMethod));
Andreas Gampe8228cdf2017-05-30 15:03:54 -0700727 CHECK_EQ(runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveRefsAndArgs),
Andreas Gampea463b6a2016-08-12 21:53:32 -0700728 image_header->GetImageMethod(ImageHeader::kSaveRefsAndArgsMethod));
Andreas Gampe8228cdf2017-05-30 15:03:54 -0700729 CHECK_EQ(runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveEverything),
Andreas Gampea463b6a2016-08-12 21:53:32 -0700730 image_header->GetImageMethod(ImageHeader::kSaveEverythingMethod));
Mingyao Yang0a87a652017-04-12 13:43:15 -0700731 CHECK_EQ(runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveEverythingForClinit),
732 image_header->GetImageMethod(ImageHeader::kSaveEverythingMethodForClinit));
733 CHECK_EQ(runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveEverythingForSuspendCheck),
734 image_header->GetImageMethod(ImageHeader::kSaveEverythingMethodForSuspendCheck));
Andreas Gampea463b6a2016-08-12 21:53:32 -0700735 } else if (!runtime->HasResolutionMethod()) {
736 runtime->SetInstructionSet(space->oat_file_non_owned_->GetOatHeader().GetInstructionSet());
737 runtime->SetResolutionMethod(image_header->GetImageMethod(ImageHeader::kResolutionMethod));
738 runtime->SetImtConflictMethod(image_header->GetImageMethod(ImageHeader::kImtConflictMethod));
739 runtime->SetImtUnimplementedMethod(
740 image_header->GetImageMethod(ImageHeader::kImtUnimplementedMethod));
741 runtime->SetCalleeSaveMethod(
742 image_header->GetImageMethod(ImageHeader::kSaveAllCalleeSavesMethod),
Andreas Gampe8228cdf2017-05-30 15:03:54 -0700743 CalleeSaveType::kSaveAllCalleeSaves);
Andreas Gampea463b6a2016-08-12 21:53:32 -0700744 runtime->SetCalleeSaveMethod(
Andreas Gampe8228cdf2017-05-30 15:03:54 -0700745 image_header->GetImageMethod(ImageHeader::kSaveRefsOnlyMethod),
746 CalleeSaveType::kSaveRefsOnly);
Andreas Gampea463b6a2016-08-12 21:53:32 -0700747 runtime->SetCalleeSaveMethod(
748 image_header->GetImageMethod(ImageHeader::kSaveRefsAndArgsMethod),
Andreas Gampe8228cdf2017-05-30 15:03:54 -0700749 CalleeSaveType::kSaveRefsAndArgs);
Andreas Gampea463b6a2016-08-12 21:53:32 -0700750 runtime->SetCalleeSaveMethod(
Andreas Gampe8228cdf2017-05-30 15:03:54 -0700751 image_header->GetImageMethod(ImageHeader::kSaveEverythingMethod),
752 CalleeSaveType::kSaveEverything);
Mingyao Yang0a87a652017-04-12 13:43:15 -0700753 runtime->SetCalleeSaveMethod(
754 image_header->GetImageMethod(ImageHeader::kSaveEverythingMethodForClinit),
755 CalleeSaveType::kSaveEverythingForClinit);
756 runtime->SetCalleeSaveMethod(
757 image_header->GetImageMethod(ImageHeader::kSaveEverythingMethodForSuspendCheck),
758 CalleeSaveType::kSaveEverythingForSuspendCheck);
Andreas Gampea463b6a2016-08-12 21:53:32 -0700759 }
760
761 VLOG(image) << "ImageSpace::Init exiting " << *space.get();
762 if (VLOG_IS_ON(image)) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -0700763 logger.Dump(LOG_STREAM(INFO));
Andreas Gampea463b6a2016-08-12 21:53:32 -0700764 }
765 return space;
766 }
767
768 private:
769 static MemMap* LoadImageFile(const char* image_filename,
770 const char* image_location,
771 const ImageHeader& image_header,
772 uint8_t* address,
773 int fd,
774 TimingLogger& logger,
775 std::string* error_msg) {
776 TimingLogger::ScopedTiming timing("MapImageFile", &logger);
777 const ImageHeader::StorageMode storage_mode = image_header.GetStorageMode();
778 if (storage_mode == ImageHeader::kStorageModeUncompressed) {
779 return MemMap::MapFileAtAddress(address,
780 image_header.GetImageSize(),
781 PROT_READ | PROT_WRITE,
782 MAP_PRIVATE,
783 fd,
784 0,
785 /*low_4gb*/true,
786 /*reuse*/false,
787 image_filename,
788 error_msg);
789 }
790
791 if (storage_mode != ImageHeader::kStorageModeLZ4 &&
792 storage_mode != ImageHeader::kStorageModeLZ4HC) {
Mathieu Chartier66b1d572017-02-10 18:41:39 -0800793 if (error_msg != nullptr) {
794 *error_msg = StringPrintf("Invalid storage mode in image header %d",
795 static_cast<int>(storage_mode));
796 }
Andreas Gampea463b6a2016-08-12 21:53:32 -0700797 return nullptr;
798 }
799
800 // Reserve output and decompress into it.
801 std::unique_ptr<MemMap> map(MemMap::MapAnonymous(image_location,
802 address,
803 image_header.GetImageSize(),
804 PROT_READ | PROT_WRITE,
805 /*low_4gb*/true,
806 /*reuse*/false,
807 error_msg));
808 if (map != nullptr) {
809 const size_t stored_size = image_header.GetDataSize();
810 const size_t decompress_offset = sizeof(ImageHeader); // Skip the header.
811 std::unique_ptr<MemMap> temp_map(MemMap::MapFile(sizeof(ImageHeader) + stored_size,
812 PROT_READ,
813 MAP_PRIVATE,
814 fd,
815 /*offset*/0,
816 /*low_4gb*/false,
817 image_filename,
818 error_msg));
819 if (temp_map == nullptr) {
Mathieu Chartier66b1d572017-02-10 18:41:39 -0800820 DCHECK(error_msg == nullptr || !error_msg->empty());
Andreas Gampea463b6a2016-08-12 21:53:32 -0700821 return nullptr;
822 }
823 memcpy(map->Begin(), &image_header, sizeof(ImageHeader));
824 const uint64_t start = NanoTime();
825 // LZ4HC and LZ4 have same internal format, both use LZ4_decompress.
826 TimingLogger::ScopedTiming timing2("LZ4 decompress image", &logger);
827 const size_t decompressed_size = LZ4_decompress_safe(
828 reinterpret_cast<char*>(temp_map->Begin()) + sizeof(ImageHeader),
829 reinterpret_cast<char*>(map->Begin()) + decompress_offset,
830 stored_size,
831 map->Size() - decompress_offset);
Mathieu Chartier0d4d2912017-02-10 17:22:41 -0800832 const uint64_t time = NanoTime() - start;
833 // Add one 1 ns to prevent possible divide by 0.
834 VLOG(image) << "Decompressing image took " << PrettyDuration(time) << " ("
835 << PrettySize(static_cast<uint64_t>(map->Size()) * MsToNs(1000) / (time + 1))
836 << "/s)";
Andreas Gampea463b6a2016-08-12 21:53:32 -0700837 if (decompressed_size + sizeof(ImageHeader) != image_header.GetImageSize()) {
Mathieu Chartier66b1d572017-02-10 18:41:39 -0800838 if (error_msg != nullptr) {
839 *error_msg = StringPrintf(
840 "Decompressed size does not match expected image size %zu vs %zu",
841 decompressed_size + sizeof(ImageHeader),
842 image_header.GetImageSize());
843 }
Andreas Gampea463b6a2016-08-12 21:53:32 -0700844 return nullptr;
845 }
846 }
847
848 return map.release();
849 }
850
851 class FixupVisitor : public ValueObject {
852 public:
853 FixupVisitor(const RelocationRange& boot_image,
854 const RelocationRange& boot_oat,
855 const RelocationRange& app_image,
856 const RelocationRange& app_oat)
857 : boot_image_(boot_image),
858 boot_oat_(boot_oat),
859 app_image_(app_image),
860 app_oat_(app_oat) {}
861
862 // Return the relocated address of a heap object.
863 template <typename T>
864 ALWAYS_INLINE T* ForwardObject(T* src) const {
865 const uintptr_t uint_src = reinterpret_cast<uintptr_t>(src);
866 if (boot_image_.InSource(uint_src)) {
867 return reinterpret_cast<T*>(boot_image_.ToDest(uint_src));
868 }
869 if (app_image_.InSource(uint_src)) {
870 return reinterpret_cast<T*>(app_image_.ToDest(uint_src));
871 }
872 // Since we are fixing up the app image, there should only be pointers to the app image and
873 // boot image.
874 DCHECK(src == nullptr) << reinterpret_cast<const void*>(src);
875 return src;
876 }
877
878 // Return the relocated address of a code pointer (contained by an oat file).
879 ALWAYS_INLINE const void* ForwardCode(const void* src) const {
880 const uintptr_t uint_src = reinterpret_cast<uintptr_t>(src);
881 if (boot_oat_.InSource(uint_src)) {
882 return reinterpret_cast<const void*>(boot_oat_.ToDest(uint_src));
883 }
884 if (app_oat_.InSource(uint_src)) {
885 return reinterpret_cast<const void*>(app_oat_.ToDest(uint_src));
886 }
887 DCHECK(src == nullptr) << src;
888 return src;
889 }
890
891 // Must be called on pointers that already have been relocated to the destination relocation.
892 ALWAYS_INLINE bool IsInAppImage(mirror::Object* object) const {
893 return app_image_.InDest(reinterpret_cast<uintptr_t>(object));
894 }
895
896 protected:
897 // Source section.
898 const RelocationRange boot_image_;
899 const RelocationRange boot_oat_;
900 const RelocationRange app_image_;
901 const RelocationRange app_oat_;
902 };
903
904 // Adapt for mirror::Class::FixupNativePointers.
905 class FixupObjectAdapter : public FixupVisitor {
906 public:
907 template<typename... Args>
908 explicit FixupObjectAdapter(Args... args) : FixupVisitor(args...) {}
909
910 template <typename T>
Mathieu Chartier8c19d242017-03-06 12:35:10 -0800911 T* operator()(T* obj, void** dest_addr ATTRIBUTE_UNUSED = nullptr) const {
Andreas Gampea463b6a2016-08-12 21:53:32 -0700912 return ForwardObject(obj);
913 }
914 };
915
916 class FixupRootVisitor : public FixupVisitor {
917 public:
918 template<typename... Args>
919 explicit FixupRootVisitor(Args... args) : FixupVisitor(args...) {}
920
921 ALWAYS_INLINE void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700922 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampea463b6a2016-08-12 21:53:32 -0700923 if (!root->IsNull()) {
924 VisitRoot(root);
925 }
926 }
927
928 ALWAYS_INLINE void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700929 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampea463b6a2016-08-12 21:53:32 -0700930 mirror::Object* ref = root->AsMirrorPtr();
931 mirror::Object* new_ref = ForwardObject(ref);
932 if (ref != new_ref) {
933 root->Assign(new_ref);
934 }
935 }
936 };
937
938 class FixupObjectVisitor : public FixupVisitor {
939 public:
940 template<typename... Args>
941 explicit FixupObjectVisitor(gc::accounting::ContinuousSpaceBitmap* visited,
942 const PointerSize pointer_size,
943 Args... args)
944 : FixupVisitor(args...),
945 pointer_size_(pointer_size),
946 visited_(visited) {}
947
948 // Fix up separately since we also need to fix up method entrypoints.
949 ALWAYS_INLINE void VisitRootIfNonNull(
950 mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const {}
951
952 ALWAYS_INLINE void VisitRoot(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED)
953 const {}
954
Mathieu Chartier31e88222016-10-14 18:43:19 -0700955 ALWAYS_INLINE void operator()(ObjPtr<mirror::Object> obj,
Andreas Gampea463b6a2016-08-12 21:53:32 -0700956 MemberOffset offset,
957 bool is_static ATTRIBUTE_UNUSED) const
958 NO_THREAD_SAFETY_ANALYSIS {
959 // There could be overlap between ranges, we must avoid visiting the same reference twice.
960 // Avoid the class field since we already fixed it up in FixupClassVisitor.
961 if (offset.Uint32Value() != mirror::Object::ClassOffset().Uint32Value()) {
962 // Space is not yet added to the heap, don't do a read barrier.
963 mirror::Object* ref = obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(
964 offset);
965 // Use SetFieldObjectWithoutWriteBarrier to avoid card marking since we are writing to the
966 // image.
967 obj->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(offset, ForwardObject(ref));
968 }
969 }
970
971 // Visit a pointer array and forward corresponding native data. Ignores pointer arrays in the
972 // boot image. Uses the bitmap to ensure the same array is not visited multiple times.
973 template <typename Visitor>
974 void UpdatePointerArrayContents(mirror::PointerArray* array, const Visitor& visitor) const
975 NO_THREAD_SAFETY_ANALYSIS {
976 DCHECK(array != nullptr);
977 DCHECK(visitor.IsInAppImage(array));
978 // The bit for the array contents is different than the bit for the array. Since we may have
979 // already visited the array as a long / int array from walking the bitmap without knowing it
980 // was a pointer array.
981 static_assert(kObjectAlignment == 8u, "array bit may be in another object");
982 mirror::Object* const contents_bit = reinterpret_cast<mirror::Object*>(
983 reinterpret_cast<uintptr_t>(array) + kObjectAlignment);
984 // If the bit is not set then the contents have not yet been updated.
985 if (!visited_->Test(contents_bit)) {
986 array->Fixup<kVerifyNone, kWithoutReadBarrier>(array, pointer_size_, visitor);
987 visited_->Set(contents_bit);
988 }
989 }
990
991 // java.lang.ref.Reference visitor.
Mathieu Chartier31e88222016-10-14 18:43:19 -0700992 void operator()(ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
993 ObjPtr<mirror::Reference> ref) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700994 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Andreas Gampea463b6a2016-08-12 21:53:32 -0700995 mirror::Object* obj = ref->GetReferent<kWithoutReadBarrier>();
996 ref->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
997 mirror::Reference::ReferentOffset(),
998 ForwardObject(obj));
999 }
1000
Mathieu Chartier8c19d242017-03-06 12:35:10 -08001001 void operator()(mirror::Object* obj) const
1002 NO_THREAD_SAFETY_ANALYSIS {
Andreas Gampea463b6a2016-08-12 21:53:32 -07001003 if (visited_->Test(obj)) {
1004 // Already visited.
1005 return;
1006 }
1007 visited_->Set(obj);
1008
1009 // Handle class specially first since we need it to be updated to properly visit the rest of
1010 // the instance fields.
1011 {
1012 mirror::Class* klass = obj->GetClass<kVerifyNone, kWithoutReadBarrier>();
1013 DCHECK(klass != nullptr) << "Null class in image";
1014 // No AsClass since our fields aren't quite fixed up yet.
1015 mirror::Class* new_klass = down_cast<mirror::Class*>(ForwardObject(klass));
1016 if (klass != new_klass) {
1017 obj->SetClass<kVerifyNone>(new_klass);
1018 }
1019 if (new_klass != klass && IsInAppImage(new_klass)) {
1020 // Make sure the klass contents are fixed up since we depend on it to walk the fields.
1021 operator()(new_klass);
1022 }
1023 }
1024
Chang Xing4be3e9b2017-07-10 15:03:22 -07001025 if (obj->IsClass()) {
1026 mirror::Class* klass = obj->AsClass<kVerifyNone, kWithoutReadBarrier>();
1027 // Fixup super class before visiting instance fields which require
1028 // information from their super class to calculate offsets.
Chang Xing6f54cf22017-07-14 09:59:01 -07001029 mirror::Class* super_class = klass->GetSuperClass<kVerifyNone, kWithoutReadBarrier>();
Chang Xing4be3e9b2017-07-10 15:03:22 -07001030 if (super_class != nullptr) {
1031 mirror::Class* new_super_class = down_cast<mirror::Class*>(ForwardObject(super_class));
1032 if (new_super_class != super_class && IsInAppImage(new_super_class)) {
1033 // Recursively fix all dependencies.
1034 operator()(new_super_class);
1035 }
1036 }
1037 }
1038
Andreas Gampea463b6a2016-08-12 21:53:32 -07001039 obj->VisitReferences</*visit native roots*/false, kVerifyNone, kWithoutReadBarrier>(
1040 *this,
1041 *this);
1042 // Note that this code relies on no circular dependencies.
1043 // We want to use our own class loader and not the one in the image.
1044 if (obj->IsClass<kVerifyNone, kWithoutReadBarrier>()) {
1045 mirror::Class* as_klass = obj->AsClass<kVerifyNone, kWithoutReadBarrier>();
1046 FixupObjectAdapter visitor(boot_image_, boot_oat_, app_image_, app_oat_);
1047 as_klass->FixupNativePointers<kVerifyNone, kWithoutReadBarrier>(as_klass,
1048 pointer_size_,
1049 visitor);
1050 // Deal with the pointer arrays. Use the helper function since multiple classes can reference
1051 // the same arrays.
1052 mirror::PointerArray* const vtable = as_klass->GetVTable<kVerifyNone, kWithoutReadBarrier>();
1053 if (vtable != nullptr && IsInAppImage(vtable)) {
1054 operator()(vtable);
1055 UpdatePointerArrayContents(vtable, visitor);
1056 }
1057 mirror::IfTable* iftable = as_klass->GetIfTable<kVerifyNone, kWithoutReadBarrier>();
1058 // Ensure iftable arrays are fixed up since we need GetMethodArray to return the valid
1059 // contents.
Mathieu Chartier6beced42016-11-15 15:51:31 -08001060 if (IsInAppImage(iftable)) {
Andreas Gampea463b6a2016-08-12 21:53:32 -07001061 operator()(iftable);
1062 for (int32_t i = 0, count = iftable->Count(); i < count; ++i) {
1063 if (iftable->GetMethodArrayCount<kVerifyNone, kWithoutReadBarrier>(i) > 0) {
1064 mirror::PointerArray* methods =
1065 iftable->GetMethodArray<kVerifyNone, kWithoutReadBarrier>(i);
1066 if (visitor.IsInAppImage(methods)) {
1067 operator()(methods);
1068 DCHECK(methods != nullptr);
1069 UpdatePointerArrayContents(methods, visitor);
1070 }
Mathieu Chartier92ec5942016-04-11 12:03:48 -07001071 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001072 }
1073 }
1074 }
1075 }
Mathieu Chartier91edc622016-02-16 17:16:01 -08001076
Andreas Gampea463b6a2016-08-12 21:53:32 -07001077 private:
1078 const PointerSize pointer_size_;
1079 gc::accounting::ContinuousSpaceBitmap* const visited_;
1080 };
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001081
Andreas Gampea463b6a2016-08-12 21:53:32 -07001082 class ForwardObjectAdapter {
1083 public:
1084 ALWAYS_INLINE explicit ForwardObjectAdapter(const FixupVisitor* visitor) : visitor_(visitor) {}
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001085
Andreas Gampea463b6a2016-08-12 21:53:32 -07001086 template <typename T>
1087 ALWAYS_INLINE T* operator()(T* src) const {
1088 return visitor_->ForwardObject(src);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001089 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001090
Andreas Gampea463b6a2016-08-12 21:53:32 -07001091 private:
1092 const FixupVisitor* const visitor_;
1093 };
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001094
Andreas Gampea463b6a2016-08-12 21:53:32 -07001095 class ForwardCodeAdapter {
1096 public:
1097 ALWAYS_INLINE explicit ForwardCodeAdapter(const FixupVisitor* visitor)
1098 : visitor_(visitor) {}
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001099
Andreas Gampea463b6a2016-08-12 21:53:32 -07001100 template <typename T>
1101 ALWAYS_INLINE T* operator()(T* src) const {
1102 return visitor_->ForwardCode(src);
1103 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001104
Andreas Gampea463b6a2016-08-12 21:53:32 -07001105 private:
1106 const FixupVisitor* const visitor_;
1107 };
1108
1109 class FixupArtMethodVisitor : public FixupVisitor, public ArtMethodVisitor {
1110 public:
1111 template<typename... Args>
1112 explicit FixupArtMethodVisitor(bool fixup_heap_objects, PointerSize pointer_size, Args... args)
1113 : FixupVisitor(args...),
1114 fixup_heap_objects_(fixup_heap_objects),
1115 pointer_size_(pointer_size) {}
1116
1117 virtual void Visit(ArtMethod* method) NO_THREAD_SAFETY_ANALYSIS {
1118 // TODO: Separate visitor for runtime vs normal methods.
1119 if (UNLIKELY(method->IsRuntimeMethod())) {
1120 ImtConflictTable* table = method->GetImtConflictTable(pointer_size_);
1121 if (table != nullptr) {
1122 ImtConflictTable* new_table = ForwardObject(table);
1123 if (table != new_table) {
1124 method->SetImtConflictTable(new_table, pointer_size_);
1125 }
1126 }
1127 const void* old_code = method->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size_);
1128 const void* new_code = ForwardCode(old_code);
1129 if (old_code != new_code) {
1130 method->SetEntryPointFromQuickCompiledCodePtrSize(new_code, pointer_size_);
1131 }
1132 } else {
1133 if (fixup_heap_objects_) {
Vladimir Marko5122e6b2017-08-17 16:10:09 +01001134 method->UpdateObjectsForImageRelocation(ForwardObjectAdapter(this));
Andreas Gampea463b6a2016-08-12 21:53:32 -07001135 }
1136 method->UpdateEntrypoints<kWithoutReadBarrier>(ForwardCodeAdapter(this), pointer_size_);
1137 }
1138 }
1139
1140 private:
1141 const bool fixup_heap_objects_;
1142 const PointerSize pointer_size_;
1143 };
1144
1145 class FixupArtFieldVisitor : public FixupVisitor, public ArtFieldVisitor {
1146 public:
1147 template<typename... Args>
1148 explicit FixupArtFieldVisitor(Args... args) : FixupVisitor(args...) {}
1149
1150 virtual void Visit(ArtField* field) NO_THREAD_SAFETY_ANALYSIS {
1151 field->UpdateObjects(ForwardObjectAdapter(this));
1152 }
1153 };
1154
1155 // Relocate an image space mapped at target_base which possibly used to be at a different base
1156 // address. Only needs a single image space, not one for both source and destination.
1157 // In place means modifying a single ImageSpace in place rather than relocating from one ImageSpace
1158 // to another.
1159 static bool RelocateInPlace(ImageHeader& image_header,
1160 uint8_t* target_base,
1161 accounting::ContinuousSpaceBitmap* bitmap,
1162 const OatFile* app_oat_file,
1163 std::string* error_msg) {
1164 DCHECK(error_msg != nullptr);
1165 if (!image_header.IsPic()) {
1166 if (image_header.GetImageBegin() == target_base) {
1167 return true;
1168 }
1169 *error_msg = StringPrintf("Cannot relocate non-pic image for oat file %s",
1170 (app_oat_file != nullptr) ? app_oat_file->GetLocation().c_str() : "");
1171 return false;
1172 }
1173 // Set up sections.
1174 uint32_t boot_image_begin = 0;
1175 uint32_t boot_image_end = 0;
1176 uint32_t boot_oat_begin = 0;
1177 uint32_t boot_oat_end = 0;
1178 const PointerSize pointer_size = image_header.GetPointerSize();
1179 gc::Heap* const heap = Runtime::Current()->GetHeap();
1180 heap->GetBootImagesSize(&boot_image_begin, &boot_image_end, &boot_oat_begin, &boot_oat_end);
1181 if (boot_image_begin == boot_image_end) {
1182 *error_msg = "Can not relocate app image without boot image space";
1183 return false;
1184 }
1185 if (boot_oat_begin == boot_oat_end) {
1186 *error_msg = "Can not relocate app image without boot oat file";
1187 return false;
1188 }
1189 const uint32_t boot_image_size = boot_image_end - boot_image_begin;
1190 const uint32_t boot_oat_size = boot_oat_end - boot_oat_begin;
1191 const uint32_t image_header_boot_image_size = image_header.GetBootImageSize();
1192 const uint32_t image_header_boot_oat_size = image_header.GetBootOatSize();
1193 if (boot_image_size != image_header_boot_image_size) {
1194 *error_msg = StringPrintf("Boot image size %" PRIu64 " does not match expected size %"
1195 PRIu64,
1196 static_cast<uint64_t>(boot_image_size),
1197 static_cast<uint64_t>(image_header_boot_image_size));
1198 return false;
1199 }
1200 if (boot_oat_size != image_header_boot_oat_size) {
1201 *error_msg = StringPrintf("Boot oat size %" PRIu64 " does not match expected size %"
1202 PRIu64,
1203 static_cast<uint64_t>(boot_oat_size),
1204 static_cast<uint64_t>(image_header_boot_oat_size));
1205 return false;
1206 }
1207 TimingLogger logger(__FUNCTION__, true, false);
1208 RelocationRange boot_image(image_header.GetBootImageBegin(),
1209 boot_image_begin,
1210 boot_image_size);
1211 RelocationRange boot_oat(image_header.GetBootOatBegin(),
1212 boot_oat_begin,
1213 boot_oat_size);
1214 RelocationRange app_image(reinterpret_cast<uintptr_t>(image_header.GetImageBegin()),
1215 reinterpret_cast<uintptr_t>(target_base),
1216 image_header.GetImageSize());
1217 // Use the oat data section since this is where the OatFile::Begin is.
1218 RelocationRange app_oat(reinterpret_cast<uintptr_t>(image_header.GetOatDataBegin()),
1219 // Not necessarily in low 4GB.
1220 reinterpret_cast<uintptr_t>(app_oat_file->Begin()),
1221 image_header.GetOatDataEnd() - image_header.GetOatDataBegin());
1222 VLOG(image) << "App image " << app_image;
1223 VLOG(image) << "App oat " << app_oat;
1224 VLOG(image) << "Boot image " << boot_image;
1225 VLOG(image) << "Boot oat " << boot_oat;
1226 // True if we need to fixup any heap pointers, otherwise only code pointers.
1227 const bool fixup_image = boot_image.Delta() != 0 || app_image.Delta() != 0;
1228 const bool fixup_code = boot_oat.Delta() != 0 || app_oat.Delta() != 0;
1229 if (!fixup_image && !fixup_code) {
1230 // Nothing to fix up.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001231 return true;
1232 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07001233 ScopedDebugDisallowReadBarriers sddrb(Thread::Current());
1234 // Need to update the image to be at the target base.
Vladimir Markocd87c3e2017-09-05 13:11:57 +01001235 const ImageSection& objects_section = image_header.GetObjectsSection();
Andreas Gampea463b6a2016-08-12 21:53:32 -07001236 uintptr_t objects_begin = reinterpret_cast<uintptr_t>(target_base + objects_section.Offset());
1237 uintptr_t objects_end = reinterpret_cast<uintptr_t>(target_base + objects_section.End());
1238 FixupObjectAdapter fixup_adapter(boot_image, boot_oat, app_image, app_oat);
1239 if (fixup_image) {
1240 // Two pass approach, fix up all classes first, then fix up non class-objects.
1241 // The visited bitmap is used to ensure that pointer arrays are not forwarded twice.
1242 std::unique_ptr<gc::accounting::ContinuousSpaceBitmap> visited_bitmap(
1243 gc::accounting::ContinuousSpaceBitmap::Create("Relocate bitmap",
1244 target_base,
1245 image_header.GetImageSize()));
1246 FixupObjectVisitor fixup_object_visitor(visited_bitmap.get(),
1247 pointer_size,
1248 boot_image,
1249 boot_oat,
1250 app_image,
1251 app_oat);
1252 TimingLogger::ScopedTiming timing("Fixup classes", &logger);
1253 // Fixup objects may read fields in the boot image, use the mutator lock here for sanity. Though
1254 // its probably not required.
1255 ScopedObjectAccess soa(Thread::Current());
1256 timing.NewTiming("Fixup objects");
1257 bitmap->VisitMarkedRange(objects_begin, objects_end, fixup_object_visitor);
1258 // Fixup image roots.
1259 CHECK(app_image.InSource(reinterpret_cast<uintptr_t>(
1260 image_header.GetImageRoots<kWithoutReadBarrier>())));
1261 image_header.RelocateImageObjects(app_image.Delta());
1262 CHECK_EQ(image_header.GetImageBegin(), target_base);
1263 // Fix up dex cache DexFile pointers.
1264 auto* dex_caches = image_header.GetImageRoot<kWithoutReadBarrier>(ImageHeader::kDexCaches)->
1265 AsObjectArray<mirror::DexCache, kVerifyNone, kWithoutReadBarrier>();
1266 for (int32_t i = 0, count = dex_caches->GetLength(); i < count; ++i) {
1267 mirror::DexCache* dex_cache = dex_caches->Get<kVerifyNone, kWithoutReadBarrier>(i);
1268 // Fix up dex cache pointers.
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07001269 mirror::StringDexCacheType* strings = dex_cache->GetStrings();
Andreas Gampea463b6a2016-08-12 21:53:32 -07001270 if (strings != nullptr) {
Christina Wadsworthbf44e0e2016-08-18 10:37:42 -07001271 mirror::StringDexCacheType* new_strings = fixup_adapter.ForwardObject(strings);
Andreas Gampea463b6a2016-08-12 21:53:32 -07001272 if (strings != new_strings) {
1273 dex_cache->SetStrings(new_strings);
1274 }
1275 dex_cache->FixupStrings<kWithoutReadBarrier>(new_strings, fixup_adapter);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001276 }
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001277 mirror::TypeDexCacheType* types = dex_cache->GetResolvedTypes();
Andreas Gampea463b6a2016-08-12 21:53:32 -07001278 if (types != nullptr) {
Vladimir Marko8d6768d2017-03-14 10:13:21 +00001279 mirror::TypeDexCacheType* new_types = fixup_adapter.ForwardObject(types);
Andreas Gampea463b6a2016-08-12 21:53:32 -07001280 if (types != new_types) {
1281 dex_cache->SetResolvedTypes(new_types);
1282 }
1283 dex_cache->FixupResolvedTypes<kWithoutReadBarrier>(new_types, fixup_adapter);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001284 }
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001285 mirror::MethodDexCacheType* methods = dex_cache->GetResolvedMethods();
Andreas Gampea463b6a2016-08-12 21:53:32 -07001286 if (methods != nullptr) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001287 mirror::MethodDexCacheType* new_methods = fixup_adapter.ForwardObject(methods);
Andreas Gampea463b6a2016-08-12 21:53:32 -07001288 if (methods != new_methods) {
1289 dex_cache->SetResolvedMethods(new_methods);
1290 }
1291 for (size_t j = 0, num = dex_cache->NumResolvedMethods(); j != num; ++j) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001292 auto pair = mirror::DexCache::GetNativePairPtrSize(new_methods, j, pointer_size);
1293 ArtMethod* orig = pair.object;
Andreas Gampea463b6a2016-08-12 21:53:32 -07001294 ArtMethod* copy = fixup_adapter.ForwardObject(orig);
1295 if (orig != copy) {
Vladimir Marko07bfbac2017-07-06 14:55:02 +01001296 pair.object = copy;
1297 mirror::DexCache::SetNativePairPtrSize(new_methods, j, pair, pointer_size);
Andreas Gampea463b6a2016-08-12 21:53:32 -07001298 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001299 }
1300 }
Vladimir Markof44d36c2017-03-14 14:18:46 +00001301 mirror::FieldDexCacheType* fields = dex_cache->GetResolvedFields();
Andreas Gampea463b6a2016-08-12 21:53:32 -07001302 if (fields != nullptr) {
Vladimir Markof44d36c2017-03-14 14:18:46 +00001303 mirror::FieldDexCacheType* new_fields = fixup_adapter.ForwardObject(fields);
Andreas Gampea463b6a2016-08-12 21:53:32 -07001304 if (fields != new_fields) {
1305 dex_cache->SetResolvedFields(new_fields);
1306 }
1307 for (size_t j = 0, num = dex_cache->NumResolvedFields(); j != num; ++j) {
Vladimir Markof44d36c2017-03-14 14:18:46 +00001308 mirror::FieldDexCachePair orig =
1309 mirror::DexCache::GetNativePairPtrSize(new_fields, j, pointer_size);
1310 mirror::FieldDexCachePair copy(fixup_adapter.ForwardObject(orig.object), orig.index);
1311 if (orig.object != copy.object) {
1312 mirror::DexCache::SetNativePairPtrSize(new_fields, j, copy, pointer_size);
Andreas Gampea463b6a2016-08-12 21:53:32 -07001313 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001314 }
1315 }
Narayan Kamath7fe56582016-10-14 18:49:12 +01001316
1317 mirror::MethodTypeDexCacheType* method_types = dex_cache->GetResolvedMethodTypes();
1318 if (method_types != nullptr) {
1319 mirror::MethodTypeDexCacheType* new_method_types =
1320 fixup_adapter.ForwardObject(method_types);
1321 if (method_types != new_method_types) {
1322 dex_cache->SetResolvedMethodTypes(new_method_types);
1323 }
1324 dex_cache->FixupResolvedMethodTypes<kWithoutReadBarrier>(new_method_types, fixup_adapter);
1325 }
Orion Hodsonc069a302017-01-18 09:23:12 +00001326 GcRoot<mirror::CallSite>* call_sites = dex_cache->GetResolvedCallSites();
1327 if (call_sites != nullptr) {
1328 GcRoot<mirror::CallSite>* new_call_sites = fixup_adapter.ForwardObject(call_sites);
1329 if (call_sites != new_call_sites) {
1330 dex_cache->SetResolvedCallSites(new_call_sites);
1331 }
1332 dex_cache->FixupResolvedCallSites<kWithoutReadBarrier>(new_call_sites, fixup_adapter);
1333 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001334 }
1335 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001336 {
1337 // Only touches objects in the app image, no need for mutator lock.
Andreas Gampea463b6a2016-08-12 21:53:32 -07001338 TimingLogger::ScopedTiming timing("Fixup methods", &logger);
1339 FixupArtMethodVisitor method_visitor(fixup_image,
1340 pointer_size,
1341 boot_image,
1342 boot_oat,
1343 app_image,
1344 app_oat);
1345 image_header.VisitPackedArtMethods(&method_visitor, target_base, pointer_size);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001346 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07001347 if (fixup_image) {
1348 {
1349 // Only touches objects in the app image, no need for mutator lock.
1350 TimingLogger::ScopedTiming timing("Fixup fields", &logger);
1351 FixupArtFieldVisitor field_visitor(boot_image, boot_oat, app_image, app_oat);
1352 image_header.VisitPackedArtFields(&field_visitor, target_base);
1353 }
1354 {
1355 TimingLogger::ScopedTiming timing("Fixup imt", &logger);
1356 image_header.VisitPackedImTables(fixup_adapter, target_base, pointer_size);
1357 }
1358 {
1359 TimingLogger::ScopedTiming timing("Fixup conflict tables", &logger);
1360 image_header.VisitPackedImtConflictTables(fixup_adapter, target_base, pointer_size);
1361 }
1362 // In the app image case, the image methods are actually in the boot image.
1363 image_header.RelocateImageMethods(boot_image.Delta());
Vladimir Markocd87c3e2017-09-05 13:11:57 +01001364 const auto& class_table_section = image_header.GetClassTableSection();
Andreas Gampea463b6a2016-08-12 21:53:32 -07001365 if (class_table_section.Size() > 0u) {
1366 // Note that we require that ReadFromMemory does not make an internal copy of the elements.
1367 // This also relies on visit roots not doing any verification which could fail after we update
1368 // the roots to be the image addresses.
1369 ScopedObjectAccess soa(Thread::Current());
1370 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
1371 ClassTable temp_table;
1372 temp_table.ReadFromMemory(target_base + class_table_section.Offset());
1373 FixupRootVisitor root_visitor(boot_image, boot_oat, app_image, app_oat);
1374 temp_table.VisitRoots(root_visitor);
1375 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001376 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07001377 if (VLOG_IS_ON(image)) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07001378 logger.Dump(LOG_STREAM(INFO));
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001379 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07001380 return true;
Andreas Gampe7fa55782016-06-15 17:45:01 -07001381 }
1382
Andreas Gampea463b6a2016-08-12 21:53:32 -07001383 static std::unique_ptr<OatFile> OpenOatFile(const ImageSpace& image,
1384 const char* image_path,
1385 std::string* error_msg) {
1386 const ImageHeader& image_header = image.GetImageHeader();
1387 std::string oat_filename = ImageHeader::GetOatLocationFromImageLocation(image_path);
Andreas Gampe7fa55782016-06-15 17:45:01 -07001388
Andreas Gampea463b6a2016-08-12 21:53:32 -07001389 CHECK(image_header.GetOatDataBegin() != nullptr);
1390
1391 std::unique_ptr<OatFile> oat_file(OatFile::Open(oat_filename,
1392 oat_filename,
1393 image_header.GetOatDataBegin(),
1394 image_header.GetOatFileBegin(),
1395 !Runtime::Current()->IsAotCompiler(),
1396 /*low_4gb*/false,
1397 nullptr,
1398 error_msg));
1399 if (oat_file == nullptr) {
1400 *error_msg = StringPrintf("Failed to open oat file '%s' referenced from image %s: %s",
1401 oat_filename.c_str(),
1402 image.GetName(),
1403 error_msg->c_str());
Andreas Gampe7fa55782016-06-15 17:45:01 -07001404 return nullptr;
1405 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07001406 uint32_t oat_checksum = oat_file->GetOatHeader().GetChecksum();
1407 uint32_t image_oat_checksum = image_header.GetOatChecksum();
Mathieu Chartier9ff84602016-01-29 12:22:17 -08001408 if (oat_checksum != image_oat_checksum) {
Andreas Gampea463b6a2016-08-12 21:53:32 -07001409 *error_msg = StringPrintf("Failed to match oat file checksum 0x%x to expected oat checksum 0x%x"
1410 " in image %s",
Mathieu Chartier9ff84602016-01-29 12:22:17 -08001411 oat_checksum,
1412 image_oat_checksum,
Andreas Gampea463b6a2016-08-12 21:53:32 -07001413 image.GetName());
Mathieu Chartier9ff84602016-01-29 12:22:17 -08001414 return nullptr;
1415 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07001416 int32_t image_patch_delta = image_header.GetPatchDelta();
1417 int32_t oat_patch_delta = oat_file->GetOatHeader().GetImagePatchDelta();
1418 if (oat_patch_delta != image_patch_delta && !image_header.CompilePic()) {
1419 // We should have already relocated by this point. Bail out.
1420 *error_msg = StringPrintf("Failed to match oat file patch delta %d to expected patch delta %d "
1421 "in image %s",
1422 oat_patch_delta,
1423 image_patch_delta,
1424 image.GetName());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001425 return nullptr;
1426 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07001427
1428 return oat_file;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001429 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07001430};
Hiroshi Yamauchibd0fb612014-05-20 13:46:00 -07001431
Andreas Gampea463b6a2016-08-12 21:53:32 -07001432static constexpr uint64_t kLowSpaceValue = 50 * MB;
1433static constexpr uint64_t kTmpFsSentinelValue = 384 * MB;
1434
1435// Read the free space of the cache partition and make a decision whether to keep the generated
1436// image. This is to try to mitigate situations where the system might run out of space later.
1437static bool CheckSpace(const std::string& cache_filename, std::string* error_msg) {
1438 // Using statvfs vs statvfs64 because of b/18207376, and it is enough for all practical purposes.
1439 struct statvfs buf;
1440
1441 int res = TEMP_FAILURE_RETRY(statvfs(cache_filename.c_str(), &buf));
1442 if (res != 0) {
1443 // Could not stat. Conservatively tell the system to delete the image.
1444 *error_msg = "Could not stat the filesystem, assuming low-memory situation.";
1445 return false;
Nicolas Geoffray1bc977c2016-01-23 14:15:49 +00001446 }
Nicolas Geoffray1bc977c2016-01-23 14:15:49 +00001447
Andreas Gampea463b6a2016-08-12 21:53:32 -07001448 uint64_t fs_overall_size = buf.f_bsize * static_cast<uint64_t>(buf.f_blocks);
1449 // Zygote is privileged, but other things are not. Use bavail.
1450 uint64_t fs_free_size = buf.f_bsize * static_cast<uint64_t>(buf.f_bavail);
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001451
Andreas Gampea463b6a2016-08-12 21:53:32 -07001452 // Take the overall size as an indicator for a tmpfs, which is being used for the decryption
1453 // environment. We do not want to fail quickening the boot image there, as it is beneficial
1454 // for time-to-UI.
1455 if (fs_overall_size > kTmpFsSentinelValue) {
1456 if (fs_free_size < kLowSpaceValue) {
1457 *error_msg = StringPrintf("Low-memory situation: only %4.2f megabytes available, need at "
1458 "least %" PRIu64 ".",
1459 static_cast<double>(fs_free_size) / MB,
1460 kLowSpaceValue / MB);
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001461 return false;
1462 }
1463 }
1464 return true;
1465}
1466
Andreas Gampea463b6a2016-08-12 21:53:32 -07001467std::unique_ptr<ImageSpace> ImageSpace::CreateBootImage(const char* image_location,
1468 const InstructionSet image_isa,
1469 bool secondary_image,
1470 std::string* error_msg) {
1471 ScopedTrace trace(__FUNCTION__);
1472
1473 // Step 0: Extra zygote work.
1474
1475 // Step 0.a: If we're the zygote, mark boot.
1476 const bool is_zygote = Runtime::Current()->IsZygote();
Robert Sesekbfa1f8d2016-08-15 15:21:09 -04001477 if (is_zygote && !secondary_image && CanWriteToDalvikCache(image_isa)) {
Andreas Gampea463b6a2016-08-12 21:53:32 -07001478 MarkZygoteStart(image_isa, Runtime::Current()->GetZygoteMaxFailedBoots());
1479 }
1480
1481 // Step 0.b: If we're the zygote, check for free space, and prune the cache preemptively,
1482 // if necessary. While the runtime may be fine (it is pretty tolerant to
1483 // out-of-disk-space situations), other parts of the platform are not.
1484 //
1485 // The advantage of doing this proactively is that the later steps are simplified,
1486 // i.e., we do not need to code retries.
1487 std::string system_filename;
1488 bool has_system = false;
1489 std::string cache_filename;
1490 bool has_cache = false;
1491 bool dalvik_cache_exists = false;
1492 bool is_global_cache = true;
1493 std::string dalvik_cache;
1494 bool found_image = FindImageFilenameImpl(image_location,
1495 image_isa,
1496 &has_system,
1497 &system_filename,
1498 &dalvik_cache_exists,
1499 &dalvik_cache,
1500 &is_global_cache,
1501 &has_cache,
1502 &cache_filename);
1503
1504 if (is_zygote && dalvik_cache_exists) {
1505 DCHECK(!dalvik_cache.empty());
1506 std::string local_error_msg;
1507 if (!CheckSpace(dalvik_cache, &local_error_msg)) {
1508 LOG(WARNING) << local_error_msg << " Preemptively pruning the dalvik cache.";
1509 PruneDalvikCache(image_isa);
1510
1511 // Re-evaluate the image.
1512 found_image = FindImageFilenameImpl(image_location,
1513 image_isa,
1514 &has_system,
1515 &system_filename,
1516 &dalvik_cache_exists,
1517 &dalvik_cache,
1518 &is_global_cache,
1519 &has_cache,
1520 &cache_filename);
1521 }
1522 }
1523
1524 // Collect all the errors.
1525 std::vector<std::string> error_msgs;
1526
1527 // Step 1: Check if we have an existing and relocated image.
1528
1529 // Step 1.a: Have files in system and cache. Then they need to match.
1530 if (found_image && has_system && has_cache) {
1531 std::string local_error_msg;
1532 // Check that the files are matching.
1533 if (ChecksumsMatch(system_filename.c_str(), cache_filename.c_str(), &local_error_msg)) {
1534 std::unique_ptr<ImageSpace> relocated_space =
1535 ImageSpaceLoader::Load(image_location,
1536 cache_filename,
1537 is_zygote,
1538 is_global_cache,
Andreas Gampe44c8ed62016-08-19 16:43:00 -07001539 /* validate_oat_file */ false,
Andreas Gampea463b6a2016-08-12 21:53:32 -07001540 &local_error_msg);
1541 if (relocated_space != nullptr) {
1542 return relocated_space;
1543 }
1544 }
1545 error_msgs.push_back(local_error_msg);
1546 }
1547
1548 // Step 1.b: Only have a cache file.
1549 if (found_image && !has_system && has_cache) {
1550 std::string local_error_msg;
1551 std::unique_ptr<ImageSpace> cache_space =
1552 ImageSpaceLoader::Load(image_location,
1553 cache_filename,
1554 is_zygote,
1555 is_global_cache,
Andreas Gampe44c8ed62016-08-19 16:43:00 -07001556 /* validate_oat_file */ true,
Andreas Gampea463b6a2016-08-12 21:53:32 -07001557 &local_error_msg);
1558 if (cache_space != nullptr) {
1559 return cache_space;
1560 }
1561 error_msgs.push_back(local_error_msg);
1562 }
1563
1564 // Step 2: We have an existing image in /system.
1565
1566 // Step 2.a: We are not required to relocate it. Then we can use it directly.
1567 bool relocate = Runtime::Current()->ShouldRelocate();
1568
1569 if (found_image && has_system && !relocate) {
1570 std::string local_error_msg;
1571 std::unique_ptr<ImageSpace> system_space =
1572 ImageSpaceLoader::Load(image_location,
1573 system_filename,
1574 is_zygote,
1575 is_global_cache,
Andreas Gampe44c8ed62016-08-19 16:43:00 -07001576 /* validate_oat_file */ false,
Andreas Gampea463b6a2016-08-12 21:53:32 -07001577 &local_error_msg);
1578 if (system_space != nullptr) {
1579 return system_space;
1580 }
1581 error_msgs.push_back(local_error_msg);
1582 }
1583
1584 // Step 2.b: We require a relocated image. Then we must patch it. This step fails if this is a
1585 // secondary image.
1586 if (found_image && has_system && relocate) {
1587 std::string local_error_msg;
1588 if (!Runtime::Current()->IsImageDex2OatEnabled()) {
1589 local_error_msg = "Patching disabled.";
1590 } else if (secondary_image) {
Andreas Gampe8d8a0052017-12-12 12:03:04 -08001591 // We really want a working image. Prune and restart.
1592 PruneDalvikCache(image_isa);
1593 _exit(1);
Robert Sesekbfa1f8d2016-08-15 15:21:09 -04001594 } else if (ImageCreationAllowed(is_global_cache, image_isa, &local_error_msg)) {
Andreas Gampea463b6a2016-08-12 21:53:32 -07001595 bool patch_success =
1596 RelocateImage(image_location, cache_filename.c_str(), image_isa, &local_error_msg);
1597 if (patch_success) {
1598 std::unique_ptr<ImageSpace> patched_space =
1599 ImageSpaceLoader::Load(image_location,
1600 cache_filename,
1601 is_zygote,
1602 is_global_cache,
Andreas Gampe44c8ed62016-08-19 16:43:00 -07001603 /* validate_oat_file */ false,
Andreas Gampea463b6a2016-08-12 21:53:32 -07001604 &local_error_msg);
1605 if (patched_space != nullptr) {
1606 return patched_space;
1607 }
1608 }
1609 }
1610 error_msgs.push_back(StringPrintf("Cannot relocate image %s to %s: %s",
1611 image_location,
1612 cache_filename.c_str(),
1613 local_error_msg.c_str()));
1614 }
1615
1616 // Step 3: We do not have an existing image in /system, so generate an image into the dalvik
1617 // cache. This step fails if this is a secondary image.
1618 if (!has_system) {
1619 std::string local_error_msg;
1620 if (!Runtime::Current()->IsImageDex2OatEnabled()) {
1621 local_error_msg = "Image compilation disabled.";
1622 } else if (secondary_image) {
1623 local_error_msg = "Cannot compile a secondary image.";
Robert Sesekbfa1f8d2016-08-15 15:21:09 -04001624 } else if (ImageCreationAllowed(is_global_cache, image_isa, &local_error_msg)) {
Andreas Gampea463b6a2016-08-12 21:53:32 -07001625 bool compilation_success = GenerateImage(cache_filename, image_isa, &local_error_msg);
1626 if (compilation_success) {
1627 std::unique_ptr<ImageSpace> compiled_space =
1628 ImageSpaceLoader::Load(image_location,
1629 cache_filename,
1630 is_zygote,
1631 is_global_cache,
Andreas Gampe44c8ed62016-08-19 16:43:00 -07001632 /* validate_oat_file */ false,
Andreas Gampea463b6a2016-08-12 21:53:32 -07001633 &local_error_msg);
1634 if (compiled_space != nullptr) {
1635 return compiled_space;
1636 }
1637 }
1638 }
1639 error_msgs.push_back(StringPrintf("Cannot compile image to %s: %s",
1640 cache_filename.c_str(),
1641 local_error_msg.c_str()));
1642 }
1643
1644 // We failed. Prune the cache the free up space, create a compound error message and return no
1645 // image.
1646 PruneDalvikCache(image_isa);
1647
1648 std::ostringstream oss;
1649 bool first = true;
Andreas Gampe4c481a42016-11-03 08:21:59 -07001650 for (const auto& msg : error_msgs) {
Andreas Gampea463b6a2016-08-12 21:53:32 -07001651 if (!first) {
1652 oss << "\n ";
1653 }
1654 oss << msg;
1655 }
1656 *error_msg = oss.str();
1657
1658 return nullptr;
1659}
1660
Andreas Gampe2bd84282016-12-05 12:37:36 -08001661bool ImageSpace::LoadBootImage(const std::string& image_file_name,
1662 const InstructionSet image_instruction_set,
1663 std::vector<space::ImageSpace*>* boot_image_spaces,
1664 uint8_t** oat_file_end) {
1665 DCHECK(boot_image_spaces != nullptr);
1666 DCHECK(boot_image_spaces->empty());
1667 DCHECK(oat_file_end != nullptr);
1668 DCHECK_NE(image_instruction_set, InstructionSet::kNone);
1669
1670 if (image_file_name.empty()) {
1671 return false;
1672 }
1673
1674 // For code reuse, handle this like a work queue.
1675 std::vector<std::string> image_file_names;
1676 image_file_names.push_back(image_file_name);
1677
1678 bool error = false;
1679 uint8_t* oat_file_end_tmp = *oat_file_end;
1680
1681 for (size_t index = 0; index < image_file_names.size(); ++index) {
1682 std::string& image_name = image_file_names[index];
1683 std::string error_msg;
1684 std::unique_ptr<space::ImageSpace> boot_image_space_uptr = CreateBootImage(
1685 image_name.c_str(),
1686 image_instruction_set,
1687 index > 0,
1688 &error_msg);
1689 if (boot_image_space_uptr != nullptr) {
1690 space::ImageSpace* boot_image_space = boot_image_space_uptr.release();
1691 boot_image_spaces->push_back(boot_image_space);
1692 // Oat files referenced by image files immediately follow them in memory, ensure alloc space
1693 // isn't going to get in the middle
1694 uint8_t* oat_file_end_addr = boot_image_space->GetImageHeader().GetOatFileEnd();
1695 CHECK_GT(oat_file_end_addr, boot_image_space->End());
1696 oat_file_end_tmp = AlignUp(oat_file_end_addr, kPageSize);
1697
1698 if (index == 0) {
1699 // If this was the first space, check whether there are more images to load.
1700 const OatFile* boot_oat_file = boot_image_space->GetOatFile();
1701 if (boot_oat_file == nullptr) {
1702 continue;
1703 }
1704
1705 const OatHeader& boot_oat_header = boot_oat_file->GetOatHeader();
1706 const char* boot_classpath =
1707 boot_oat_header.GetStoreValueByKey(OatHeader::kBootClassPathKey);
1708 if (boot_classpath == nullptr) {
1709 continue;
1710 }
1711
1712 ExtractMultiImageLocations(image_file_name, boot_classpath, &image_file_names);
1713 }
1714 } else {
1715 error = true;
1716 LOG(ERROR) << "Could not create image space with image file '" << image_file_name << "'. "
1717 << "Attempting to fall back to imageless running. Error was: " << error_msg
1718 << "\nAttempted image: " << image_name;
1719 break;
1720 }
1721 }
1722
1723 if (error) {
1724 // Remove already loaded spaces.
1725 for (space::Space* loaded_space : *boot_image_spaces) {
1726 delete loaded_space;
1727 }
1728 boot_image_spaces->clear();
1729 return false;
1730 }
1731
1732 *oat_file_end = oat_file_end_tmp;
1733 return true;
1734}
1735
Igor Murashkin8275fba2017-05-02 15:58:02 -07001736ImageSpace::~ImageSpace() {
1737 Runtime* runtime = Runtime::Current();
1738 if (runtime == nullptr) {
1739 return;
1740 }
1741
1742 if (GetImageHeader().IsAppImage()) {
1743 // This image space did not modify resolution method then in Init.
1744 return;
1745 }
1746
1747 if (!runtime->HasResolutionMethod()) {
1748 // Another image space has already unloaded the below methods.
1749 return;
1750 }
1751
1752 runtime->ClearInstructionSet();
1753 runtime->ClearResolutionMethod();
1754 runtime->ClearImtConflictMethod();
1755 runtime->ClearImtUnimplementedMethod();
1756 runtime->ClearCalleeSaveMethods();
1757}
1758
Andreas Gampea463b6a2016-08-12 21:53:32 -07001759std::unique_ptr<ImageSpace> ImageSpace::CreateFromAppImage(const char* image,
1760 const OatFile* oat_file,
1761 std::string* error_msg) {
1762 return ImageSpaceLoader::Init(image,
1763 image,
1764 /*validate_oat_file*/false,
1765 oat_file,
1766 /*out*/error_msg);
1767}
1768
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001769const OatFile* ImageSpace::GetOatFile() const {
Andreas Gampe88da3b02015-06-12 20:38:49 -07001770 return oat_file_non_owned_;
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001771}
1772
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -07001773std::unique_ptr<const OatFile> ImageSpace::ReleaseOatFile() {
1774 CHECK(oat_file_ != nullptr);
1775 return std::move(oat_file_);
Ian Rogers1d54e732013-05-02 21:10:01 -07001776}
1777
Ian Rogers1d54e732013-05-02 21:10:01 -07001778void ImageSpace::Dump(std::ostream& os) const {
1779 os << GetType()
Mathieu Chartier590fee92013-09-13 13:46:47 -07001780 << " begin=" << reinterpret_cast<void*>(Begin())
Ian Rogers1d54e732013-05-02 21:10:01 -07001781 << ",end=" << reinterpret_cast<void*>(End())
1782 << ",size=" << PrettySize(Size())
1783 << ",name=\"" << GetName() << "\"]";
1784}
1785
Mathieu Chartier866d8742016-09-21 15:24:18 -07001786std::string ImageSpace::GetMultiImageBootClassPath(
1787 const std::vector<const char*>& dex_locations,
1788 const std::vector<const char*>& oat_filenames,
1789 const std::vector<const char*>& image_filenames) {
1790 DCHECK_GT(oat_filenames.size(), 1u);
1791 // If the image filename was adapted (e.g., for our tests), we need to change this here,
1792 // too, but need to strip all path components (they will be re-established when loading).
1793 std::ostringstream bootcp_oss;
1794 bool first_bootcp = true;
1795 for (size_t i = 0; i < dex_locations.size(); ++i) {
1796 if (!first_bootcp) {
1797 bootcp_oss << ":";
1798 }
1799
1800 std::string dex_loc = dex_locations[i];
1801 std::string image_filename = image_filenames[i];
1802
1803 // Use the dex_loc path, but the image_filename name (without path elements).
1804 size_t dex_last_slash = dex_loc.rfind('/');
1805
1806 // npos is max(size_t). That makes this a bit ugly.
1807 size_t image_last_slash = image_filename.rfind('/');
1808 size_t image_last_at = image_filename.rfind('@');
1809 size_t image_last_sep = (image_last_slash == std::string::npos)
1810 ? image_last_at
1811 : (image_last_at == std::string::npos)
1812 ? std::string::npos
1813 : std::max(image_last_slash, image_last_at);
1814 // Note: whenever image_last_sep == npos, +1 overflow means using the full string.
1815
1816 if (dex_last_slash == std::string::npos) {
1817 dex_loc = image_filename.substr(image_last_sep + 1);
1818 } else {
1819 dex_loc = dex_loc.substr(0, dex_last_slash + 1) +
1820 image_filename.substr(image_last_sep + 1);
1821 }
1822
1823 // Image filenames already end with .art, no need to replace.
1824
1825 bootcp_oss << dex_loc;
1826 first_bootcp = false;
1827 }
1828 return bootcp_oss.str();
1829}
1830
Richard Uhler84f50ae2017-02-06 15:12:45 +00001831bool ImageSpace::ValidateOatFile(const OatFile& oat_file, std::string* error_msg) {
David Sehr013fd802018-01-11 22:55:24 -08001832 const ArtDexFileLoader dex_file_loader;
Richard Uhler84f50ae2017-02-06 15:12:45 +00001833 for (const OatFile::OatDexFile* oat_dex_file : oat_file.GetOatDexFiles()) {
1834 const std::string& dex_file_location = oat_dex_file->GetDexFileLocation();
1835
1836 // Skip multidex locations - These will be checked when we visit their
1837 // corresponding primary non-multidex location.
Mathieu Chartier79c87da2017-10-10 11:54:29 -07001838 if (DexFileLoader::IsMultiDexLocation(dex_file_location.c_str())) {
Richard Uhler84f50ae2017-02-06 15:12:45 +00001839 continue;
1840 }
1841
1842 std::vector<uint32_t> checksums;
David Sehr013fd802018-01-11 22:55:24 -08001843 if (!dex_file_loader.GetMultiDexChecksums(dex_file_location.c_str(), &checksums, error_msg)) {
Richard Uhler84f50ae2017-02-06 15:12:45 +00001844 *error_msg = StringPrintf("ValidateOatFile failed to get checksums of dex file '%s' "
1845 "referenced by oat file %s: %s",
1846 dex_file_location.c_str(),
1847 oat_file.GetLocation().c_str(),
1848 error_msg->c_str());
1849 return false;
1850 }
1851 CHECK(!checksums.empty());
1852 if (checksums[0] != oat_dex_file->GetDexFileLocationChecksum()) {
1853 *error_msg = StringPrintf("ValidateOatFile found checksum mismatch between oat file "
1854 "'%s' and dex file '%s' (0x%x != 0x%x)",
1855 oat_file.GetLocation().c_str(),
1856 dex_file_location.c_str(),
1857 oat_dex_file->GetDexFileLocationChecksum(),
1858 checksums[0]);
1859 return false;
1860 }
1861
1862 // Verify checksums for any related multidex entries.
1863 for (size_t i = 1; i < checksums.size(); i++) {
Mathieu Chartier79c87da2017-10-10 11:54:29 -07001864 std::string multi_dex_location = DexFileLoader::GetMultiDexLocation(
1865 i,
1866 dex_file_location.c_str());
Richard Uhler84f50ae2017-02-06 15:12:45 +00001867 const OatFile::OatDexFile* multi_dex = oat_file.GetOatDexFile(multi_dex_location.c_str(),
1868 nullptr,
1869 error_msg);
1870 if (multi_dex == nullptr) {
1871 *error_msg = StringPrintf("ValidateOatFile oat file '%s' is missing entry '%s'",
1872 oat_file.GetLocation().c_str(),
1873 multi_dex_location.c_str());
1874 return false;
1875 }
1876
1877 if (checksums[i] != multi_dex->GetDexFileLocationChecksum()) {
1878 *error_msg = StringPrintf("ValidateOatFile found checksum mismatch between oat file "
1879 "'%s' and dex file '%s' (0x%x != 0x%x)",
1880 oat_file.GetLocation().c_str(),
1881 multi_dex_location.c_str(),
1882 multi_dex->GetDexFileLocationChecksum(),
1883 checksums[i]);
1884 return false;
1885 }
1886 }
1887 }
1888 return true;
1889}
1890
Mathieu Chartier866d8742016-09-21 15:24:18 -07001891void ImageSpace::ExtractMultiImageLocations(const std::string& input_image_file_name,
1892 const std::string& boot_classpath,
1893 std::vector<std::string>* image_file_names) {
Andreas Gampe8994a042015-12-30 19:03:17 +00001894 DCHECK(image_file_names != nullptr);
1895
1896 std::vector<std::string> images;
1897 Split(boot_classpath, ':', &images);
1898
1899 // Add the rest into the list. We have to adjust locations, possibly:
1900 //
1901 // For example, image_file_name is /a/b/c/d/e.art
1902 // images[0] is f/c/d/e.art
1903 // ----------------------------------------------
1904 // images[1] is g/h/i/j.art -> /a/b/h/i/j.art
Mathieu Chartier8b8f6d62016-03-08 16:50:20 -08001905 const std::string& first_image = images[0];
1906 // Length of common suffix.
1907 size_t common = 0;
1908 while (common < input_image_file_name.size() &&
1909 common < first_image.size() &&
1910 *(input_image_file_name.end() - common - 1) == *(first_image.end() - common - 1)) {
1911 ++common;
Andreas Gampe8994a042015-12-30 19:03:17 +00001912 }
Mathieu Chartier8b8f6d62016-03-08 16:50:20 -08001913 // We want to replace the prefix of the input image with the prefix of the boot class path.
1914 // This handles the case where the image file contains @ separators.
1915 // Example image_file_name is oats/system@framework@boot.art
1916 // images[0] is .../arm/boot.art
1917 // means that the image name prefix will be oats/system@framework@
1918 // so that the other images are openable.
1919 const size_t old_prefix_length = first_image.size() - common;
1920 const std::string new_prefix = input_image_file_name.substr(
1921 0,
1922 input_image_file_name.size() - common);
Andreas Gampe8994a042015-12-30 19:03:17 +00001923
1924 // Apply pattern to images[1] .. images[n].
1925 for (size_t i = 1; i < images.size(); ++i) {
Mathieu Chartier8b8f6d62016-03-08 16:50:20 -08001926 const std::string& image = images[i];
1927 CHECK_GT(image.length(), old_prefix_length);
1928 std::string suffix = image.substr(old_prefix_length);
1929 image_file_names->push_back(new_prefix + suffix);
Andreas Gampe8994a042015-12-30 19:03:17 +00001930 }
1931}
1932
Mathieu Chartierd5f3f322016-03-21 14:05:56 -07001933void ImageSpace::DumpSections(std::ostream& os) const {
1934 const uint8_t* base = Begin();
1935 const ImageHeader& header = GetImageHeader();
1936 for (size_t i = 0; i < ImageHeader::kSectionCount; ++i) {
1937 auto section_type = static_cast<ImageHeader::ImageSections>(i);
1938 const ImageSection& section = header.GetImageSection(section_type);
1939 os << section_type << " " << reinterpret_cast<const void*>(base + section.Offset())
1940 << "-" << reinterpret_cast<const void*>(base + section.End()) << "\n";
1941 }
1942}
1943
Ian Rogers1d54e732013-05-02 21:10:01 -07001944} // namespace space
1945} // namespace gc
1946} // namespace art