blob: 5ebd4b36a323a5a8911f23557bffc5a5bda89bd8 [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
Andreas Gampe70be1fb2014-10-31 16:45:19 -070019#include <sys/statvfs.h>
Alex Light25396132014-08-27 15:37:23 -070020#include <sys/types.h>
Narayan Kamath5a2be3f2015-02-16 13:51:51 +000021#include <unistd.h>
Alex Light25396132014-08-27 15:37:23 -070022
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070023#include <random>
24
Andreas Gampe46ee31b2016-12-14 10:11:49 -080025#include "android-base/stringprintf.h"
Andreas Gampe9186ced2016-12-12 14:28:21 -080026#include "android-base/strings.h"
27
Andreas Gampe639b2b12019-01-08 10:32:50 -080028#include "arch/instruction_set.h"
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"
Vladimir Marko0ace5632018-12-14 11:11:47 +000031#include "base/array_ref.h"
Vladimir Marko4df2d802018-09-27 16:42:44 +000032#include "base/bit_memory_region.h"
Andreas Gampe8228cdf2017-05-30 15:03:54 -070033#include "base/callee_save_type.h"
Andreas Gampe542451c2016-07-26 09:02:02 -070034#include "base/enums.h"
David Sehr891a50e2017-10-27 17:01:07 -070035#include "base/file_utils.h"
Ian Rogersc7dd2952014-10-21 23:31:19 -070036#include "base/macros.h"
David Sehrc431b9d2018-03-02 12:01:51 -080037#include "base/os.h"
Narayan Kamathd1c606f2014-06-09 16:50:19 +010038#include "base/scoped_flock.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070039#include "base/stl_util.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080040#include "base/systrace.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010041#include "base/time_utils.h"
David Sehrc431b9d2018-03-02 12:01:51 -080042#include "base/utils.h"
Vladimir Marko4df2d802018-09-27 16:42:44 +000043#include "class_root.h"
David Sehr013fd802018-01-11 22:55:24 -080044#include "dex/art_dex_file_loader.h"
David Sehr9e734c72018-01-04 17:56:19 -080045#include "dex/dex_file_loader.h"
David Sehr97c381e2017-02-01 15:09:58 -080046#include "exec_utils.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070047#include "gc/accounting/space_bitmap-inl.h"
Mathieu Chartier93c21ba2018-12-10 13:08:30 -080048#include "gc/task_processor.h"
Mathieu Chartier4a26f172016-01-26 14:26:18 -080049#include "image-inl.h"
Andreas Gampebec63582015-11-20 19:26:51 -080050#include "image_space_fs.h"
Mathieu Chartier74ccee62018-10-10 10:30:29 -070051#include "intern_table-inl.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070052#include "mirror/class-inl.h"
Vladimir Marko4df2d802018-09-27 16:42:44 +000053#include "mirror/executable.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070054#include "mirror/object-inl.h"
Andreas Gampec6ea7d02017-02-01 16:46:28 -080055#include "mirror/object-refvisitor-inl.h"
Brian Carlstrom56d947f2013-07-15 13:14:23 -070056#include "oat_file.h"
Andreas Gamped482e732017-04-24 17:59:09 -070057#include "runtime.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070058#include "space-inl.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070059
60namespace art {
61namespace gc {
62namespace space {
63
Vladimir Marko0ace5632018-12-14 11:11:47 +000064using android::base::StringAppendF;
Andreas Gampe46ee31b2016-12-14 10:11:49 -080065using android::base::StringPrintf;
66
Ian Rogersef7d42f2014-01-06 12:55:46 -080067Atomic<uint32_t> ImageSpace::bitmap_index_(0);
Ian Rogers1d54e732013-05-02 21:10:01 -070068
Jeff Haodcdc85b2015-12-04 14:06:18 -080069ImageSpace::ImageSpace(const std::string& image_filename,
70 const char* image_location,
Vladimir Markoc34bebf2018-08-16 16:12:49 +010071 MemMap&& mem_map,
Vladimir Markoc09cd052018-08-23 16:36:36 +010072 std::unique_ptr<accounting::ContinuousSpaceBitmap> live_bitmap,
Mathieu Chartier2d124ec2016-01-05 18:03:15 -080073 uint8_t* end)
74 : MemMapSpace(image_filename,
Vladimir Markoc34bebf2018-08-16 16:12:49 +010075 std::move(mem_map),
76 mem_map.Begin(),
Mathieu Chartier2d124ec2016-01-05 18:03:15 -080077 end,
78 end,
Narayan Kamath52f84882014-05-02 10:10:39 +010079 kGcRetentionPolicyNeverCollect),
Vladimir Markoc09cd052018-08-23 16:36:36 +010080 live_bitmap_(std::move(live_bitmap)),
Jeff Haodcdc85b2015-12-04 14:06:18 -080081 oat_file_non_owned_(nullptr),
Mathieu Chartier2d124ec2016-01-05 18:03:15 -080082 image_location_(image_location) {
Vladimir Markoc09cd052018-08-23 16:36:36 +010083 DCHECK(live_bitmap_ != nullptr);
Ian Rogers1d54e732013-05-02 21:10:01 -070084}
85
Alex Lightcf4bf382014-07-24 11:29:14 -070086static int32_t ChooseRelocationOffsetDelta(int32_t min_delta, int32_t max_delta) {
87 CHECK_ALIGNED(min_delta, kPageSize);
88 CHECK_ALIGNED(max_delta, kPageSize);
89 CHECK_LT(min_delta, max_delta);
90
Alex Light15324762015-11-19 11:03:10 -080091 int32_t r = GetRandomNumber<int32_t>(min_delta, max_delta);
Alex Lightcf4bf382014-07-24 11:29:14 -070092 if (r % 2 == 0) {
93 r = RoundUp(r, kPageSize);
94 } else {
95 r = RoundDown(r, kPageSize);
96 }
97 CHECK_LE(min_delta, r);
98 CHECK_GE(max_delta, r);
99 CHECK_ALIGNED(r, kPageSize);
100 return r;
101}
102
Andreas Gampea463b6a2016-08-12 21:53:32 -0700103static int32_t ChooseRelocationOffsetDelta() {
104 return ChooseRelocationOffsetDelta(ART_BASE_ADDRESS_MIN_DELTA, ART_BASE_ADDRESS_MAX_DELTA);
105}
106
107static bool GenerateImage(const std::string& image_filename,
108 InstructionSet image_isa,
Alex Light25396132014-08-27 15:37:23 -0700109 std::string* error_msg) {
Vladimir Marko91f10322018-12-07 18:04:10 +0000110 Runtime* runtime = Runtime::Current();
111 const std::vector<std::string>& boot_class_path = runtime->GetBootClassPath();
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700112 if (boot_class_path.empty()) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700113 *error_msg = "Failed to generate image because no boot class path specified";
114 return false;
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700115 }
Alex Light25396132014-08-27 15:37:23 -0700116 // We should clean up so we are more likely to have room for the image.
117 if (Runtime::Current()->IsZygote()) {
Andreas Gampe3c13a792014-09-18 20:56:04 -0700118 LOG(INFO) << "Pruning dalvik-cache since we are generating an image and will need to recompile";
Narayan Kamath28bc9872014-11-07 17:46:28 +0000119 PruneDalvikCache(image_isa);
Alex Light25396132014-08-27 15:37:23 -0700120 }
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700121
Mathieu Chartier8bbc8c02013-07-31 16:27:01 -0700122 std::vector<std::string> arg_vector;
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700123
Tsu Chiang Chuang12e6d742014-05-22 10:22:25 -0700124 std::string dex2oat(Runtime::Current()->GetCompilerExecutable());
Mathieu Chartier08d7d442013-07-31 18:08:51 -0700125 arg_vector.push_back(dex2oat);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700126
127 std::string image_option_string("--image=");
Narayan Kamath52f84882014-05-02 10:10:39 +0100128 image_option_string += image_filename;
Mathieu Chartier8bbc8c02013-07-31 16:27:01 -0700129 arg_vector.push_back(image_option_string);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700130
Vladimir Marko91f10322018-12-07 18:04:10 +0000131 const std::vector<std::string>& boot_class_path_locations = runtime->GetBootClassPathLocations();
132 DCHECK_EQ(boot_class_path.size(), boot_class_path_locations.size());
133 for (size_t i = 0u; i < boot_class_path.size(); i++) {
Mathieu Chartier8bbc8c02013-07-31 16:27:01 -0700134 arg_vector.push_back(std::string("--dex-file=") + boot_class_path[i]);
Vladimir Marko91f10322018-12-07 18:04:10 +0000135 arg_vector.push_back(std::string("--dex-location=") + boot_class_path_locations[i]);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700136 }
137
138 std::string oat_file_option_string("--oat-file=");
Brian Carlstrom2f1e15c2014-10-27 16:27:06 -0700139 oat_file_option_string += ImageHeader::GetOatLocationFromImageLocation(image_filename);
Mathieu Chartier8bbc8c02013-07-31 16:27:01 -0700140 arg_vector.push_back(oat_file_option_string);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700141
Sebastien Hertz0de11332015-05-13 12:14:05 +0200142 // Note: we do not generate a fully debuggable boot image so we do not pass the
143 // compiler flag --debuggable here.
144
Igor Murashkinb1d8c312015-08-04 11:18:43 -0700145 Runtime::Current()->AddCurrentRuntimeFeaturesAsDex2OatArguments(&arg_vector);
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700146 CHECK_EQ(image_isa, kRuntimeISA)
147 << "We should always be generating an image for the current isa.";
Ian Rogers8afeb852014-04-02 14:55:49 -0700148
Andreas Gampea463b6a2016-08-12 21:53:32 -0700149 int32_t base_offset = ChooseRelocationOffsetDelta();
Alex Lightcf4bf382014-07-24 11:29:14 -0700150 LOG(INFO) << "Using an offset of 0x" << std::hex << base_offset << " from default "
151 << "art base address of 0x" << std::hex << ART_BASE_ADDRESS;
152 arg_vector.push_back(StringPrintf("--base=0x%x", ART_BASE_ADDRESS + base_offset));
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700153
Brian Carlstrom57309db2014-07-30 15:13:25 -0700154 if (!kIsTargetBuild) {
Mathieu Chartier8bbc8c02013-07-31 16:27:01 -0700155 arg_vector.push_back("--host");
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700156 }
157
Brian Carlstrom6449c622014-02-10 23:48:36 -0800158 const std::vector<std::string>& compiler_options = Runtime::Current()->GetImageCompilerOptions();
Brian Carlstrom2ec65202014-03-03 15:16:37 -0800159 for (size_t i = 0; i < compiler_options.size(); ++i) {
Brian Carlstrom6449c622014-02-10 23:48:36 -0800160 arg_vector.push_back(compiler_options[i].c_str());
161 }
162
Andreas Gampe9186ced2016-12-12 14:28:21 -0800163 std::string command_line(android::base::Join(arg_vector, ' '));
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700164 LOG(INFO) << "GenerateImage: " << command_line;
Brian Carlstrom6449c622014-02-10 23:48:36 -0800165 return Exec(arg_vector, error_msg);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700166}
167
Andreas Gampea463b6a2016-08-12 21:53:32 -0700168static bool FindImageFilenameImpl(const char* image_location,
169 const InstructionSet image_isa,
170 bool* has_system,
171 std::string* system_filename,
172 bool* dalvik_cache_exists,
173 std::string* dalvik_cache,
174 bool* is_global_cache,
175 bool* has_cache,
176 std::string* cache_filename) {
177 DCHECK(dalvik_cache != nullptr);
178
Alex Lighta59dd802014-07-02 16:28:08 -0700179 *has_system = false;
180 *has_cache = false;
Brian Carlstrom0e12bdc2014-05-14 17:44:28 -0700181 // image_location = /system/framework/boot.art
182 // system_image_location = /system/framework/<image_isa>/boot.art
183 std::string system_image_filename(GetSystemImageFilename(image_location, image_isa));
184 if (OS::FileExists(system_image_filename.c_str())) {
Alex Lighta59dd802014-07-02 16:28:08 -0700185 *system_filename = system_image_filename;
186 *has_system = true;
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700187 }
Narayan Kamath52f84882014-05-02 10:10:39 +0100188
Alex Lighta59dd802014-07-02 16:28:08 -0700189 bool have_android_data = false;
190 *dalvik_cache_exists = false;
Andreas Gampea463b6a2016-08-12 21:53:32 -0700191 GetDalvikCache(GetInstructionSetString(image_isa),
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100192 /*create_if_absent=*/ true,
Andreas Gampea463b6a2016-08-12 21:53:32 -0700193 dalvik_cache,
194 &have_android_data,
195 dalvik_cache_exists,
196 is_global_cache);
Narayan Kamath52f84882014-05-02 10:10:39 +0100197
Vladimir Marko82e1e272018-08-20 13:38:06 +0000198 if (*dalvik_cache_exists) {
199 DCHECK(have_android_data);
Alex Lighta59dd802014-07-02 16:28:08 -0700200 // Always set output location even if it does not exist,
201 // so that the caller knows where to create the image.
202 //
203 // image_location = /system/framework/boot.art
Vladimir Marko82e1e272018-08-20 13:38:06 +0000204 // *image_filename = /data/dalvik-cache/<image_isa>/system@framework@boot.art
Alex Lighta59dd802014-07-02 16:28:08 -0700205 std::string error_msg;
Andreas Gampea463b6a2016-08-12 21:53:32 -0700206 if (!GetDalvikCacheFilename(image_location,
207 dalvik_cache->c_str(),
208 cache_filename,
209 &error_msg)) {
Alex Lighta59dd802014-07-02 16:28:08 -0700210 LOG(WARNING) << error_msg;
211 return *has_system;
212 }
213 *has_cache = OS::FileExists(cache_filename->c_str());
214 }
215 return *has_system || *has_cache;
216}
217
Andreas Gampea463b6a2016-08-12 21:53:32 -0700218bool ImageSpace::FindImageFilename(const char* image_location,
219 const InstructionSet image_isa,
220 std::string* system_filename,
221 bool* has_system,
222 std::string* cache_filename,
223 bool* dalvik_cache_exists,
224 bool* has_cache,
225 bool* is_global_cache) {
226 std::string dalvik_cache_unused;
227 return FindImageFilenameImpl(image_location,
228 image_isa,
229 has_system,
230 system_filename,
231 dalvik_cache_exists,
232 &dalvik_cache_unused,
233 is_global_cache,
234 has_cache,
235 cache_filename);
236}
237
Alex Lighta59dd802014-07-02 16:28:08 -0700238static bool ReadSpecificImageHeader(const char* filename, ImageHeader* image_header) {
239 std::unique_ptr<File> image_file(OS::OpenFileForReading(filename));
240 if (image_file.get() == nullptr) {
241 return false;
242 }
243 const bool success = image_file->ReadFully(image_header, sizeof(ImageHeader));
244 if (!success || !image_header->IsValid()) {
245 return false;
246 }
247 return true;
248}
249
Vladimir Marko4df2d802018-09-27 16:42:44 +0000250static std::unique_ptr<ImageHeader> ReadSpecificImageHeader(const char* filename,
251 std::string* error_msg) {
Alex Lighta59dd802014-07-02 16:28:08 -0700252 std::unique_ptr<ImageHeader> hdr(new ImageHeader);
253 if (!ReadSpecificImageHeader(filename, hdr.get())) {
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700254 *error_msg = StringPrintf("Unable to read image header for %s", filename);
Alex Lighta59dd802014-07-02 16:28:08 -0700255 return nullptr;
256 }
Vladimir Marko4df2d802018-09-27 16:42:44 +0000257 return hdr;
Narayan Kamath52f84882014-05-02 10:10:39 +0100258}
259
Vladimir Marko4df2d802018-09-27 16:42:44 +0000260std::unique_ptr<ImageHeader> ImageSpace::ReadImageHeader(const char* image_location,
261 const InstructionSet image_isa,
Andreas Gampe86823542019-02-25 09:38:49 -0800262 ImageSpaceLoadingOrder order,
Vladimir Marko4df2d802018-09-27 16:42:44 +0000263 std::string* error_msg) {
Alex Lighta59dd802014-07-02 16:28:08 -0700264 std::string system_filename;
265 bool has_system = false;
266 std::string cache_filename;
267 bool has_cache = false;
268 bool dalvik_cache_exists = false;
Andreas Gampe3c13a792014-09-18 20:56:04 -0700269 bool is_global_cache = false;
Vladimir Marko4df2d802018-09-27 16:42:44 +0000270 if (FindImageFilename(image_location,
271 image_isa,
272 &system_filename,
273 &has_system,
274 &cache_filename,
275 &dalvik_cache_exists,
276 &has_cache,
277 &is_global_cache)) {
Andreas Gampe86823542019-02-25 09:38:49 -0800278 if (order == ImageSpaceLoadingOrder::kSystemFirst) {
279 if (has_system) {
280 return ReadSpecificImageHeader(system_filename.c_str(), error_msg);
281 }
282 if (has_cache) {
283 return ReadSpecificImageHeader(cache_filename.c_str(), error_msg);
284 }
285 } else {
286 if (has_cache) {
287 return ReadSpecificImageHeader(cache_filename.c_str(), error_msg);
288 }
289 if (has_system) {
290 return ReadSpecificImageHeader(system_filename.c_str(), error_msg);
291 }
Narayan Kamath52f84882014-05-02 10:10:39 +0100292 }
Narayan Kamath52f84882014-05-02 10:10:39 +0100293 }
294
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700295 *error_msg = StringPrintf("Unable to find image file for %s", image_location);
Narayan Kamath52f84882014-05-02 10:10:39 +0100296 return nullptr;
297}
298
Robert Sesekbfa1f8d2016-08-15 15:21:09 -0400299static bool CanWriteToDalvikCache(const InstructionSet isa) {
300 const std::string dalvik_cache = GetDalvikCache(GetInstructionSetString(isa));
301 if (access(dalvik_cache.c_str(), O_RDWR) == 0) {
302 return true;
303 } else if (errno != EACCES) {
304 PLOG(WARNING) << "CanWriteToDalvikCache returned error other than EACCES";
305 }
306 return false;
307}
308
309static bool ImageCreationAllowed(bool is_global_cache,
310 const InstructionSet isa,
Vladimir Marko3364d182019-03-13 13:55:01 +0000311 bool is_zygote,
Robert Sesekbfa1f8d2016-08-15 15:21:09 -0400312 std::string* error_msg) {
Andreas Gampe3c13a792014-09-18 20:56:04 -0700313 // Anyone can write into a "local" cache.
314 if (!is_global_cache) {
315 return true;
316 }
317
Robert Sesekbfa1f8d2016-08-15 15:21:09 -0400318 // Only the zygote running as root is allowed to create the global boot image.
319 // If the zygote is running as non-root (and cannot write to the dalvik-cache),
320 // then image creation is not allowed..
Vladimir Marko3364d182019-03-13 13:55:01 +0000321 if (is_zygote) {
Robert Sesekbfa1f8d2016-08-15 15:21:09 -0400322 return CanWriteToDalvikCache(isa);
Andreas Gampe3c13a792014-09-18 20:56:04 -0700323 }
324
325 *error_msg = "Only the zygote can create the global boot image.";
326 return false;
327}
328
Mathieu Chartier31e89252013-08-28 11:29:12 -0700329void ImageSpace::VerifyImageAllocations() {
Ian Rogers13735952014-10-08 12:43:28 -0700330 uint8_t* current = Begin() + RoundUp(sizeof(ImageHeader), kObjectAlignment);
Mathieu Chartier31e89252013-08-28 11:29:12 -0700331 while (current < End()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700332 CHECK_ALIGNED(current, kObjectAlignment);
333 auto* obj = reinterpret_cast<mirror::Object*>(current);
Mathieu Chartier31e89252013-08-28 11:29:12 -0700334 CHECK(obj->GetClass() != nullptr) << "Image object at address " << obj << " has null class";
David Sehr709b0702016-10-13 09:12:37 -0700335 CHECK(live_bitmap_->Test(obj)) << obj->PrettyTypeOf();
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700336 if (kUseBakerReadBarrier) {
337 obj->AssertReadBarrierState();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800338 }
Mathieu Chartier31e89252013-08-28 11:29:12 -0700339 current += RoundUp(obj->SizeOf(), kObjectAlignment);
340 }
341}
342
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800343// Helper class for relocating from one range of memory to another.
344class RelocationRange {
345 public:
346 RelocationRange() = default;
347 RelocationRange(const RelocationRange&) = default;
348 RelocationRange(uintptr_t source, uintptr_t dest, uintptr_t length)
349 : source_(source),
350 dest_(dest),
351 length_(length) {}
352
Mathieu Chartier91edc622016-02-16 17:16:01 -0800353 bool InSource(uintptr_t address) const {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800354 return address - source_ < length_;
355 }
356
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -0800357 bool InDest(const void* dest) const {
358 return InDest(reinterpret_cast<uintptr_t>(dest));
359 }
360
Mathieu Chartier91edc622016-02-16 17:16:01 -0800361 bool InDest(uintptr_t address) const {
362 return address - dest_ < length_;
363 }
364
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800365 // Translate a source address to the destination space.
366 uintptr_t ToDest(uintptr_t address) const {
Mathieu Chartier91edc622016-02-16 17:16:01 -0800367 DCHECK(InSource(address));
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800368 return address + Delta();
369 }
370
371 // Returns the delta between the dest from the source.
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800372 uintptr_t Delta() const {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800373 return dest_ - source_;
374 }
375
376 uintptr_t Source() const {
377 return source_;
378 }
379
380 uintptr_t Dest() const {
381 return dest_;
382 }
383
384 uintptr_t Length() const {
385 return length_;
386 }
387
388 private:
389 const uintptr_t source_;
390 const uintptr_t dest_;
391 const uintptr_t length_;
392};
393
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800394std::ostream& operator<<(std::ostream& os, const RelocationRange& reloc) {
395 return os << "(" << reinterpret_cast<const void*>(reloc.Source()) << "-"
396 << reinterpret_cast<const void*>(reloc.Source() + reloc.Length()) << ")->("
397 << reinterpret_cast<const void*>(reloc.Dest()) << "-"
398 << reinterpret_cast<const void*>(reloc.Dest() + reloc.Length()) << ")";
399}
400
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -0800401template <PointerSize kPointerSize, typename HeapVisitor, typename NativeVisitor>
Mathieu Chartierd3f037b2018-12-06 23:50:56 -0800402class ImageSpace::PatchObjectVisitor final {
403 public:
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -0800404 explicit PatchObjectVisitor(HeapVisitor heap_visitor, NativeVisitor native_visitor)
405 : heap_visitor_(heap_visitor), native_visitor_(native_visitor) {}
Mathieu Chartierd3f037b2018-12-06 23:50:56 -0800406
407 void VisitClass(mirror::Class* klass) REQUIRES_SHARED(Locks::mutator_lock_) {
408 // A mirror::Class object consists of
409 // - instance fields inherited from j.l.Object,
410 // - instance fields inherited from j.l.Class,
411 // - embedded tables (vtable, interface method table),
412 // - static fields of the class itself.
413 // The reference fields are at the start of each field section (this is how the
414 // ClassLinker orders fields; except when that would create a gap between superclass
415 // fields and the first reference of the subclass due to alignment, it can be filled
416 // with smaller fields - but that's not the case for j.l.Object and j.l.Class).
417
418 DCHECK_ALIGNED(klass, kObjectAlignment);
419 static_assert(IsAligned<kHeapReferenceSize>(kObjectAlignment), "Object alignment check.");
420 // First, patch the `klass->klass_`, known to be a reference to the j.l.Class.class.
421 // This should be the only reference field in j.l.Object and we assert that below.
422 PatchReferenceField</*kMayBeNull=*/ false>(klass, mirror::Object::ClassOffset());
423 // Then patch the reference instance fields described by j.l.Class.class.
424 // Use the sizeof(Object) to determine where these reference fields start;
425 // this is the same as `class_class->GetFirstReferenceInstanceFieldOffset()`
426 // after patching but the j.l.Class may not have been patched yet.
427 mirror::Class* class_class = klass->GetClass<kVerifyNone, kWithoutReadBarrier>();
428 size_t num_reference_instance_fields = class_class->NumReferenceInstanceFields<kVerifyNone>();
429 DCHECK_NE(num_reference_instance_fields, 0u);
430 static_assert(IsAligned<kHeapReferenceSize>(sizeof(mirror::Object)), "Size alignment check.");
431 MemberOffset instance_field_offset(sizeof(mirror::Object));
432 for (size_t i = 0; i != num_reference_instance_fields; ++i) {
433 PatchReferenceField(klass, instance_field_offset);
434 static_assert(sizeof(mirror::HeapReference<mirror::Object>) == kHeapReferenceSize,
435 "Heap reference sizes equality check.");
436 instance_field_offset =
437 MemberOffset(instance_field_offset.Uint32Value() + kHeapReferenceSize);
438 }
439 // Now that we have patched the `super_class_`, if this is the j.l.Class.class,
440 // we can get a reference to j.l.Object.class and assert that it has only one
441 // reference instance field (the `klass_` patched above).
442 if (kIsDebugBuild && klass == class_class) {
443 ObjPtr<mirror::Class> object_class =
444 klass->GetSuperClass<kVerifyNone, kWithoutReadBarrier>();
445 CHECK_EQ(object_class->NumReferenceInstanceFields<kVerifyNone>(), 1u);
446 }
447 // Then patch static fields.
448 size_t num_reference_static_fields = klass->NumReferenceStaticFields<kVerifyNone>();
449 if (num_reference_static_fields != 0u) {
450 MemberOffset static_field_offset =
451 klass->GetFirstReferenceStaticFieldOffset<kVerifyNone>(kPointerSize);
452 for (size_t i = 0; i != num_reference_static_fields; ++i) {
453 PatchReferenceField(klass, static_field_offset);
454 static_assert(sizeof(mirror::HeapReference<mirror::Object>) == kHeapReferenceSize,
455 "Heap reference sizes equality check.");
456 static_field_offset =
457 MemberOffset(static_field_offset.Uint32Value() + kHeapReferenceSize);
458 }
459 }
460 // Then patch native pointers.
461 klass->FixupNativePointers<kVerifyNone>(klass, kPointerSize, *this);
462 }
463
464 template <typename T>
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -0800465 T* operator()(T* ptr, void** dest_addr ATTRIBUTE_UNUSED) const {
466 return (ptr != nullptr) ? native_visitor_(ptr) : nullptr;
Mathieu Chartierd3f037b2018-12-06 23:50:56 -0800467 }
468
469 void VisitPointerArray(mirror::PointerArray* pointer_array)
470 REQUIRES_SHARED(Locks::mutator_lock_) {
471 // Fully patch the pointer array, including the `klass_` field.
472 PatchReferenceField</*kMayBeNull=*/ false>(pointer_array, mirror::Object::ClassOffset());
473
474 int32_t length = pointer_array->GetLength<kVerifyNone>();
475 for (int32_t i = 0; i != length; ++i) {
476 ArtMethod** method_entry = reinterpret_cast<ArtMethod**>(
477 pointer_array->ElementAddress<kVerifyNone>(i, kPointerSize));
478 PatchNativePointer</*kMayBeNull=*/ false>(method_entry);
479 }
480 }
481
482 void VisitObject(mirror::Object* object) REQUIRES_SHARED(Locks::mutator_lock_) {
483 // Visit all reference fields.
484 object->VisitReferences</*kVisitNativeRoots=*/ false,
485 kVerifyNone,
486 kWithoutReadBarrier>(*this, *this);
487 // This function should not be called for classes.
488 DCHECK(!object->IsClass<kVerifyNone>());
489 }
490
491 // Visitor for VisitReferences().
492 ALWAYS_INLINE void operator()(mirror::Object* object, MemberOffset field_offset, bool is_static)
493 const REQUIRES_SHARED(Locks::mutator_lock_) {
494 DCHECK(!is_static);
495 PatchReferenceField(object, field_offset);
496 }
497 // Visitor for VisitReferences(), java.lang.ref.Reference case.
498 ALWAYS_INLINE void operator()(ObjPtr<mirror::Class> klass, mirror::Reference* ref) const
499 REQUIRES_SHARED(Locks::mutator_lock_) {
500 DCHECK(klass->IsTypeOfReferenceClass());
501 this->operator()(ref, mirror::Reference::ReferentOffset(), /*is_static=*/ false);
502 }
503 // Ignore class native roots; not called from VisitReferences() for kVisitNativeRoots == false.
504 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED)
505 const {}
506 void VisitRoot(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const {}
507
508 void VisitDexCacheArrays(mirror::DexCache* dex_cache) REQUIRES_SHARED(Locks::mutator_lock_) {
509 FixupDexCacheArray<mirror::StringDexCacheType>(dex_cache,
510 mirror::DexCache::StringsOffset(),
511 dex_cache->NumStrings<kVerifyNone>());
512 FixupDexCacheArray<mirror::TypeDexCacheType>(dex_cache,
513 mirror::DexCache::ResolvedTypesOffset(),
514 dex_cache->NumResolvedTypes<kVerifyNone>());
515 FixupDexCacheArray<mirror::MethodDexCacheType>(dex_cache,
516 mirror::DexCache::ResolvedMethodsOffset(),
517 dex_cache->NumResolvedMethods<kVerifyNone>());
518 FixupDexCacheArray<mirror::FieldDexCacheType>(dex_cache,
519 mirror::DexCache::ResolvedFieldsOffset(),
520 dex_cache->NumResolvedFields<kVerifyNone>());
521 FixupDexCacheArray<mirror::MethodTypeDexCacheType>(
522 dex_cache,
523 mirror::DexCache::ResolvedMethodTypesOffset(),
524 dex_cache->NumResolvedMethodTypes<kVerifyNone>());
525 FixupDexCacheArray<GcRoot<mirror::CallSite>>(
526 dex_cache,
527 mirror::DexCache::ResolvedCallSitesOffset(),
528 dex_cache->NumResolvedCallSites<kVerifyNone>());
529 FixupDexCacheArray<GcRoot<mirror::String>>(
530 dex_cache,
531 mirror::DexCache::PreResolvedStringsOffset(),
532 dex_cache->NumPreResolvedStrings<kVerifyNone>());
533 }
534
535 template <bool kMayBeNull = true, typename T>
536 ALWAYS_INLINE void PatchGcRoot(/*inout*/GcRoot<T>* root) const
537 REQUIRES_SHARED(Locks::mutator_lock_) {
538 static_assert(sizeof(GcRoot<mirror::Class*>) == sizeof(uint32_t), "GcRoot size check");
539 T* old_value = root->template Read<kWithoutReadBarrier>();
540 DCHECK(kMayBeNull || old_value != nullptr);
541 if (!kMayBeNull || old_value != nullptr) {
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -0800542 *root = GcRoot<T>(heap_visitor_(old_value));
Mathieu Chartierd3f037b2018-12-06 23:50:56 -0800543 }
544 }
545
546 template <bool kMayBeNull = true, typename T>
547 ALWAYS_INLINE void PatchNativePointer(/*inout*/T** entry) const {
548 if (kPointerSize == PointerSize::k64) {
549 uint64_t* raw_entry = reinterpret_cast<uint64_t*>(entry);
550 T* old_value = reinterpret_cast64<T*>(*raw_entry);
551 DCHECK(kMayBeNull || old_value != nullptr);
552 if (!kMayBeNull || old_value != nullptr) {
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -0800553 T* new_value = native_visitor_(old_value);
Mathieu Chartierd3f037b2018-12-06 23:50:56 -0800554 *raw_entry = reinterpret_cast64<uint64_t>(new_value);
555 }
556 } else {
557 uint32_t* raw_entry = reinterpret_cast<uint32_t*>(entry);
558 T* old_value = reinterpret_cast32<T*>(*raw_entry);
559 DCHECK(kMayBeNull || old_value != nullptr);
560 if (!kMayBeNull || old_value != nullptr) {
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -0800561 T* new_value = native_visitor_(old_value);
Mathieu Chartierd3f037b2018-12-06 23:50:56 -0800562 *raw_entry = reinterpret_cast32<uint32_t>(new_value);
563 }
564 }
565 }
566
567 template <bool kMayBeNull = true>
568 ALWAYS_INLINE void PatchReferenceField(mirror::Object* object, MemberOffset offset) const
569 REQUIRES_SHARED(Locks::mutator_lock_) {
570 mirror::Object* old_value =
571 object->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(offset);
572 DCHECK(kMayBeNull || old_value != nullptr);
573 if (!kMayBeNull || old_value != nullptr) {
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -0800574 mirror::Object* new_value = heap_visitor_(old_value);
Mathieu Chartierd3f037b2018-12-06 23:50:56 -0800575 object->SetFieldObjectWithoutWriteBarrier</*kTransactionActive=*/ false,
576 /*kCheckTransaction=*/ true,
577 kVerifyNone>(offset, new_value);
578 }
579 }
580
581 template <typename T>
582 void FixupDexCacheArrayEntry(std::atomic<mirror::DexCachePair<T>>* array, uint32_t index)
583 REQUIRES_SHARED(Locks::mutator_lock_) {
584 static_assert(sizeof(std::atomic<mirror::DexCachePair<T>>) == sizeof(mirror::DexCachePair<T>),
585 "Size check for removing std::atomic<>.");
586 PatchGcRoot(&(reinterpret_cast<mirror::DexCachePair<T>*>(array)[index].object));
587 }
588
589 template <typename T>
590 void FixupDexCacheArrayEntry(std::atomic<mirror::NativeDexCachePair<T>>* array, uint32_t index)
591 REQUIRES_SHARED(Locks::mutator_lock_) {
592 static_assert(sizeof(std::atomic<mirror::NativeDexCachePair<T>>) ==
593 sizeof(mirror::NativeDexCachePair<T>),
594 "Size check for removing std::atomic<>.");
595 mirror::NativeDexCachePair<T> pair =
596 mirror::DexCache::GetNativePairPtrSize(array, index, kPointerSize);
597 if (pair.object != nullptr) {
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -0800598 pair.object = native_visitor_(pair.object);
Mathieu Chartierd3f037b2018-12-06 23:50:56 -0800599 mirror::DexCache::SetNativePairPtrSize(array, index, pair, kPointerSize);
600 }
601 }
602
603 void FixupDexCacheArrayEntry(GcRoot<mirror::CallSite>* array, uint32_t index)
604 REQUIRES_SHARED(Locks::mutator_lock_) {
605 PatchGcRoot(&array[index]);
606 }
607
608 void FixupDexCacheArrayEntry(GcRoot<mirror::String>* array, uint32_t index)
609 REQUIRES_SHARED(Locks::mutator_lock_) {
610 PatchGcRoot(&array[index]);
611 }
612
613 template <typename EntryType>
614 void FixupDexCacheArray(mirror::DexCache* dex_cache,
615 MemberOffset array_offset,
616 uint32_t size) REQUIRES_SHARED(Locks::mutator_lock_) {
617 EntryType* old_array =
618 reinterpret_cast64<EntryType*>(dex_cache->GetField64<kVerifyNone>(array_offset));
619 DCHECK_EQ(old_array != nullptr, size != 0u);
620 if (old_array != nullptr) {
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -0800621 EntryType* new_array = native_visitor_(old_array);
Mathieu Chartierd3f037b2018-12-06 23:50:56 -0800622 dex_cache->SetField64<kVerifyNone>(array_offset, reinterpret_cast64<uint64_t>(new_array));
623 for (uint32_t i = 0; i != size; ++i) {
624 FixupDexCacheArrayEntry(new_array, i);
625 }
626 }
627 }
628
629 private:
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -0800630 // Heap objects visitor.
631 HeapVisitor heap_visitor_;
632
633 // Native objects visitor.
634 NativeVisitor native_visitor_;
Mathieu Chartierd3f037b2018-12-06 23:50:56 -0800635};
636
Mathieu Chartier25602dc2018-12-11 11:31:57 -0800637template <typename ReferenceVisitor>
638class ImageSpace::ClassTableVisitor final {
639 public:
640 explicit ClassTableVisitor(const ReferenceVisitor& reference_visitor)
641 : reference_visitor_(reference_visitor) {}
642
643 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
644 REQUIRES_SHARED(Locks::mutator_lock_) {
645 DCHECK(root->AsMirrorPtr() != nullptr);
646 root->Assign(reference_visitor_(root->AsMirrorPtr()));
647 }
648
649 private:
650 ReferenceVisitor reference_visitor_;
651};
652
Andreas Gampea463b6a2016-08-12 21:53:32 -0700653// Helper class encapsulating loading, so we can access private ImageSpace members (this is a
Vladimir Markoc09cd052018-08-23 16:36:36 +0100654// nested class), but not declare functions in the header.
Vladimir Marko82e1e272018-08-20 13:38:06 +0000655class ImageSpace::Loader {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800656 public:
Vladimir Marko4df2d802018-09-27 16:42:44 +0000657 static std::unique_ptr<ImageSpace> InitAppImage(const char* image_filename,
658 const char* image_location,
Vladimir Marko4df2d802018-09-27 16:42:44 +0000659 const OatFile* oat_file,
660 /*inout*/MemMap* image_reservation,
Vladimir Marko4df2d802018-09-27 16:42:44 +0000661 /*out*/std::string* error_msg)
662 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100663 TimingLogger logger(__PRETTY_FUNCTION__, /*precise=*/ true, VLOG_IS_ON(image));
Mathieu Chartier3ea43222018-12-08 20:44:50 -0800664
Vladimir Marko4df2d802018-09-27 16:42:44 +0000665 std::unique_ptr<ImageSpace> space = Init(image_filename,
666 image_location,
Vladimir Marko4df2d802018-09-27 16:42:44 +0000667 oat_file,
668 &logger,
669 image_reservation,
Vladimir Marko4df2d802018-09-27 16:42:44 +0000670 error_msg);
671 if (space != nullptr) {
Vladimir Marko7391c8c2018-11-21 17:58:44 +0000672 uint32_t expected_reservation_size =
673 RoundUp(space->GetImageHeader().GetImageSize(), kPageSize);
674 if (!CheckImageReservationSize(*space, expected_reservation_size, error_msg) ||
675 !CheckImageComponentCount(*space, /*expected_component_count=*/ 1u, error_msg)) {
676 return nullptr;
677 }
678
Vladimir Marko4df2d802018-09-27 16:42:44 +0000679 TimingLogger::ScopedTiming timing("RelocateImage", &logger);
680 ImageHeader* image_header = reinterpret_cast<ImageHeader*>(space->GetMemMap()->Begin());
Mathieu Chartier25602dc2018-12-11 11:31:57 -0800681 const PointerSize pointer_size = image_header->GetPointerSize();
682 bool result;
683 if (pointer_size == PointerSize::k64) {
684 result = RelocateInPlace<PointerSize::k64>(*image_header,
685 space->GetMemMap()->Begin(),
686 space->GetLiveBitmap(),
687 oat_file,
688 error_msg);
689 } else {
690 result = RelocateInPlace<PointerSize::k32>(*image_header,
691 space->GetMemMap()->Begin(),
692 space->GetLiveBitmap(),
693 oat_file,
694 error_msg);
695 }
696 if (!result) {
Vladimir Marko4df2d802018-09-27 16:42:44 +0000697 return nullptr;
698 }
699 Runtime* runtime = Runtime::Current();
700 CHECK_EQ(runtime->GetResolutionMethod(),
701 image_header->GetImageMethod(ImageHeader::kResolutionMethod));
702 CHECK_EQ(runtime->GetImtConflictMethod(),
703 image_header->GetImageMethod(ImageHeader::kImtConflictMethod));
704 CHECK_EQ(runtime->GetImtUnimplementedMethod(),
705 image_header->GetImageMethod(ImageHeader::kImtUnimplementedMethod));
706 CHECK_EQ(runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveAllCalleeSaves),
707 image_header->GetImageMethod(ImageHeader::kSaveAllCalleeSavesMethod));
708 CHECK_EQ(runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveRefsOnly),
709 image_header->GetImageMethod(ImageHeader::kSaveRefsOnlyMethod));
710 CHECK_EQ(runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveRefsAndArgs),
711 image_header->GetImageMethod(ImageHeader::kSaveRefsAndArgsMethod));
712 CHECK_EQ(runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveEverything),
713 image_header->GetImageMethod(ImageHeader::kSaveEverythingMethod));
714 CHECK_EQ(runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveEverythingForClinit),
715 image_header->GetImageMethod(ImageHeader::kSaveEverythingMethodForClinit));
716 CHECK_EQ(runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveEverythingForSuspendCheck),
717 image_header->GetImageMethod(ImageHeader::kSaveEverythingMethodForSuspendCheck));
718
719 VLOG(image) << "ImageSpace::Loader::InitAppImage exiting " << *space.get();
Mathieu Chartier3f1fec62018-10-17 09:14:05 -0700720 }
721 if (VLOG_IS_ON(image)) {
722 logger.Dump(LOG_STREAM(INFO));
Vladimir Marko4df2d802018-09-27 16:42:44 +0000723 }
724 return space;
725 }
726
Andreas Gampea463b6a2016-08-12 21:53:32 -0700727 static std::unique_ptr<ImageSpace> Init(const char* image_filename,
728 const char* image_location,
Andreas Gampea463b6a2016-08-12 21:53:32 -0700729 const OatFile* oat_file,
Vladimir Marko4df2d802018-09-27 16:42:44 +0000730 TimingLogger* logger,
Vladimir Markoc09cd052018-08-23 16:36:36 +0100731 /*inout*/MemMap* image_reservation,
Vladimir Markoc09cd052018-08-23 16:36:36 +0100732 /*out*/std::string* error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700733 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampea463b6a2016-08-12 21:53:32 -0700734 CHECK(image_filename != nullptr);
735 CHECK(image_location != nullptr);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800736
Andreas Gampea463b6a2016-08-12 21:53:32 -0700737 VLOG(image) << "ImageSpace::Init entering image_filename=" << image_filename;
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800738
Andreas Gampea463b6a2016-08-12 21:53:32 -0700739 std::unique_ptr<File> file;
Mathieu Chartier92ec5942016-04-11 12:03:48 -0700740 {
Vladimir Marko4df2d802018-09-27 16:42:44 +0000741 TimingLogger::ScopedTiming timing("OpenImageFile", logger);
Andreas Gampea463b6a2016-08-12 21:53:32 -0700742 file.reset(OS::OpenFileForReading(image_filename));
743 if (file == nullptr) {
744 *error_msg = StringPrintf("Failed to open '%s'", image_filename);
745 return nullptr;
Mathieu Chartier92ec5942016-04-11 12:03:48 -0700746 }
Andreas Gampea463b6a2016-08-12 21:53:32 -0700747 }
748 ImageHeader temp_image_header;
749 ImageHeader* image_header = &temp_image_header;
750 {
Vladimir Marko4df2d802018-09-27 16:42:44 +0000751 TimingLogger::ScopedTiming timing("ReadImageHeader", logger);
Andreas Gampea463b6a2016-08-12 21:53:32 -0700752 bool success = file->ReadFully(image_header, sizeof(*image_header));
753 if (!success || !image_header->IsValid()) {
754 *error_msg = StringPrintf("Invalid image header in '%s'", image_filename);
755 return nullptr;
756 }
757 }
758 // Check that the file is larger or equal to the header size + data size.
759 const uint64_t image_file_size = static_cast<uint64_t>(file->GetLength());
760 if (image_file_size < sizeof(ImageHeader) + image_header->GetDataSize()) {
Mathieu Chartier1a842962018-11-13 15:09:51 -0800761 *error_msg = StringPrintf(
762 "Image file truncated: %" PRIu64 " vs. %" PRIu64 ".",
763 image_file_size,
764 static_cast<uint64_t>(sizeof(ImageHeader) + image_header->GetDataSize()));
Andreas Gampea463b6a2016-08-12 21:53:32 -0700765 return nullptr;
766 }
767
768 if (oat_file != nullptr) {
Vladimir Marko312f10e2018-11-21 12:35:24 +0000769 // If we have an oat file (i.e. for app image), check the oat file checksum.
770 // Otherwise, we open the oat file after the image and check the checksum there.
Andreas Gampea463b6a2016-08-12 21:53:32 -0700771 const uint32_t oat_checksum = oat_file->GetOatHeader().GetChecksum();
772 const uint32_t image_oat_checksum = image_header->GetOatChecksum();
773 if (oat_checksum != image_oat_checksum) {
774 *error_msg = StringPrintf("Oat checksum 0x%x does not match the image one 0x%x in image %s",
775 oat_checksum,
776 image_oat_checksum,
777 image_filename);
778 return nullptr;
Mathieu Chartier92ec5942016-04-11 12:03:48 -0700779 }
780 }
781
Andreas Gampea463b6a2016-08-12 21:53:32 -0700782 if (VLOG_IS_ON(startup)) {
783 LOG(INFO) << "Dumping image sections";
784 for (size_t i = 0; i < ImageHeader::kSectionCount; ++i) {
785 const auto section_idx = static_cast<ImageHeader::ImageSections>(i);
786 auto& section = image_header->GetImageSection(section_idx);
787 LOG(INFO) << section_idx << " start="
788 << reinterpret_cast<void*>(image_header->GetImageBegin() + section.Offset()) << " "
789 << section;
Mathieu Chartier92ec5942016-04-11 12:03:48 -0700790 }
Andreas Gampea463b6a2016-08-12 21:53:32 -0700791 }
792
Vladimir Markocd87c3e2017-09-05 13:11:57 +0100793 const auto& bitmap_section = image_header->GetImageBitmapSection();
Andreas Gampea463b6a2016-08-12 21:53:32 -0700794 // The location we want to map from is the first aligned page after the end of the stored
795 // (possibly compressed) data.
796 const size_t image_bitmap_offset = RoundUp(sizeof(ImageHeader) + image_header->GetDataSize(),
797 kPageSize);
798 const size_t end_of_bitmap = image_bitmap_offset + bitmap_section.Size();
Vladimir Markod68ab242018-10-18 16:07:10 +0100799 if (end_of_bitmap != image_file_size) {
Andreas Gampea463b6a2016-08-12 21:53:32 -0700800 *error_msg = StringPrintf(
Vladimir Markod68ab242018-10-18 16:07:10 +0100801 "Image file size does not equal end of bitmap: size=%" PRIu64 " vs. %zu.",
Vladimir Marko6121aa62018-07-06 10:04:35 +0100802 image_file_size,
Vladimir Markod68ab242018-10-18 16:07:10 +0100803 end_of_bitmap);
Andreas Gampea463b6a2016-08-12 21:53:32 -0700804 return nullptr;
805 }
806
Andreas Gampea463b6a2016-08-12 21:53:32 -0700807 // GetImageBegin is the preferred address to map the image. If we manage to map the
808 // image at the image begin, the amount of fixup work required is minimized.
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -0800809 // If it is pic we will retry with error_msg for the2 failure case. Pass a null error_msg to
Mathieu Chartier66b1d572017-02-10 18:41:39 -0800810 // avoid reading proc maps for a mapping failure and slowing everything down.
Vladimir Markoc09cd052018-08-23 16:36:36 +0100811 // For the boot image, we have already reserved the memory and we load the image
812 // into the `image_reservation`.
Vladimir Marko312f10e2018-11-21 12:35:24 +0000813 MemMap map = LoadImageFile(
Vladimir Markoc09cd052018-08-23 16:36:36 +0100814 image_filename,
815 image_location,
816 *image_header,
Vladimir Markoc09cd052018-08-23 16:36:36 +0100817 file->Fd(),
818 logger,
819 image_reservation,
Vladimir Marko4df2d802018-09-27 16:42:44 +0000820 error_msg);
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100821 if (!map.IsValid()) {
Andreas Gampea463b6a2016-08-12 21:53:32 -0700822 DCHECK(!error_msg->empty());
823 return nullptr;
824 }
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100825 DCHECK_EQ(0, memcmp(image_header, map.Begin(), sizeof(ImageHeader)));
Andreas Gampea463b6a2016-08-12 21:53:32 -0700826
Vladimir Markoc09cd052018-08-23 16:36:36 +0100827 MemMap image_bitmap_map = MemMap::MapFile(bitmap_section.Size(),
Vladimir Marko4df2d802018-09-27 16:42:44 +0000828 PROT_READ,
829 MAP_PRIVATE,
Vladimir Markoc09cd052018-08-23 16:36:36 +0100830 file->Fd(),
831 image_bitmap_offset,
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100832 /*low_4gb=*/ false,
Vladimir Markoc09cd052018-08-23 16:36:36 +0100833 image_filename,
834 error_msg);
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100835 if (!image_bitmap_map.IsValid()) {
Andreas Gampea463b6a2016-08-12 21:53:32 -0700836 *error_msg = StringPrintf("Failed to map image bitmap: %s", error_msg->c_str());
837 return nullptr;
838 }
839 // Loaded the map, use the image header from the file now in case we patch it with
840 // RelocateInPlace.
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100841 image_header = reinterpret_cast<ImageHeader*>(map.Begin());
Hans Boehmfb8b4e22018-09-05 16:45:42 -0700842 const uint32_t bitmap_index = ImageSpace::bitmap_index_.fetch_add(1);
Andreas Gampea463b6a2016-08-12 21:53:32 -0700843 std::string bitmap_name(StringPrintf("imagespace %s live-bitmap %u",
844 image_filename,
845 bitmap_index));
846 // Bitmap only needs to cover until the end of the mirror objects section.
Vladimir Markocd87c3e2017-09-05 13:11:57 +0100847 const ImageSection& image_objects = image_header->GetObjectsSection();
Andreas Gampea463b6a2016-08-12 21:53:32 -0700848 // We only want the mirror object, not the ArtFields and ArtMethods.
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100849 uint8_t* const image_end = map.Begin() + image_objects.End();
Andreas Gampea463b6a2016-08-12 21:53:32 -0700850 std::unique_ptr<accounting::ContinuousSpaceBitmap> bitmap;
851 {
Vladimir Marko4df2d802018-09-27 16:42:44 +0000852 TimingLogger::ScopedTiming timing("CreateImageBitmap", logger);
Andreas Gampea463b6a2016-08-12 21:53:32 -0700853 bitmap.reset(
854 accounting::ContinuousSpaceBitmap::CreateFromMemMap(
855 bitmap_name,
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100856 std::move(image_bitmap_map),
857 reinterpret_cast<uint8_t*>(map.Begin()),
Mathieu Chartier612ff542017-05-01 09:59:24 -0700858 // Make sure the bitmap is aligned to card size instead of just bitmap word size.
859 RoundUp(image_objects.End(), gc::accounting::CardTable::kCardSize)));
Andreas Gampea463b6a2016-08-12 21:53:32 -0700860 if (bitmap == nullptr) {
861 *error_msg = StringPrintf("Could not create bitmap '%s'", bitmap_name.c_str());
862 return nullptr;
863 }
864 }
Andreas Gampea463b6a2016-08-12 21:53:32 -0700865 // We only want the mirror object, not the ArtFields and ArtMethods.
866 std::unique_ptr<ImageSpace> space(new ImageSpace(image_filename,
867 image_location,
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100868 std::move(map),
Vladimir Markoc09cd052018-08-23 16:36:36 +0100869 std::move(bitmap),
Andreas Gampea463b6a2016-08-12 21:53:32 -0700870 image_end));
Vladimir Marko312f10e2018-11-21 12:35:24 +0000871 space->oat_file_non_owned_ = oat_file;
Andreas Gampea463b6a2016-08-12 21:53:32 -0700872 return space;
873 }
874
Vladimir Marko7391c8c2018-11-21 17:58:44 +0000875 static bool CheckImageComponentCount(const ImageSpace& space,
876 uint32_t expected_component_count,
877 /*out*/std::string* error_msg) {
878 const ImageHeader& header = space.GetImageHeader();
879 if (header.GetComponentCount() != expected_component_count) {
880 *error_msg = StringPrintf("Unexpected component count in %s, received %u, expected %u",
881 space.GetImageFilename().c_str(),
882 header.GetComponentCount(),
883 expected_component_count);
884 return false;
885 }
886 return true;
887 }
888
889 static bool CheckImageReservationSize(const ImageSpace& space,
890 uint32_t expected_reservation_size,
891 /*out*/std::string* error_msg) {
892 const ImageHeader& header = space.GetImageHeader();
893 if (header.GetImageReservationSize() != expected_reservation_size) {
894 *error_msg = StringPrintf("Unexpected reservation size in %s, received %u, expected %u",
895 space.GetImageFilename().c_str(),
896 header.GetImageReservationSize(),
897 expected_reservation_size);
898 return false;
899 }
900 return true;
901 }
902
Andreas Gampea463b6a2016-08-12 21:53:32 -0700903 private:
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100904 static MemMap LoadImageFile(const char* image_filename,
905 const char* image_location,
906 const ImageHeader& image_header,
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100907 int fd,
Vladimir Marko4df2d802018-09-27 16:42:44 +0000908 TimingLogger* logger,
Vladimir Markoc09cd052018-08-23 16:36:36 +0100909 /*inout*/MemMap* image_reservation,
910 /*out*/std::string* error_msg) {
Vladimir Marko4df2d802018-09-27 16:42:44 +0000911 TimingLogger::ScopedTiming timing("MapImageFile", logger);
Mathieu Chartier1a842962018-11-13 15:09:51 -0800912 std::string temp_error_msg;
913 const bool is_compressed = image_header.HasCompressedBlock();
914 if (!is_compressed) {
Vladimir Marko11306592018-10-26 14:22:59 +0100915 uint8_t* address = (image_reservation != nullptr) ? image_reservation->Begin() : nullptr;
Andreas Gampea463b6a2016-08-12 21:53:32 -0700916 return MemMap::MapFileAtAddress(address,
917 image_header.GetImageSize(),
918 PROT_READ | PROT_WRITE,
919 MAP_PRIVATE,
920 fd,
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100921 /*start=*/ 0,
922 /*low_4gb=*/ true,
Andreas Gampea463b6a2016-08-12 21:53:32 -0700923 image_filename,
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100924 /*reuse=*/ false,
Vladimir Markoc09cd052018-08-23 16:36:36 +0100925 image_reservation,
Andreas Gampea463b6a2016-08-12 21:53:32 -0700926 error_msg);
927 }
928
Andreas Gampea463b6a2016-08-12 21:53:32 -0700929 // Reserve output and decompress into it.
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100930 MemMap map = MemMap::MapAnonymous(image_location,
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100931 image_header.GetImageSize(),
932 PROT_READ | PROT_WRITE,
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100933 /*low_4gb=*/ true,
Vladimir Markoc09cd052018-08-23 16:36:36 +0100934 image_reservation,
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100935 error_msg);
936 if (map.IsValid()) {
Andreas Gampea463b6a2016-08-12 21:53:32 -0700937 const size_t stored_size = image_header.GetDataSize();
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100938 MemMap temp_map = MemMap::MapFile(sizeof(ImageHeader) + stored_size,
939 PROT_READ,
940 MAP_PRIVATE,
941 fd,
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100942 /*start=*/ 0,
943 /*low_4gb=*/ false,
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100944 image_filename,
945 error_msg);
946 if (!temp_map.IsValid()) {
Mathieu Chartier66b1d572017-02-10 18:41:39 -0800947 DCHECK(error_msg == nullptr || !error_msg->empty());
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100948 return MemMap::Invalid();
Andreas Gampea463b6a2016-08-12 21:53:32 -0700949 }
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100950 memcpy(map.Begin(), &image_header, sizeof(ImageHeader));
Mathieu Chartierc6068c72018-11-13 16:00:58 -0800951
Mathieu Chartierada33d72018-12-17 13:17:30 -0800952 Runtime::ScopedThreadPoolUsage stpu;
953 ThreadPool* const pool = stpu.GetThreadPool();
Andreas Gampea463b6a2016-08-12 21:53:32 -0700954 const uint64_t start = NanoTime();
Mathieu Chartierc6068c72018-11-13 16:00:58 -0800955 Thread* const self = Thread::Current();
Mathieu Chartierada33d72018-12-17 13:17:30 -0800956 static constexpr size_t kMinBlocks = 2u;
957 const bool use_parallel = pool != nullptr && image_header.GetBlockCount() >= kMinBlocks;
Mathieu Chartier1a842962018-11-13 15:09:51 -0800958 for (const ImageHeader::Block& block : image_header.GetBlocks(temp_map.Begin())) {
Mathieu Chartierc6068c72018-11-13 16:00:58 -0800959 auto function = [&](Thread*) {
960 const uint64_t start2 = NanoTime();
961 ScopedTrace trace("LZ4 decompress block");
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -0800962 bool result = block.Decompress(/*out_ptr=*/map.Begin(),
963 /*in_ptr=*/temp_map.Begin(),
964 error_msg);
965 if (!result && error_msg != nullptr) {
966 *error_msg = "Failed to decompress image block " + *error_msg;
Mathieu Chartier1a842962018-11-13 15:09:51 -0800967 }
Mathieu Chartierc6068c72018-11-13 16:00:58 -0800968 VLOG(image) << "Decompress block " << block.GetDataSize() << " -> "
969 << block.GetImageSize() << " in " << PrettyDuration(NanoTime() - start2);
970 };
971 if (use_parallel) {
972 pool->AddTask(self, new FunctionTask(std::move(function)));
973 } else {
974 function(self);
Mathieu Chartier1a842962018-11-13 15:09:51 -0800975 }
976 }
Mathieu Chartierc6068c72018-11-13 16:00:58 -0800977 if (use_parallel) {
978 ScopedTrace trace("Waiting for workers");
979 pool->Wait(self, true, false);
980 }
Mathieu Chartier0d4d2912017-02-10 17:22:41 -0800981 const uint64_t time = NanoTime() - start;
982 // Add one 1 ns to prevent possible divide by 0.
983 VLOG(image) << "Decompressing image took " << PrettyDuration(time) << " ("
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100984 << PrettySize(static_cast<uint64_t>(map.Size()) * MsToNs(1000) / (time + 1))
Mathieu Chartier0d4d2912017-02-10 17:22:41 -0800985 << "/s)";
Andreas Gampea463b6a2016-08-12 21:53:32 -0700986 }
987
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100988 return map;
Andreas Gampea463b6a2016-08-12 21:53:32 -0700989 }
990
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -0800991 class EmptyRange {
Andreas Gampea463b6a2016-08-12 21:53:32 -0700992 public:
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -0800993 ALWAYS_INLINE bool InSource(uintptr_t) const { return false; }
994 ALWAYS_INLINE bool InDest(uintptr_t) const { return false; }
995 ALWAYS_INLINE uintptr_t ToDest(uintptr_t) const { UNREACHABLE(); }
996 };
997
998 template <typename Range0, typename Range1 = EmptyRange, typename Range2 = EmptyRange>
999 class ForwardAddress {
1000 public:
1001 ForwardAddress(const Range0& range0 = Range0(),
1002 const Range1& range1 = Range1(),
1003 const Range2& range2 = Range2())
1004 : range0_(range0), range1_(range1), range2_(range2) {}
Andreas Gampea463b6a2016-08-12 21:53:32 -07001005
1006 // Return the relocated address of a heap object.
Mathieu Chartier9a3da9a2018-12-21 12:56:55 -08001007 // Null checks must be performed in the caller (for performance reasons).
Andreas Gampea463b6a2016-08-12 21:53:32 -07001008 template <typename T>
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -08001009 ALWAYS_INLINE T* operator()(T* src) const {
Mathieu Chartier9a3da9a2018-12-21 12:56:55 -08001010 DCHECK(src != nullptr);
Andreas Gampea463b6a2016-08-12 21:53:32 -07001011 const uintptr_t uint_src = reinterpret_cast<uintptr_t>(src);
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -08001012 if (range2_.InSource(uint_src)) {
1013 return reinterpret_cast<T*>(range2_.ToDest(uint_src));
Andreas Gampea463b6a2016-08-12 21:53:32 -07001014 }
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -08001015 if (range1_.InSource(uint_src)) {
1016 return reinterpret_cast<T*>(range1_.ToDest(uint_src));
Andreas Gampea463b6a2016-08-12 21:53:32 -07001017 }
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -08001018 CHECK(range0_.InSource(uint_src))
1019 << reinterpret_cast<const void*>(src) << " not in "
1020 << reinterpret_cast<const void*>(range0_.Source()) << "-"
1021 << reinterpret_cast<const void*>(range0_.Source() + range0_.Length());
1022 return reinterpret_cast<T*>(range0_.ToDest(uint_src));
Andreas Gampea463b6a2016-08-12 21:53:32 -07001023 }
1024
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -08001025 private:
1026 const Range0 range0_;
1027 const Range1 range1_;
1028 const Range2 range2_;
Andreas Gampea463b6a2016-08-12 21:53:32 -07001029 };
1030
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -08001031 template <typename Forward>
1032 class FixupRootVisitor {
Andreas Gampea463b6a2016-08-12 21:53:32 -07001033 public:
1034 template<typename... Args>
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -08001035 explicit FixupRootVisitor(Args... args) : forward_(args...) {}
Andreas Gampea463b6a2016-08-12 21:53:32 -07001036
1037 ALWAYS_INLINE void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001038 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampea463b6a2016-08-12 21:53:32 -07001039 if (!root->IsNull()) {
1040 VisitRoot(root);
1041 }
1042 }
1043
1044 ALWAYS_INLINE void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001045 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampea463b6a2016-08-12 21:53:32 -07001046 mirror::Object* ref = root->AsMirrorPtr();
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -08001047 mirror::Object* new_ref = forward_(ref);
Andreas Gampea463b6a2016-08-12 21:53:32 -07001048 if (ref != new_ref) {
1049 root->Assign(new_ref);
1050 }
1051 }
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -08001052
1053 private:
1054 Forward forward_;
Andreas Gampea463b6a2016-08-12 21:53:32 -07001055 };
1056
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -08001057 template <typename Forward>
1058 class FixupObjectVisitor {
Andreas Gampea463b6a2016-08-12 21:53:32 -07001059 public:
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -08001060 explicit FixupObjectVisitor(gc::accounting::ContinuousSpaceBitmap* visited,
1061 const Forward& forward)
1062 : visited_(visited), forward_(forward) {}
Andreas Gampea463b6a2016-08-12 21:53:32 -07001063
1064 // Fix up separately since we also need to fix up method entrypoints.
1065 ALWAYS_INLINE void VisitRootIfNonNull(
1066 mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const {}
1067
1068 ALWAYS_INLINE void VisitRoot(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED)
1069 const {}
1070
Mathieu Chartier31e88222016-10-14 18:43:19 -07001071 ALWAYS_INLINE void operator()(ObjPtr<mirror::Object> obj,
Andreas Gampea463b6a2016-08-12 21:53:32 -07001072 MemberOffset offset,
1073 bool is_static ATTRIBUTE_UNUSED) const
1074 NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier25602dc2018-12-11 11:31:57 -08001075 // Space is not yet added to the heap, don't do a read barrier.
1076 mirror::Object* ref = obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(
1077 offset);
Mathieu Chartier9a3da9a2018-12-21 12:56:55 -08001078 if (ref != nullptr) {
1079 // Use SetFieldObjectWithoutWriteBarrier to avoid card marking since we are writing to the
1080 // image.
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -08001081 obj->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(offset, forward_(ref));
Mathieu Chartier9a3da9a2018-12-21 12:56:55 -08001082 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07001083 }
1084
1085 // java.lang.ref.Reference visitor.
Mathieu Chartier31e88222016-10-14 18:43:19 -07001086 void operator()(ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
1087 ObjPtr<mirror::Reference> ref) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001088 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Andreas Gampea463b6a2016-08-12 21:53:32 -07001089 mirror::Object* obj = ref->GetReferent<kWithoutReadBarrier>();
Mathieu Chartier9a3da9a2018-12-21 12:56:55 -08001090 if (obj != nullptr) {
1091 ref->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
1092 mirror::Reference::ReferentOffset(),
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -08001093 forward_(obj));
Mathieu Chartier9a3da9a2018-12-21 12:56:55 -08001094 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07001095 }
1096
Mathieu Chartier8c19d242017-03-06 12:35:10 -08001097 void operator()(mirror::Object* obj) const
1098 NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier25602dc2018-12-11 11:31:57 -08001099 if (!visited_->Set(obj)) {
1100 // Not already visited.
1101 obj->VisitReferences</*visit native roots*/false, kVerifyNone, kWithoutReadBarrier>(
1102 *this,
1103 *this);
1104 CHECK(!obj->IsClass());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001105 }
1106 }
Mathieu Chartier91edc622016-02-16 17:16:01 -08001107
Andreas Gampea463b6a2016-08-12 21:53:32 -07001108 private:
Andreas Gampea463b6a2016-08-12 21:53:32 -07001109 gc::accounting::ContinuousSpaceBitmap* const visited_;
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -08001110 Forward forward_;
Andreas Gampea463b6a2016-08-12 21:53:32 -07001111 };
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001112
Andreas Gampea463b6a2016-08-12 21:53:32 -07001113 // Relocate an image space mapped at target_base which possibly used to be at a different base
Vladimir Marko4df2d802018-09-27 16:42:44 +00001114 // address. In place means modifying a single ImageSpace in place rather than relocating from
1115 // one ImageSpace to another.
Mathieu Chartier25602dc2018-12-11 11:31:57 -08001116 template <PointerSize kPointerSize>
Andreas Gampea463b6a2016-08-12 21:53:32 -07001117 static bool RelocateInPlace(ImageHeader& image_header,
1118 uint8_t* target_base,
1119 accounting::ContinuousSpaceBitmap* bitmap,
1120 const OatFile* app_oat_file,
1121 std::string* error_msg) {
1122 DCHECK(error_msg != nullptr);
Andreas Gampea463b6a2016-08-12 21:53:32 -07001123 // Set up sections.
1124 uint32_t boot_image_begin = 0;
1125 uint32_t boot_image_end = 0;
1126 uint32_t boot_oat_begin = 0;
1127 uint32_t boot_oat_end = 0;
Andreas Gampea463b6a2016-08-12 21:53:32 -07001128 gc::Heap* const heap = Runtime::Current()->GetHeap();
1129 heap->GetBootImagesSize(&boot_image_begin, &boot_image_end, &boot_oat_begin, &boot_oat_end);
1130 if (boot_image_begin == boot_image_end) {
1131 *error_msg = "Can not relocate app image without boot image space";
1132 return false;
1133 }
1134 if (boot_oat_begin == boot_oat_end) {
1135 *error_msg = "Can not relocate app image without boot oat file";
1136 return false;
1137 }
Vladimir Marko0c78ef72018-11-21 14:09:35 +00001138 const uint32_t boot_image_size = boot_oat_end - boot_image_begin;
Andreas Gampea463b6a2016-08-12 21:53:32 -07001139 const uint32_t image_header_boot_image_size = image_header.GetBootImageSize();
Andreas Gampea463b6a2016-08-12 21:53:32 -07001140 if (boot_image_size != image_header_boot_image_size) {
1141 *error_msg = StringPrintf("Boot image size %" PRIu64 " does not match expected size %"
1142 PRIu64,
1143 static_cast<uint64_t>(boot_image_size),
1144 static_cast<uint64_t>(image_header_boot_image_size));
1145 return false;
1146 }
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -08001147 const ImageSection& objects_section = image_header.GetObjectsSection();
1148 // Where the app image objects are mapped to.
1149 uint8_t* objects_location = target_base + objects_section.Offset();
Andreas Gampea463b6a2016-08-12 21:53:32 -07001150 TimingLogger logger(__FUNCTION__, true, false);
1151 RelocationRange boot_image(image_header.GetBootImageBegin(),
1152 boot_image_begin,
1153 boot_image_size);
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -08001154 // Metadata is everything after the objects section, use exclusion to be safe.
1155 RelocationRange app_image_metadata(
1156 reinterpret_cast<uintptr_t>(image_header.GetImageBegin()) + objects_section.End(),
1157 reinterpret_cast<uintptr_t>(target_base) + objects_section.End(),
1158 image_header.GetImageSize() - objects_section.End());
1159 // App image heap objects, may be mapped in the heap.
1160 RelocationRange app_image_objects(
1161 reinterpret_cast<uintptr_t>(image_header.GetImageBegin()) + objects_section.Offset(),
1162 reinterpret_cast<uintptr_t>(objects_location),
1163 objects_section.Size());
Andreas Gampea463b6a2016-08-12 21:53:32 -07001164 // Use the oat data section since this is where the OatFile::Begin is.
1165 RelocationRange app_oat(reinterpret_cast<uintptr_t>(image_header.GetOatDataBegin()),
1166 // Not necessarily in low 4GB.
1167 reinterpret_cast<uintptr_t>(app_oat_file->Begin()),
1168 image_header.GetOatDataEnd() - image_header.GetOatDataBegin());
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -08001169 VLOG(image) << "App image metadata " << app_image_metadata;
1170 VLOG(image) << "App image objects " << app_image_objects;
Andreas Gampea463b6a2016-08-12 21:53:32 -07001171 VLOG(image) << "App oat " << app_oat;
1172 VLOG(image) << "Boot image " << boot_image;
Vladimir Marko0c78ef72018-11-21 14:09:35 +00001173 // True if we need to fixup any heap pointers.
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -08001174 const bool fixup_image = boot_image.Delta() != 0 || app_image_metadata.Delta() != 0 ||
1175 app_image_objects.Delta() != 0;
Vladimir Marko0c78ef72018-11-21 14:09:35 +00001176 if (!fixup_image) {
Andreas Gampea463b6a2016-08-12 21:53:32 -07001177 // Nothing to fix up.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001178 return true;
1179 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07001180 ScopedDebugDisallowReadBarriers sddrb(Thread::Current());
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -08001181
1182 using ForwardObject = ForwardAddress<RelocationRange, RelocationRange>;
1183 ForwardObject forward_object(boot_image, app_image_objects);
1184 ForwardObject forward_metadata(boot_image, app_image_metadata);
1185 using ForwardCode = ForwardAddress<RelocationRange, RelocationRange>;
1186 ForwardCode forward_code(boot_image, app_oat);
1187 PatchObjectVisitor<kPointerSize, ForwardObject, ForwardCode> patch_object_visitor(
1188 forward_object,
1189 forward_metadata);
Andreas Gampea463b6a2016-08-12 21:53:32 -07001190 if (fixup_image) {
1191 // Two pass approach, fix up all classes first, then fix up non class-objects.
1192 // The visited bitmap is used to ensure that pointer arrays are not forwarded twice.
1193 std::unique_ptr<gc::accounting::ContinuousSpaceBitmap> visited_bitmap(
1194 gc::accounting::ContinuousSpaceBitmap::Create("Relocate bitmap",
1195 target_base,
1196 image_header.GetImageSize()));
Mathieu Chartier25602dc2018-12-11 11:31:57 -08001197 {
1198 TimingLogger::ScopedTiming timing("Fixup classes", &logger);
1199 const auto& class_table_section = image_header.GetClassTableSection();
1200 if (class_table_section.Size() > 0u) {
1201 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -08001202 ClassTableVisitor class_table_visitor(forward_object);
Mathieu Chartier25602dc2018-12-11 11:31:57 -08001203 size_t read_count = 0u;
1204 const uint8_t* data = target_base + class_table_section.Offset();
1205 // We avoid making a copy of the data since we want modifications to be propagated to the
1206 // memory map.
1207 ClassTable::ClassSet temp_set(data, /*make_copy_of_data=*/ false, &read_count);
1208 for (ClassTable::TableSlot& slot : temp_set) {
1209 slot.VisitRoot(class_table_visitor);
1210 mirror::Class* klass = slot.Read<kWithoutReadBarrier>();
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -08001211 if (!app_image_objects.InDest(klass)) {
Mathieu Chartier25602dc2018-12-11 11:31:57 -08001212 continue;
1213 }
1214 const bool already_marked = visited_bitmap->Set(klass);
1215 CHECK(!already_marked) << "App image class already visited";
1216 patch_object_visitor.VisitClass(klass);
1217 // Then patch the non-embedded vtable and iftable.
1218 mirror::PointerArray* vtable = klass->GetVTable<kVerifyNone, kWithoutReadBarrier>();
1219 if (vtable != nullptr &&
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -08001220 app_image_objects.InDest(vtable) &&
Mathieu Chartier25602dc2018-12-11 11:31:57 -08001221 !visited_bitmap->Set(vtable)) {
1222 patch_object_visitor.VisitPointerArray(vtable);
1223 }
1224 auto* iftable = klass->GetIfTable<kVerifyNone, kWithoutReadBarrier>();
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -08001225 if (iftable != nullptr && app_image_objects.InDest(iftable)) {
Mathieu Chartier25602dc2018-12-11 11:31:57 -08001226 // Avoid processing the fields of iftable since we will process them later anyways
1227 // below.
1228 int32_t ifcount = klass->GetIfTableCount<kVerifyNone>();
1229 for (int32_t i = 0; i != ifcount; ++i) {
1230 mirror::PointerArray* unpatched_ifarray =
1231 iftable->GetMethodArrayOrNull<kVerifyNone, kWithoutReadBarrier>(i);
1232 if (unpatched_ifarray != nullptr) {
1233 // The iftable has not been patched, so we need to explicitly adjust the pointer.
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -08001234 mirror::PointerArray* ifarray = forward_object(unpatched_ifarray);
1235 if (app_image_objects.InDest(ifarray) && !visited_bitmap->Set(ifarray)) {
Mathieu Chartier25602dc2018-12-11 11:31:57 -08001236 patch_object_visitor.VisitPointerArray(ifarray);
1237 }
1238 }
1239 }
1240 }
1241 }
1242 }
1243 }
1244
1245 // Fixup objects may read fields in the boot image, use the mutator lock here for sanity.
1246 // Though its probably not required.
Mathieu Chartier2ffc74b2019-01-03 19:25:41 -08001247 TimingLogger::ScopedTiming timing("Fixup objects", &logger);
Andreas Gampea463b6a2016-08-12 21:53:32 -07001248 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier25602dc2018-12-11 11:31:57 -08001249 // Need to update the image to be at the target base.
Mathieu Chartier25602dc2018-12-11 11:31:57 -08001250 uintptr_t objects_begin = reinterpret_cast<uintptr_t>(target_base + objects_section.Offset());
1251 uintptr_t objects_end = reinterpret_cast<uintptr_t>(target_base + objects_section.End());
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -08001252 FixupObjectVisitor<ForwardObject> fixup_object_visitor(visited_bitmap.get(), forward_object);
Andreas Gampea463b6a2016-08-12 21:53:32 -07001253 bitmap->VisitMarkedRange(objects_begin, objects_end, fixup_object_visitor);
1254 // Fixup image roots.
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -08001255 CHECK(app_image_objects.InSource(reinterpret_cast<uintptr_t>(
Vladimir Markoc13fbd82018-06-04 16:16:28 +01001256 image_header.GetImageRoots<kWithoutReadBarrier>().Ptr())));
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -08001257 image_header.RelocateImageObjects(app_image_objects.Delta());
Andreas Gampea463b6a2016-08-12 21:53:32 -07001258 CHECK_EQ(image_header.GetImageBegin(), target_base);
1259 // Fix up dex cache DexFile pointers.
1260 auto* dex_caches = image_header.GetImageRoot<kWithoutReadBarrier>(ImageHeader::kDexCaches)->
Vladimir Marko98db89c2018-09-07 11:45:46 +01001261 AsObjectArray<mirror::DexCache, kVerifyNone>();
Andreas Gampea463b6a2016-08-12 21:53:32 -07001262 for (int32_t i = 0, count = dex_caches->GetLength(); i < count; ++i) {
1263 mirror::DexCache* dex_cache = dex_caches->Get<kVerifyNone, kWithoutReadBarrier>(i);
Mathieu Chartier25602dc2018-12-11 11:31:57 -08001264 CHECK(dex_cache != nullptr);
1265 patch_object_visitor.VisitDexCacheArrays(dex_cache);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001266 }
1267 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001268 {
1269 // Only touches objects in the app image, no need for mutator lock.
Andreas Gampea463b6a2016-08-12 21:53:32 -07001270 TimingLogger::ScopedTiming timing("Fixup methods", &logger);
Mathieu Chartier9d5956a2019-03-22 11:29:08 -07001271 image_header.VisitPackedArtMethods([&](ArtMethod& method) NO_THREAD_SAFETY_ANALYSIS {
1272 // TODO: Consider a separate visitor for runtime vs normal methods.
1273 if (UNLIKELY(method.IsRuntimeMethod())) {
1274 ImtConflictTable* table = method.GetImtConflictTable(kPointerSize);
1275 if (table != nullptr) {
1276 ImtConflictTable* new_table = forward_metadata(table);
1277 if (table != new_table) {
1278 method.SetImtConflictTable(new_table, kPointerSize);
1279 }
1280 }
1281 const void* old_code = method.GetEntryPointFromQuickCompiledCodePtrSize(kPointerSize);
1282 const void* new_code = forward_code(old_code);
1283 if (old_code != new_code) {
1284 method.SetEntryPointFromQuickCompiledCodePtrSize(new_code, kPointerSize);
1285 }
1286 } else {
1287 method.UpdateObjectsForImageRelocation(forward_object);
1288 method.UpdateEntrypoints(forward_code, kPointerSize);
1289 }
1290 }, target_base, kPointerSize);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001291 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07001292 if (fixup_image) {
1293 {
1294 // Only touches objects in the app image, no need for mutator lock.
1295 TimingLogger::ScopedTiming timing("Fixup fields", &logger);
Mathieu Chartier9d5956a2019-03-22 11:29:08 -07001296 image_header.VisitPackedArtFields([&](ArtField& field) NO_THREAD_SAFETY_ANALYSIS {
1297 field.UpdateObjects(forward_object);
1298 }, target_base);
Andreas Gampea463b6a2016-08-12 21:53:32 -07001299 }
1300 {
1301 TimingLogger::ScopedTiming timing("Fixup imt", &logger);
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -08001302 image_header.VisitPackedImTables(forward_metadata, target_base, kPointerSize);
Andreas Gampea463b6a2016-08-12 21:53:32 -07001303 }
1304 {
1305 TimingLogger::ScopedTiming timing("Fixup conflict tables", &logger);
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -08001306 image_header.VisitPackedImtConflictTables(forward_metadata, target_base, kPointerSize);
Andreas Gampea463b6a2016-08-12 21:53:32 -07001307 }
1308 // In the app image case, the image methods are actually in the boot image.
1309 image_header.RelocateImageMethods(boot_image.Delta());
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001310 // Fix up the intern table.
1311 const auto& intern_table_section = image_header.GetInternedStringsSection();
1312 if (intern_table_section.Size() > 0u) {
1313 TimingLogger::ScopedTiming timing("Fixup intern table", &logger);
1314 ScopedObjectAccess soa(Thread::Current());
1315 // Fixup the pointers in the newly written intern table to contain image addresses.
1316 InternTable temp_intern_table;
1317 // Note that we require that ReadFromMemory does not make an internal copy of the elements
1318 // so that the VisitRoots() will update the memory directly rather than the copies.
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001319 temp_intern_table.AddTableFromMemory(target_base + intern_table_section.Offset(),
1320 [&](InternTable::UnorderedSet& strings)
1321 REQUIRES_SHARED(Locks::mutator_lock_) {
1322 for (GcRoot<mirror::String>& root : strings) {
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -08001323 root = GcRoot<mirror::String>(forward_object(root.Read<kWithoutReadBarrier>()));
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001324 }
Mathieu Chartier8cc418e2018-10-31 10:54:30 -07001325 }, /*is_boot_image=*/ false);
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001326 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001327 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07001328 if (VLOG_IS_ON(image)) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07001329 logger.Dump(LOG_STREAM(INFO));
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001330 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07001331 return true;
Andreas Gampe7fa55782016-06-15 17:45:01 -07001332 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07001333};
Hiroshi Yamauchibd0fb612014-05-20 13:46:00 -07001334
Vladimir Marko82e1e272018-08-20 13:38:06 +00001335class ImageSpace::BootImageLoader {
1336 public:
Vladimir Marko91f10322018-12-07 18:04:10 +00001337 BootImageLoader(const std::vector<std::string>& boot_class_path,
1338 const std::vector<std::string>& boot_class_path_locations,
1339 const std::string& image_location,
Vladimir Marko3364d182019-03-13 13:55:01 +00001340 InstructionSet image_isa,
1341 bool relocate,
1342 bool executable,
1343 bool is_zygote)
Vladimir Marko91f10322018-12-07 18:04:10 +00001344 : boot_class_path_(boot_class_path),
1345 boot_class_path_locations_(boot_class_path_locations),
1346 image_location_(image_location),
Vladimir Marko82e1e272018-08-20 13:38:06 +00001347 image_isa_(image_isa),
Vladimir Marko3364d182019-03-13 13:55:01 +00001348 relocate_(relocate),
1349 executable_(executable),
1350 is_zygote_(is_zygote),
Vladimir Marko82e1e272018-08-20 13:38:06 +00001351 has_system_(false),
1352 has_cache_(false),
1353 is_global_cache_(true),
Vladimir Markoe3070022018-08-22 09:36:19 +00001354 dalvik_cache_exists_(false),
Vladimir Marko82e1e272018-08-20 13:38:06 +00001355 dalvik_cache_(),
1356 cache_filename_() {
1357 }
1358
1359 bool IsZygote() const { return is_zygote_; }
1360
1361 void FindImageFiles() {
1362 std::string system_filename;
Vladimir Marko82e1e272018-08-20 13:38:06 +00001363 bool found_image = FindImageFilenameImpl(image_location_.c_str(),
1364 image_isa_,
1365 &has_system_,
1366 &system_filename,
Vladimir Markoe3070022018-08-22 09:36:19 +00001367 &dalvik_cache_exists_,
Vladimir Marko82e1e272018-08-20 13:38:06 +00001368 &dalvik_cache_,
1369 &is_global_cache_,
1370 &has_cache_,
1371 &cache_filename_);
Vladimir Markoe3070022018-08-22 09:36:19 +00001372 DCHECK(!dalvik_cache_exists_ || !dalvik_cache_.empty());
Vladimir Marko82e1e272018-08-20 13:38:06 +00001373 DCHECK_EQ(found_image, has_system_ || has_cache_);
1374 }
1375
1376 bool HasSystem() const { return has_system_; }
1377 bool HasCache() const { return has_cache_; }
1378
Vladimir Markoe3070022018-08-22 09:36:19 +00001379 bool DalvikCacheExists() const { return dalvik_cache_exists_; }
Vladimir Marko82e1e272018-08-20 13:38:06 +00001380 bool IsGlobalCache() const { return is_global_cache_; }
1381
1382 const std::string& GetDalvikCache() const {
Vladimir Marko82e1e272018-08-20 13:38:06 +00001383 return dalvik_cache_;
1384 }
1385
1386 const std::string& GetCacheFilename() const {
Vladimir Marko82e1e272018-08-20 13:38:06 +00001387 return cache_filename_;
1388 }
1389
Andreas Gampe86823542019-02-25 09:38:49 -08001390 bool LoadFromSystem(bool validate_oat_file,
1391 size_t extra_reservation_size,
Vladimir Markod44d7032018-08-30 13:02:31 +01001392 /*out*/std::vector<std::unique_ptr<space::ImageSpace>>* boot_image_spaces,
1393 /*out*/MemMap* extra_reservation,
1394 /*out*/std::string* error_msg) REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001395 TimingLogger logger(__PRETTY_FUNCTION__, /*precise=*/ true, VLOG_IS_ON(image));
Vladimir Marko82e1e272018-08-20 13:38:06 +00001396 std::string filename = GetSystemImageFilename(image_location_.c_str(), image_isa_);
Vladimir Markoc09cd052018-08-23 16:36:36 +01001397
Vladimir Marko7391c8c2018-11-21 17:58:44 +00001398 if (!LoadFromFile(filename,
Andreas Gampe86823542019-02-25 09:38:49 -08001399 validate_oat_file,
Vladimir Marko7391c8c2018-11-21 17:58:44 +00001400 extra_reservation_size,
1401 &logger,
1402 boot_image_spaces,
1403 extra_reservation,
1404 error_msg)) {
Vladimir Markoc09cd052018-08-23 16:36:36 +01001405 return false;
1406 }
1407
Vladimir Marko4df2d802018-09-27 16:42:44 +00001408 if (VLOG_IS_ON(image)) {
Vladimir Marko312f10e2018-11-21 12:35:24 +00001409 LOG(INFO) << "ImageSpace::BootImageLoader::LoadFromSystem exiting "
1410 << boot_image_spaces->front();
Vladimir Marko4df2d802018-09-27 16:42:44 +00001411 logger.Dump(LOG_STREAM(INFO));
1412 }
Vladimir Marko82e1e272018-08-20 13:38:06 +00001413 return true;
1414 }
1415
1416 bool LoadFromDalvikCache(
Vladimir Marko82e1e272018-08-20 13:38:06 +00001417 bool validate_oat_file,
Vladimir Markod44d7032018-08-30 13:02:31 +01001418 size_t extra_reservation_size,
1419 /*out*/std::vector<std::unique_ptr<space::ImageSpace>>* boot_image_spaces,
1420 /*out*/MemMap* extra_reservation,
1421 /*out*/std::string* error_msg) REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001422 TimingLogger logger(__PRETTY_FUNCTION__, /*precise=*/ true, VLOG_IS_ON(image));
Vladimir Marko82e1e272018-08-20 13:38:06 +00001423 DCHECK(DalvikCacheExists());
Vladimir Markoc09cd052018-08-23 16:36:36 +01001424
Vladimir Marko7391c8c2018-11-21 17:58:44 +00001425 if (!LoadFromFile(cache_filename_,
1426 validate_oat_file,
1427 extra_reservation_size,
1428 &logger,
1429 boot_image_spaces,
1430 extra_reservation,
1431 error_msg)) {
Vladimir Markoc09cd052018-08-23 16:36:36 +01001432 return false;
1433 }
1434
Vladimir Marko4df2d802018-09-27 16:42:44 +00001435 if (VLOG_IS_ON(image)) {
Vladimir Marko312f10e2018-11-21 12:35:24 +00001436 LOG(INFO) << "ImageSpace::BootImageLoader::LoadFromDalvikCache exiting "
1437 << boot_image_spaces->front();
Vladimir Marko4df2d802018-09-27 16:42:44 +00001438 logger.Dump(LOG_STREAM(INFO));
1439 }
Vladimir Marko82e1e272018-08-20 13:38:06 +00001440 return true;
1441 }
1442
1443 private:
Vladimir Marko7391c8c2018-11-21 17:58:44 +00001444 bool LoadFromFile(
1445 const std::string& filename,
1446 bool validate_oat_file,
1447 size_t extra_reservation_size,
1448 TimingLogger* logger,
1449 /*out*/std::vector<std::unique_ptr<space::ImageSpace>>* boot_image_spaces,
1450 /*out*/MemMap* extra_reservation,
1451 /*out*/std::string* error_msg) REQUIRES_SHARED(Locks::mutator_lock_) {
1452 ImageHeader system_hdr;
1453 if (!ReadSpecificImageHeader(filename.c_str(), &system_hdr)) {
1454 *error_msg = StringPrintf("Cannot read header of %s", filename.c_str());
1455 return false;
1456 }
Vladimir Marko0ace5632018-12-14 11:11:47 +00001457 if (system_hdr.GetComponentCount() == 0u ||
1458 system_hdr.GetComponentCount() > boot_class_path_.size()) {
1459 *error_msg = StringPrintf("Unexpected component count in %s, received %u, "
1460 "expected non-zero and <= %zu",
Vladimir Marko7391c8c2018-11-21 17:58:44 +00001461 filename.c_str(),
1462 system_hdr.GetComponentCount(),
1463 boot_class_path_.size());
1464 return false;
1465 }
1466 MemMap image_reservation;
1467 MemMap local_extra_reservation;
1468 if (!ReserveBootImageMemory(system_hdr.GetImageReservationSize(),
1469 reinterpret_cast32<uint32_t>(system_hdr.GetImageBegin()),
1470 extra_reservation_size,
1471 &image_reservation,
1472 &local_extra_reservation,
1473 error_msg)) {
1474 return false;
1475 }
1476
Vladimir Marko0ace5632018-12-14 11:11:47 +00001477 ArrayRef<const std::string> provided_locations(boot_class_path_locations_.data(),
1478 system_hdr.GetComponentCount());
Vladimir Marko7391c8c2018-11-21 17:58:44 +00001479 std::vector<std::string> locations =
Vladimir Marko0ace5632018-12-14 11:11:47 +00001480 ExpandMultiImageLocations(provided_locations, image_location_);
Vladimir Marko7391c8c2018-11-21 17:58:44 +00001481 std::vector<std::string> filenames =
Vladimir Marko0ace5632018-12-14 11:11:47 +00001482 ExpandMultiImageLocations(provided_locations, filename);
Vladimir Marko7391c8c2018-11-21 17:58:44 +00001483 DCHECK_EQ(locations.size(), filenames.size());
1484 std::vector<std::unique_ptr<ImageSpace>> spaces;
1485 spaces.reserve(locations.size());
1486 for (std::size_t i = 0u, size = locations.size(); i != size; ++i) {
1487 spaces.push_back(Load(locations[i], filenames[i], logger, &image_reservation, error_msg));
1488 const ImageSpace* space = spaces.back().get();
1489 if (space == nullptr) {
1490 return false;
1491 }
1492 uint32_t expected_component_count = (i == 0u) ? system_hdr.GetComponentCount() : 0u;
1493 uint32_t expected_reservation_size = (i == 0u) ? system_hdr.GetImageReservationSize() : 0u;
1494 if (!Loader::CheckImageReservationSize(*space, expected_reservation_size, error_msg) ||
1495 !Loader::CheckImageComponentCount(*space, expected_component_count, error_msg)) {
1496 return false;
1497 }
1498 }
1499 for (size_t i = 0u, size = spaces.size(); i != size; ++i) {
1500 std::string expected_boot_class_path =
Vladimir Marko0ace5632018-12-14 11:11:47 +00001501 (i == 0u) ? android::base::Join(provided_locations, ':') : std::string();
Vladimir Marko7391c8c2018-11-21 17:58:44 +00001502 if (!OpenOatFile(spaces[i].get(),
1503 boot_class_path_[i],
1504 expected_boot_class_path,
1505 validate_oat_file,
1506 logger,
1507 &image_reservation,
1508 error_msg)) {
1509 return false;
1510 }
1511 }
1512 if (!CheckReservationExhausted(image_reservation, error_msg)) {
1513 return false;
1514 }
1515
1516 MaybeRelocateSpaces(spaces, logger);
Vladimir Marko7391c8c2018-11-21 17:58:44 +00001517 boot_image_spaces->swap(spaces);
1518 *extra_reservation = std::move(local_extra_reservation);
1519 return true;
1520 }
1521
Mathieu Chartierd3f037b2018-12-06 23:50:56 -08001522 private:
1523 class RelocateVisitor {
1524 public:
1525 explicit RelocateVisitor(uint32_t diff) : diff_(diff) {}
Vladimir Marko4df2d802018-09-27 16:42:44 +00001526
Mathieu Chartierd3f037b2018-12-06 23:50:56 -08001527 template <typename T>
1528 ALWAYS_INLINE T* operator()(T* src) const {
1529 DCHECK(src != nullptr);
1530 return reinterpret_cast32<T*>(reinterpret_cast32<uint32_t>(src) + diff_);
Vladimir Marko4df2d802018-09-27 16:42:44 +00001531 }
Vladimir Marko4df2d802018-09-27 16:42:44 +00001532
Mathieu Chartierd3f037b2018-12-06 23:50:56 -08001533 private:
1534 const uint32_t diff_;
1535 };
Vladimir Marko4df2d802018-09-27 16:42:44 +00001536
Mathieu Chartier9d5956a2019-03-22 11:29:08 -07001537 static void** PointerAddress(ArtMethod* method, MemberOffset offset) {
1538 return reinterpret_cast<void**>(reinterpret_cast<uint8_t*>(method) + offset.Uint32Value());
1539 }
1540
Vladimir Marko4df2d802018-09-27 16:42:44 +00001541 template <PointerSize kPointerSize>
1542 static void DoRelocateSpaces(const std::vector<std::unique_ptr<ImageSpace>>& spaces,
1543 uint32_t diff) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier2ffc74b2019-01-03 19:25:41 -08001544 std::unique_ptr<gc::accounting::ContinuousSpaceBitmap> patched_objects(
1545 gc::accounting::ContinuousSpaceBitmap::Create(
1546 "Marked objects",
1547 spaces.front()->Begin(),
1548 spaces.back()->End() - spaces.front()->Begin()));
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -08001549 using PatchRelocateVisitor = PatchObjectVisitor<kPointerSize, RelocateVisitor, RelocateVisitor>;
Mathieu Chartierd3f037b2018-12-06 23:50:56 -08001550 RelocateVisitor relocate_visitor(diff);
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -08001551 PatchRelocateVisitor patch_object_visitor(relocate_visitor, relocate_visitor);
Vladimir Marko4df2d802018-09-27 16:42:44 +00001552
1553 mirror::Class* dcheck_class_class = nullptr; // Used only for a DCHECK().
Mathieu Chartier9d5956a2019-03-22 11:29:08 -07001554 for (const std::unique_ptr<ImageSpace>& space : spaces) {
Vladimir Marko4df2d802018-09-27 16:42:44 +00001555 // First patch the image header. The `diff` is OK for patching 32-bit fields but
1556 // the 64-bit method fields in the ImageHeader may need a negative `delta`.
1557 reinterpret_cast<ImageHeader*>(space->Begin())->RelocateImage(
Vladimir Markoe37b7912019-03-13 10:52:39 +00001558 (reinterpret_cast32<uint32_t>(space->Begin()) >= -diff) // Would `begin+diff` overflow?
Vladimir Marko4df2d802018-09-27 16:42:44 +00001559 ? -static_cast<int64_t>(-diff) : static_cast<int64_t>(diff));
1560
1561 // Patch fields and methods.
1562 const ImageHeader& image_header = space->GetImageHeader();
Mathieu Chartier9d5956a2019-03-22 11:29:08 -07001563 image_header.VisitPackedArtFields([&](ArtField& field) REQUIRES_SHARED(Locks::mutator_lock_) {
1564 patch_object_visitor.template PatchGcRoot</*kMayBeNull=*/ false>(
1565 &field.DeclaringClassRoot());
1566 }, space->Begin());
1567 image_header.VisitPackedArtMethods([&](ArtMethod& method)
1568 REQUIRES_SHARED(Locks::mutator_lock_) {
1569 patch_object_visitor.PatchGcRoot(&method.DeclaringClassRoot());
1570 void** data_address = PointerAddress(&method, ArtMethod::DataOffset(kPointerSize));
1571 patch_object_visitor.PatchNativePointer(data_address);
1572 void** entrypoint_address =
1573 PointerAddress(&method, ArtMethod::EntryPointFromQuickCompiledCodeOffset(kPointerSize));
1574 patch_object_visitor.PatchNativePointer(entrypoint_address);
1575 }, space->Begin(), kPointerSize);
Mathieu Chartierd3f037b2018-12-06 23:50:56 -08001576 auto method_table_visitor = [&](ArtMethod* method) {
Vladimir Marko4df2d802018-09-27 16:42:44 +00001577 DCHECK(method != nullptr);
Mathieu Chartierd3f037b2018-12-06 23:50:56 -08001578 return relocate_visitor(method);
Vladimir Marko4df2d802018-09-27 16:42:44 +00001579 };
1580 image_header.VisitPackedImTables(method_table_visitor, space->Begin(), kPointerSize);
1581 image_header.VisitPackedImtConflictTables(method_table_visitor, space->Begin(), kPointerSize);
1582
1583 // Patch the intern table.
1584 if (image_header.GetInternedStringsSection().Size() != 0u) {
1585 const uint8_t* data = space->Begin() + image_header.GetInternedStringsSection().Offset();
1586 size_t read_count;
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001587 InternTable::UnorderedSet temp_set(data, /*make_copy_of_data=*/ false, &read_count);
Vladimir Marko4df2d802018-09-27 16:42:44 +00001588 for (GcRoot<mirror::String>& slot : temp_set) {
Mathieu Chartierd3f037b2018-12-06 23:50:56 -08001589 patch_object_visitor.template PatchGcRoot</*kMayBeNull=*/ false>(&slot);
Vladimir Marko4df2d802018-09-27 16:42:44 +00001590 }
1591 }
1592
1593 // Patch the class table and classes, so that we can traverse class hierarchy to
1594 // determine the types of other objects when we visit them later.
1595 if (image_header.GetClassTableSection().Size() != 0u) {
1596 uint8_t* data = space->Begin() + image_header.GetClassTableSection().Offset();
1597 size_t read_count;
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001598 ClassTable::ClassSet temp_set(data, /*make_copy_of_data=*/ false, &read_count);
Vladimir Marko4df2d802018-09-27 16:42:44 +00001599 DCHECK(!temp_set.empty());
Mathieu Chartierd3f037b2018-12-06 23:50:56 -08001600 ClassTableVisitor class_table_visitor(relocate_visitor);
Vladimir Marko4df2d802018-09-27 16:42:44 +00001601 for (ClassTable::TableSlot& slot : temp_set) {
1602 slot.VisitRoot(class_table_visitor);
1603 mirror::Class* klass = slot.Read<kWithoutReadBarrier>();
1604 DCHECK(klass != nullptr);
Mathieu Chartier2ffc74b2019-01-03 19:25:41 -08001605 patched_objects->Set(klass);
Vladimir Marko4df2d802018-09-27 16:42:44 +00001606 patch_object_visitor.VisitClass(klass);
1607 if (kIsDebugBuild) {
1608 mirror::Class* class_class = klass->GetClass<kVerifyNone, kWithoutReadBarrier>();
1609 if (dcheck_class_class == nullptr) {
1610 dcheck_class_class = class_class;
1611 } else {
1612 CHECK_EQ(class_class, dcheck_class_class);
1613 }
1614 }
1615 // Then patch the non-embedded vtable and iftable.
1616 mirror::PointerArray* vtable = klass->GetVTable<kVerifyNone, kWithoutReadBarrier>();
Mathieu Chartier2ffc74b2019-01-03 19:25:41 -08001617 if (vtable != nullptr && !patched_objects->Set(vtable)) {
Vladimir Marko4df2d802018-09-27 16:42:44 +00001618 patch_object_visitor.VisitPointerArray(vtable);
1619 }
1620 auto* iftable = klass->GetIfTable<kVerifyNone, kWithoutReadBarrier>();
1621 if (iftable != nullptr) {
Vladimir Markodbcb48f2018-11-12 11:47:04 +00001622 int32_t ifcount = klass->GetIfTableCount<kVerifyNone>();
Vladimir Marko4df2d802018-09-27 16:42:44 +00001623 for (int32_t i = 0; i != ifcount; ++i) {
1624 mirror::PointerArray* unpatched_ifarray =
1625 iftable->GetMethodArrayOrNull<kVerifyNone, kWithoutReadBarrier>(i);
1626 if (unpatched_ifarray != nullptr) {
1627 // The iftable has not been patched, so we need to explicitly adjust the pointer.
Mathieu Chartierd3f037b2018-12-06 23:50:56 -08001628 mirror::PointerArray* ifarray = relocate_visitor(unpatched_ifarray);
Mathieu Chartier2ffc74b2019-01-03 19:25:41 -08001629 if (!patched_objects->Set(ifarray)) {
Vladimir Marko4df2d802018-09-27 16:42:44 +00001630 patch_object_visitor.VisitPointerArray(ifarray);
1631 }
1632 }
1633 }
1634 }
1635 }
1636 }
1637 }
1638
1639 // Patch class roots now, so that we can recognize mirror::Method and mirror::Constructor.
1640 ObjPtr<mirror::Class> method_class;
1641 ObjPtr<mirror::Class> constructor_class;
1642 {
1643 const ImageSpace* space = spaces.front().get();
1644 const ImageHeader& image_header = space->GetImageHeader();
1645
1646 ObjPtr<mirror::ObjectArray<mirror::Object>> image_roots =
1647 image_header.GetImageRoots<kWithoutReadBarrier>();
Mathieu Chartier2ffc74b2019-01-03 19:25:41 -08001648 patched_objects->Set(image_roots.Ptr());
Vladimir Marko4df2d802018-09-27 16:42:44 +00001649 patch_object_visitor.VisitObject(image_roots.Ptr());
1650
1651 ObjPtr<mirror::ObjectArray<mirror::Class>> class_roots =
1652 ObjPtr<mirror::ObjectArray<mirror::Class>>::DownCast(MakeObjPtr(
1653 image_header.GetImageRoot<kWithoutReadBarrier>(ImageHeader::kClassRoots)));
Mathieu Chartier2ffc74b2019-01-03 19:25:41 -08001654 patched_objects->Set(class_roots.Ptr());
Vladimir Marko4df2d802018-09-27 16:42:44 +00001655 patch_object_visitor.VisitObject(class_roots.Ptr());
1656
1657 method_class = GetClassRoot<mirror::Method, kWithoutReadBarrier>(class_roots);
1658 constructor_class = GetClassRoot<mirror::Constructor, kWithoutReadBarrier>(class_roots);
1659 }
1660
Vladimir Markoafe14eb2018-10-01 12:11:14 +01001661 for (size_t s = 0u, size = spaces.size(); s != size; ++s) {
Vladimir Marko4df2d802018-09-27 16:42:44 +00001662 const ImageSpace* space = spaces[s].get();
1663 const ImageHeader& image_header = space->GetImageHeader();
1664
1665 static_assert(IsAligned<kObjectAlignment>(sizeof(ImageHeader)), "Header alignment check");
1666 uint32_t objects_end = image_header.GetObjectsSection().Size();
1667 DCHECK_ALIGNED(objects_end, kObjectAlignment);
1668 for (uint32_t pos = sizeof(ImageHeader); pos != objects_end; ) {
1669 mirror::Object* object = reinterpret_cast<mirror::Object*>(space->Begin() + pos);
Mathieu Chartier2ffc74b2019-01-03 19:25:41 -08001670 if (!patched_objects->Test(object)) {
1671 // This is the last pass over objects, so we do not need to Set().
Vladimir Marko4df2d802018-09-27 16:42:44 +00001672 patch_object_visitor.VisitObject(object);
1673 mirror::Class* klass = object->GetClass<kVerifyNone, kWithoutReadBarrier>();
1674 if (klass->IsDexCacheClass<kVerifyNone>()) {
1675 // Patch dex cache array pointers and elements.
1676 mirror::DexCache* dex_cache = object->AsDexCache<kVerifyNone, kWithoutReadBarrier>();
1677 patch_object_visitor.VisitDexCacheArrays(dex_cache);
1678 } else if (klass == method_class || klass == constructor_class) {
1679 // Patch the ArtMethod* in the mirror::Executable subobject.
1680 ObjPtr<mirror::Executable> as_executable =
1681 ObjPtr<mirror::Executable>::DownCast(MakeObjPtr(object));
1682 ArtMethod* unpatched_method = as_executable->GetArtMethod<kVerifyNone>();
Mathieu Chartierd3f037b2018-12-06 23:50:56 -08001683 ArtMethod* patched_method = relocate_visitor(unpatched_method);
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001684 as_executable->SetArtMethod</*kTransactionActive=*/ false,
1685 /*kCheckTransaction=*/ true,
Vladimir Marko4df2d802018-09-27 16:42:44 +00001686 kVerifyNone>(patched_method);
1687 }
1688 }
1689 pos += RoundUp(object->SizeOf<kVerifyNone>(), kObjectAlignment);
1690 }
1691 }
1692 }
1693
Vladimir Marko3364d182019-03-13 13:55:01 +00001694 void MaybeRelocateSpaces(const std::vector<std::unique_ptr<ImageSpace>>& spaces,
1695 TimingLogger* logger)
Vladimir Marko4df2d802018-09-27 16:42:44 +00001696 REQUIRES_SHARED(Locks::mutator_lock_) {
1697 TimingLogger::ScopedTiming timing("MaybeRelocateSpaces", logger);
1698 ImageSpace* first_space = spaces.front().get();
1699 const ImageHeader& first_space_header = first_space->GetImageHeader();
1700 uint32_t diff =
1701 static_cast<uint32_t>(first_space->Begin() - first_space_header.GetImageBegin());
Vladimir Marko3364d182019-03-13 13:55:01 +00001702 if (!relocate_) {
Vladimir Marko4df2d802018-09-27 16:42:44 +00001703 DCHECK_EQ(diff, 0u);
1704 return;
1705 }
1706
1707 PointerSize pointer_size = first_space_header.GetPointerSize();
1708 if (pointer_size == PointerSize::k64) {
1709 DoRelocateSpaces<PointerSize::k64>(spaces, diff);
1710 } else {
1711 DoRelocateSpaces<PointerSize::k32>(spaces, diff);
1712 }
1713 }
1714
Vladimir Markoc09cd052018-08-23 16:36:36 +01001715 std::unique_ptr<ImageSpace> Load(const std::string& image_location,
1716 const std::string& image_filename,
Vladimir Marko4df2d802018-09-27 16:42:44 +00001717 TimingLogger* logger,
Vladimir Markoc09cd052018-08-23 16:36:36 +01001718 /*inout*/MemMap* image_reservation,
Vladimir Markoc09cd052018-08-23 16:36:36 +01001719 /*out*/std::string* error_msg)
1720 REQUIRES_SHARED(Locks::mutator_lock_) {
1721 // Should this be a RDWR lock? This is only a defensive measure, as at
1722 // this point the image should exist.
1723 // However, only the zygote can write into the global dalvik-cache, so
1724 // restrict to zygote processes, or any process that isn't using
1725 // /data/dalvik-cache (which we assume to be allowed to write there).
1726 const bool rw_lock = is_zygote_ || !is_global_cache_;
1727
1728 // Note that we must not use the file descriptor associated with
1729 // ScopedFlock::GetFile to Init the image file. We want the file
1730 // descriptor (and the associated exclusive lock) to be released when
1731 // we leave Create.
1732 ScopedFlock image = LockedFile::Open(image_filename.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001733 /*flags=*/ rw_lock ? (O_CREAT | O_RDWR) : O_RDONLY,
1734 /*block=*/ true,
Vladimir Markoc09cd052018-08-23 16:36:36 +01001735 error_msg);
1736
1737 VLOG(startup) << "Using image file " << image_filename.c_str() << " for image location "
1738 << image_location;
1739 // If we are in /system we can assume the image is good. We can also
1740 // assume this if we are using a relocated image (i.e. image checksum
1741 // matches) since this is only different by the offset. We need this to
1742 // make sure that host tests continue to work.
1743 // Since we are the boot image, pass null since we load the oat file from the boot image oat
1744 // file name.
1745 return Loader::Init(image_filename.c_str(),
1746 image_location.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001747 /*oat_file=*/ nullptr,
Vladimir Marko4df2d802018-09-27 16:42:44 +00001748 logger,
Vladimir Markoc09cd052018-08-23 16:36:36 +01001749 image_reservation,
Vladimir Markoc09cd052018-08-23 16:36:36 +01001750 error_msg);
1751 }
1752
Vladimir Marko312f10e2018-11-21 12:35:24 +00001753 bool OpenOatFile(ImageSpace* space,
Vladimir Marko91f10322018-12-07 18:04:10 +00001754 const std::string& dex_filename,
1755 const std::string& expected_boot_class_path,
Vladimir Marko312f10e2018-11-21 12:35:24 +00001756 bool validate_oat_file,
1757 TimingLogger* logger,
1758 /*inout*/MemMap* image_reservation,
1759 /*out*/std::string* error_msg) {
1760 // VerifyImageAllocations() will be called later in Runtime::Init()
1761 // as some class roots like ArtMethod::java_lang_reflect_ArtMethod_
1762 // and ArtField::java_lang_reflect_ArtField_, which are used from
1763 // Object::SizeOf() which VerifyImageAllocations() calls, are not
1764 // set yet at this point.
1765 DCHECK(image_reservation != nullptr);
1766 std::unique_ptr<OatFile> oat_file;
1767 {
1768 TimingLogger::ScopedTiming timing("OpenOatFile", logger);
1769 std::string oat_filename =
1770 ImageHeader::GetOatLocationFromImageLocation(space->GetImageFilename());
Vladimir Marko91f10322018-12-07 18:04:10 +00001771 std::string oat_location =
1772 ImageHeader::GetOatLocationFromImageLocation(space->GetImageLocation());
Vladimir Marko312f10e2018-11-21 12:35:24 +00001773
1774 oat_file.reset(OatFile::Open(/*zip_fd=*/ -1,
1775 oat_filename,
Vladimir Marko91f10322018-12-07 18:04:10 +00001776 oat_location,
Vladimir Marko3364d182019-03-13 13:55:01 +00001777 executable_,
Vladimir Marko312f10e2018-11-21 12:35:24 +00001778 /*low_4gb=*/ false,
Vladimir Marko91f10322018-12-07 18:04:10 +00001779 /*abs_dex_location=*/ dex_filename.c_str(),
Vladimir Marko312f10e2018-11-21 12:35:24 +00001780 image_reservation,
1781 error_msg));
1782 if (oat_file == nullptr) {
1783 *error_msg = StringPrintf("Failed to open oat file '%s' referenced from image %s: %s",
1784 oat_filename.c_str(),
1785 space->GetName(),
1786 error_msg->c_str());
1787 return false;
1788 }
1789 const ImageHeader& image_header = space->GetImageHeader();
1790 uint32_t oat_checksum = oat_file->GetOatHeader().GetChecksum();
1791 uint32_t image_oat_checksum = image_header.GetOatChecksum();
1792 if (oat_checksum != image_oat_checksum) {
1793 *error_msg = StringPrintf("Failed to match oat file checksum 0x%x to expected oat checksum"
1794 " 0x%x in image %s",
1795 oat_checksum,
1796 image_oat_checksum,
1797 space->GetName());
1798 return false;
1799 }
Vladimir Marko91f10322018-12-07 18:04:10 +00001800 const char* oat_boot_class_path =
1801 oat_file->GetOatHeader().GetStoreValueByKey(OatHeader::kBootClassPathKey);
1802 oat_boot_class_path = (oat_boot_class_path != nullptr) ? oat_boot_class_path : "";
1803 if (expected_boot_class_path != oat_boot_class_path) {
1804 *error_msg = StringPrintf("Failed to match oat boot class path %s to expected "
1805 "boot class path %s in image %s",
1806 oat_boot_class_path,
1807 expected_boot_class_path.c_str(),
1808 space->GetName());
1809 return false;
1810 }
Vladimir Marko312f10e2018-11-21 12:35:24 +00001811 ptrdiff_t relocation_diff = space->Begin() - image_header.GetImageBegin();
1812 CHECK(image_header.GetOatDataBegin() != nullptr);
1813 uint8_t* oat_data_begin = image_header.GetOatDataBegin() + relocation_diff;
1814 if (oat_file->Begin() != oat_data_begin) {
1815 *error_msg = StringPrintf("Oat file '%s' referenced from image %s has unexpected begin"
1816 " %p v. %p",
1817 oat_filename.c_str(),
1818 space->GetName(),
1819 oat_file->Begin(),
1820 oat_data_begin);
1821 return false;
1822 }
1823 }
1824 if (validate_oat_file) {
1825 TimingLogger::ScopedTiming timing("ValidateOatFile", logger);
1826 if (!ImageSpace::ValidateOatFile(*oat_file, error_msg)) {
1827 DCHECK(!error_msg->empty());
1828 return false;
1829 }
1830 }
1831 space->oat_file_ = std::move(oat_file);
1832 space->oat_file_non_owned_ = space->oat_file_.get();
1833 return true;
1834 }
1835
Vladimir Marko312f10e2018-11-21 12:35:24 +00001836 bool ReserveBootImageMemory(uint32_t reservation_size,
1837 uint32_t image_start,
Vladimir Markod44d7032018-08-30 13:02:31 +01001838 size_t extra_reservation_size,
Vladimir Markoc09cd052018-08-23 16:36:36 +01001839 /*out*/MemMap* image_reservation,
Vladimir Markod44d7032018-08-30 13:02:31 +01001840 /*out*/MemMap* extra_reservation,
Vladimir Markoc09cd052018-08-23 16:36:36 +01001841 /*out*/std::string* error_msg) {
Vladimir Marko7391c8c2018-11-21 17:58:44 +00001842 DCHECK_ALIGNED(reservation_size, kPageSize);
1843 DCHECK_ALIGNED(image_start, kPageSize);
Vladimir Markoc09cd052018-08-23 16:36:36 +01001844 DCHECK(!image_reservation->IsValid());
Vladimir Marko312f10e2018-11-21 12:35:24 +00001845 DCHECK_LT(extra_reservation_size, std::numeric_limits<uint32_t>::max() - reservation_size);
1846 size_t total_size = reservation_size + extra_reservation_size;
Vladimir Markoae581ed2018-10-08 09:29:05 +01001847 // If relocating, choose a random address for ALSR.
Vladimir Marko3364d182019-03-13 13:55:01 +00001848 uint32_t addr = relocate_ ? ART_BASE_ADDRESS + ChooseRelocationOffsetDelta() : image_start;
Vladimir Markoc09cd052018-08-23 16:36:36 +01001849 *image_reservation =
1850 MemMap::MapAnonymous("Boot image reservation",
Vladimir Markoae581ed2018-10-08 09:29:05 +01001851 reinterpret_cast32<uint8_t*>(addr),
1852 total_size,
Vladimir Markoc09cd052018-08-23 16:36:36 +01001853 PROT_NONE,
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001854 /*low_4gb=*/ true,
1855 /*reuse=*/ false,
1856 /*reservation=*/ nullptr,
Vladimir Markoc09cd052018-08-23 16:36:36 +01001857 error_msg);
1858 if (!image_reservation->IsValid()) {
1859 return false;
1860 }
Vladimir Markod44d7032018-08-30 13:02:31 +01001861 DCHECK(!extra_reservation->IsValid());
1862 if (extra_reservation_size != 0u) {
1863 DCHECK_ALIGNED(extra_reservation_size, kPageSize);
1864 DCHECK_LT(extra_reservation_size, image_reservation->Size());
1865 uint8_t* split = image_reservation->End() - extra_reservation_size;
1866 *extra_reservation = image_reservation->RemapAtEnd(split,
1867 "Boot image extra reservation",
1868 PROT_NONE,
1869 error_msg);
1870 if (!extra_reservation->IsValid()) {
1871 return false;
1872 }
1873 }
Vladimir Markoc09cd052018-08-23 16:36:36 +01001874
1875 return true;
1876 }
1877
Vladimir Marko312f10e2018-11-21 12:35:24 +00001878 bool CheckReservationExhausted(const MemMap& image_reservation, /*out*/std::string* error_msg) {
Vladimir Markoc09cd052018-08-23 16:36:36 +01001879 if (image_reservation.IsValid()) {
1880 *error_msg = StringPrintf("Excessive image reservation after loading boot image: %p-%p",
1881 image_reservation.Begin(),
1882 image_reservation.End());
1883 return false;
1884 }
Vladimir Markoc09cd052018-08-23 16:36:36 +01001885 return true;
1886 }
1887
Vladimir Marko91f10322018-12-07 18:04:10 +00001888 const std::vector<std::string>& boot_class_path_;
1889 const std::vector<std::string>& boot_class_path_locations_;
Vladimir Marko82e1e272018-08-20 13:38:06 +00001890 const std::string& image_location_;
1891 InstructionSet image_isa_;
Vladimir Marko3364d182019-03-13 13:55:01 +00001892 bool relocate_;
1893 bool executable_;
Vladimir Marko82e1e272018-08-20 13:38:06 +00001894 bool is_zygote_;
1895 bool has_system_;
1896 bool has_cache_;
1897 bool is_global_cache_;
Vladimir Markoe3070022018-08-22 09:36:19 +00001898 bool dalvik_cache_exists_;
Vladimir Marko82e1e272018-08-20 13:38:06 +00001899 std::string dalvik_cache_;
1900 std::string cache_filename_;
1901};
1902
Andreas Gampea463b6a2016-08-12 21:53:32 -07001903static constexpr uint64_t kLowSpaceValue = 50 * MB;
1904static constexpr uint64_t kTmpFsSentinelValue = 384 * MB;
1905
1906// Read the free space of the cache partition and make a decision whether to keep the generated
1907// image. This is to try to mitigate situations where the system might run out of space later.
1908static bool CheckSpace(const std::string& cache_filename, std::string* error_msg) {
1909 // Using statvfs vs statvfs64 because of b/18207376, and it is enough for all practical purposes.
1910 struct statvfs buf;
1911
1912 int res = TEMP_FAILURE_RETRY(statvfs(cache_filename.c_str(), &buf));
1913 if (res != 0) {
1914 // Could not stat. Conservatively tell the system to delete the image.
1915 *error_msg = "Could not stat the filesystem, assuming low-memory situation.";
1916 return false;
Nicolas Geoffray1bc977c2016-01-23 14:15:49 +00001917 }
Nicolas Geoffray1bc977c2016-01-23 14:15:49 +00001918
Andreas Gampea463b6a2016-08-12 21:53:32 -07001919 uint64_t fs_overall_size = buf.f_bsize * static_cast<uint64_t>(buf.f_blocks);
1920 // Zygote is privileged, but other things are not. Use bavail.
1921 uint64_t fs_free_size = buf.f_bsize * static_cast<uint64_t>(buf.f_bavail);
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001922
Andreas Gampea463b6a2016-08-12 21:53:32 -07001923 // Take the overall size as an indicator for a tmpfs, which is being used for the decryption
1924 // environment. We do not want to fail quickening the boot image there, as it is beneficial
1925 // for time-to-UI.
1926 if (fs_overall_size > kTmpFsSentinelValue) {
1927 if (fs_free_size < kLowSpaceValue) {
1928 *error_msg = StringPrintf("Low-memory situation: only %4.2f megabytes available, need at "
1929 "least %" PRIu64 ".",
1930 static_cast<double>(fs_free_size) / MB,
1931 kLowSpaceValue / MB);
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001932 return false;
1933 }
1934 }
1935 return true;
1936}
1937
Vladimir Marko82e1e272018-08-20 13:38:06 +00001938bool ImageSpace::LoadBootImage(
Vladimir Marko91f10322018-12-07 18:04:10 +00001939 const std::vector<std::string>& boot_class_path,
1940 const std::vector<std::string>& boot_class_path_locations,
Vladimir Marko82e1e272018-08-20 13:38:06 +00001941 const std::string& image_location,
1942 const InstructionSet image_isa,
Andreas Gampe86823542019-02-25 09:38:49 -08001943 ImageSpaceLoadingOrder order,
Vladimir Marko3364d182019-03-13 13:55:01 +00001944 bool relocate,
1945 bool executable,
1946 bool is_zygote,
Vladimir Markod44d7032018-08-30 13:02:31 +01001947 size_t extra_reservation_size,
1948 /*out*/std::vector<std::unique_ptr<space::ImageSpace>>* boot_image_spaces,
1949 /*out*/MemMap* extra_reservation) {
Andreas Gampea463b6a2016-08-12 21:53:32 -07001950 ScopedTrace trace(__FUNCTION__);
1951
Vladimir Marko82e1e272018-08-20 13:38:06 +00001952 DCHECK(boot_image_spaces != nullptr);
1953 DCHECK(boot_image_spaces->empty());
Vladimir Markod44d7032018-08-30 13:02:31 +01001954 DCHECK_ALIGNED(extra_reservation_size, kPageSize);
1955 DCHECK(extra_reservation != nullptr);
Vladimir Marko82e1e272018-08-20 13:38:06 +00001956 DCHECK_NE(image_isa, InstructionSet::kNone);
1957
1958 if (image_location.empty()) {
1959 return false;
1960 }
1961
Vladimir Marko3364d182019-03-13 13:55:01 +00001962 BootImageLoader loader(boot_class_path,
1963 boot_class_path_locations,
1964 image_location,
1965 image_isa,
1966 relocate,
1967 executable,
1968 is_zygote);
Vladimir Marko82e1e272018-08-20 13:38:06 +00001969
Andreas Gampea463b6a2016-08-12 21:53:32 -07001970 // Step 0: Extra zygote work.
1971
1972 // Step 0.a: If we're the zygote, mark boot.
Vladimir Marko82e1e272018-08-20 13:38:06 +00001973 if (loader.IsZygote() && CanWriteToDalvikCache(image_isa)) {
Andreas Gampea463b6a2016-08-12 21:53:32 -07001974 MarkZygoteStart(image_isa, Runtime::Current()->GetZygoteMaxFailedBoots());
1975 }
1976
Vladimir Marko82e1e272018-08-20 13:38:06 +00001977 loader.FindImageFiles();
1978
Andreas Gampea463b6a2016-08-12 21:53:32 -07001979 // Step 0.b: If we're the zygote, check for free space, and prune the cache preemptively,
1980 // if necessary. While the runtime may be fine (it is pretty tolerant to
1981 // out-of-disk-space situations), other parts of the platform are not.
1982 //
1983 // The advantage of doing this proactively is that the later steps are simplified,
1984 // i.e., we do not need to code retries.
Vladimir Marko3364d182019-03-13 13:55:01 +00001985 bool low_space = false;
Vladimir Marko82e1e272018-08-20 13:38:06 +00001986 if (loader.IsZygote() && loader.DalvikCacheExists()) {
Andreas Gampe6e74abb2018-03-01 17:33:19 -08001987 // Extra checks for the zygote. These only apply when loading the first image, explained below.
Vladimir Marko82e1e272018-08-20 13:38:06 +00001988 const std::string& dalvik_cache = loader.GetDalvikCache();
Andreas Gampea463b6a2016-08-12 21:53:32 -07001989 DCHECK(!dalvik_cache.empty());
1990 std::string local_error_msg;
Andreas Gampe6e74abb2018-03-01 17:33:19 -08001991 bool check_space = CheckSpace(dalvik_cache, &local_error_msg);
Vladimir Marko4df2d802018-09-27 16:42:44 +00001992 if (!check_space) {
Andreas Gampea463b6a2016-08-12 21:53:32 -07001993 LOG(WARNING) << local_error_msg << " Preemptively pruning the dalvik cache.";
1994 PruneDalvikCache(image_isa);
1995
1996 // Re-evaluate the image.
Vladimir Marko82e1e272018-08-20 13:38:06 +00001997 loader.FindImageFiles();
Vladimir Marko3364d182019-03-13 13:55:01 +00001998
Andreas Gampe6e74abb2018-03-01 17:33:19 -08001999 // Disable compilation/patching - we do not want to fill up the space again.
Vladimir Marko3364d182019-03-13 13:55:01 +00002000 low_space = true;
Andreas Gampe6e74abb2018-03-01 17:33:19 -08002001 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07002002 }
2003
2004 // Collect all the errors.
2005 std::vector<std::string> error_msgs;
2006
Andreas Gampe86823542019-02-25 09:38:49 -08002007 auto try_load_from = [&](auto has_fn, auto load_fn, bool validate_oat_file) {
2008 if ((loader.*has_fn)()) {
2009 std::string local_error_msg;
2010 if ((loader.*load_fn)(validate_oat_file,
2011 extra_reservation_size,
2012 boot_image_spaces,
2013 extra_reservation,
2014 &local_error_msg)) {
2015 return true;
2016 }
2017 error_msgs.push_back(local_error_msg);
2018 }
2019 return false;
2020 };
Andreas Gampea463b6a2016-08-12 21:53:32 -07002021
Andreas Gampe86823542019-02-25 09:38:49 -08002022 auto try_load_from_system = [&]() {
2023 return try_load_from(&BootImageLoader::HasSystem, &BootImageLoader::LoadFromSystem, false);
2024 };
2025 auto try_load_from_cache = [&]() {
2026 return try_load_from(&BootImageLoader::HasCache, &BootImageLoader::LoadFromDalvikCache, true);
2027 };
2028
2029 auto invoke_sequentially = [](auto first, auto second) {
2030 return first() || second();
2031 };
2032
2033 // Step 1+2: Check system and cache images in the asked-for order.
2034 if (order == ImageSpaceLoadingOrder::kSystemFirst) {
2035 if (invoke_sequentially(try_load_from_system, try_load_from_cache)) {
Vladimir Marko82e1e272018-08-20 13:38:06 +00002036 return true;
Andreas Gampea463b6a2016-08-12 21:53:32 -07002037 }
Andreas Gampe86823542019-02-25 09:38:49 -08002038 } else {
2039 if (invoke_sequentially(try_load_from_cache, try_load_from_system)) {
Vladimir Marko4df2d802018-09-27 16:42:44 +00002040 return true;
Andreas Gampea463b6a2016-08-12 21:53:32 -07002041 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07002042 }
2043
Vladimir Marko82e1e272018-08-20 13:38:06 +00002044 // Step 3: We do not have an existing image in /system,
2045 // so generate an image into the dalvik cache.
Vladimir Markoe3070022018-08-22 09:36:19 +00002046 if (!loader.HasSystem() && loader.DalvikCacheExists()) {
Andreas Gampea463b6a2016-08-12 21:53:32 -07002047 std::string local_error_msg;
Vladimir Marko3364d182019-03-13 13:55:01 +00002048 if (low_space || !Runtime::Current()->IsImageDex2OatEnabled()) {
Andreas Gampea463b6a2016-08-12 21:53:32 -07002049 local_error_msg = "Image compilation disabled.";
Vladimir Marko3364d182019-03-13 13:55:01 +00002050 } else if (ImageCreationAllowed(loader.IsGlobalCache(),
2051 image_isa,
2052 is_zygote,
2053 &local_error_msg)) {
Vladimir Marko82e1e272018-08-20 13:38:06 +00002054 bool compilation_success =
2055 GenerateImage(loader.GetCacheFilename(), image_isa, &local_error_msg);
Andreas Gampea463b6a2016-08-12 21:53:32 -07002056 if (compilation_success) {
Vladimir Markof4efa9e2018-10-17 14:12:45 +01002057 if (loader.LoadFromDalvikCache(/*validate_oat_file=*/ false,
Vladimir Markod44d7032018-08-30 13:02:31 +01002058 extra_reservation_size,
Vladimir Marko82e1e272018-08-20 13:38:06 +00002059 boot_image_spaces,
Vladimir Markod44d7032018-08-30 13:02:31 +01002060 extra_reservation,
Vladimir Marko82e1e272018-08-20 13:38:06 +00002061 &local_error_msg)) {
2062 return true;
Andreas Gampea463b6a2016-08-12 21:53:32 -07002063 }
2064 }
2065 }
2066 error_msgs.push_back(StringPrintf("Cannot compile image to %s: %s",
Vladimir Marko82e1e272018-08-20 13:38:06 +00002067 loader.GetCacheFilename().c_str(),
Andreas Gampea463b6a2016-08-12 21:53:32 -07002068 local_error_msg.c_str()));
2069 }
2070
Vladimir Marko82e1e272018-08-20 13:38:06 +00002071 // We failed. Prune the cache the free up space, create a compound error message
2072 // and return false.
Vladimir Marko3364d182019-03-13 13:55:01 +00002073 if (loader.DalvikCacheExists()) {
2074 PruneDalvikCache(image_isa);
2075 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07002076
2077 std::ostringstream oss;
2078 bool first = true;
Andreas Gampe4c481a42016-11-03 08:21:59 -07002079 for (const auto& msg : error_msgs) {
Andreas Gampea463b6a2016-08-12 21:53:32 -07002080 if (!first) {
2081 oss << "\n ";
2082 }
2083 oss << msg;
2084 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07002085
Vladimir Marko82e1e272018-08-20 13:38:06 +00002086 LOG(ERROR) << "Could not create image space with image file '" << image_location << "'. "
2087 << "Attempting to fall back to imageless running. Error was: " << oss.str();
Andreas Gampea463b6a2016-08-12 21:53:32 -07002088
Vladimir Marko82e1e272018-08-20 13:38:06 +00002089 return false;
Andreas Gampe2bd84282016-12-05 12:37:36 -08002090}
2091
Igor Murashkin8275fba2017-05-02 15:58:02 -07002092ImageSpace::~ImageSpace() {
Vladimir Marko3364d182019-03-13 13:55:01 +00002093 // Everything done by member destructors. Classes forward-declared in header are now defined.
Igor Murashkin8275fba2017-05-02 15:58:02 -07002094}
2095
Andreas Gampea463b6a2016-08-12 21:53:32 -07002096std::unique_ptr<ImageSpace> ImageSpace::CreateFromAppImage(const char* image,
2097 const OatFile* oat_file,
2098 std::string* error_msg) {
Vladimir Marko312f10e2018-11-21 12:35:24 +00002099 // Note: The oat file has already been validated.
Vladimir Marko4df2d802018-09-27 16:42:44 +00002100 return Loader::InitAppImage(image,
2101 image,
Vladimir Marko4df2d802018-09-27 16:42:44 +00002102 oat_file,
Vladimir Markof4efa9e2018-10-17 14:12:45 +01002103 /*image_reservation=*/ nullptr,
Vladimir Marko4df2d802018-09-27 16:42:44 +00002104 error_msg);
Andreas Gampea463b6a2016-08-12 21:53:32 -07002105}
2106
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07002107const OatFile* ImageSpace::GetOatFile() const {
Andreas Gampe88da3b02015-06-12 20:38:49 -07002108 return oat_file_non_owned_;
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07002109}
2110
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -07002111std::unique_ptr<const OatFile> ImageSpace::ReleaseOatFile() {
2112 CHECK(oat_file_ != nullptr);
2113 return std::move(oat_file_);
Ian Rogers1d54e732013-05-02 21:10:01 -07002114}
2115
Ian Rogers1d54e732013-05-02 21:10:01 -07002116void ImageSpace::Dump(std::ostream& os) const {
2117 os << GetType()
Mathieu Chartier590fee92013-09-13 13:46:47 -07002118 << " begin=" << reinterpret_cast<void*>(Begin())
Ian Rogers1d54e732013-05-02 21:10:01 -07002119 << ",end=" << reinterpret_cast<void*>(End())
2120 << ",size=" << PrettySize(Size())
2121 << ",name=\"" << GetName() << "\"]";
2122}
2123
Richard Uhler84f50ae2017-02-06 15:12:45 +00002124bool ImageSpace::ValidateOatFile(const OatFile& oat_file, std::string* error_msg) {
David Sehr013fd802018-01-11 22:55:24 -08002125 const ArtDexFileLoader dex_file_loader;
Andreas Gampeb40d3612018-06-26 15:49:42 -07002126 for (const OatDexFile* oat_dex_file : oat_file.GetOatDexFiles()) {
Richard Uhler84f50ae2017-02-06 15:12:45 +00002127 const std::string& dex_file_location = oat_dex_file->GetDexFileLocation();
2128
2129 // Skip multidex locations - These will be checked when we visit their
2130 // corresponding primary non-multidex location.
Mathieu Chartier79c87da2017-10-10 11:54:29 -07002131 if (DexFileLoader::IsMultiDexLocation(dex_file_location.c_str())) {
Richard Uhler84f50ae2017-02-06 15:12:45 +00002132 continue;
2133 }
2134
2135 std::vector<uint32_t> checksums;
David Sehr013fd802018-01-11 22:55:24 -08002136 if (!dex_file_loader.GetMultiDexChecksums(dex_file_location.c_str(), &checksums, error_msg)) {
Richard Uhler84f50ae2017-02-06 15:12:45 +00002137 *error_msg = StringPrintf("ValidateOatFile failed to get checksums of dex file '%s' "
2138 "referenced by oat file %s: %s",
2139 dex_file_location.c_str(),
2140 oat_file.GetLocation().c_str(),
2141 error_msg->c_str());
2142 return false;
2143 }
2144 CHECK(!checksums.empty());
2145 if (checksums[0] != oat_dex_file->GetDexFileLocationChecksum()) {
2146 *error_msg = StringPrintf("ValidateOatFile found checksum mismatch between oat file "
2147 "'%s' and dex file '%s' (0x%x != 0x%x)",
2148 oat_file.GetLocation().c_str(),
2149 dex_file_location.c_str(),
2150 oat_dex_file->GetDexFileLocationChecksum(),
2151 checksums[0]);
2152 return false;
2153 }
2154
2155 // Verify checksums for any related multidex entries.
2156 for (size_t i = 1; i < checksums.size(); i++) {
Mathieu Chartier79c87da2017-10-10 11:54:29 -07002157 std::string multi_dex_location = DexFileLoader::GetMultiDexLocation(
2158 i,
2159 dex_file_location.c_str());
Andreas Gampeb40d3612018-06-26 15:49:42 -07002160 const OatDexFile* multi_dex = oat_file.GetOatDexFile(multi_dex_location.c_str(),
2161 nullptr,
2162 error_msg);
Richard Uhler84f50ae2017-02-06 15:12:45 +00002163 if (multi_dex == nullptr) {
2164 *error_msg = StringPrintf("ValidateOatFile oat file '%s' is missing entry '%s'",
2165 oat_file.GetLocation().c_str(),
2166 multi_dex_location.c_str());
2167 return false;
2168 }
2169
2170 if (checksums[i] != multi_dex->GetDexFileLocationChecksum()) {
2171 *error_msg = StringPrintf("ValidateOatFile found checksum mismatch between oat file "
2172 "'%s' and dex file '%s' (0x%x != 0x%x)",
2173 oat_file.GetLocation().c_str(),
2174 multi_dex_location.c_str(),
2175 multi_dex->GetDexFileLocationChecksum(),
2176 checksums[i]);
2177 return false;
2178 }
2179 }
2180 }
2181 return true;
2182}
2183
Vladimir Marko0ace5632018-12-14 11:11:47 +00002184std::string ImageSpace::GetBootClassPathChecksums(const std::vector<std::string>& boot_class_path,
2185 const std::string& image_location,
2186 InstructionSet image_isa,
Andreas Gampe86823542019-02-25 09:38:49 -08002187 ImageSpaceLoadingOrder order,
Vladimir Marko0ace5632018-12-14 11:11:47 +00002188 /*out*/std::string* error_msg) {
2189 std::string system_filename;
2190 bool has_system = false;
2191 std::string cache_filename;
2192 bool has_cache = false;
2193 bool dalvik_cache_exists = false;
2194 bool is_global_cache = false;
2195 if (!FindImageFilename(image_location.c_str(),
2196 image_isa,
2197 &system_filename,
2198 &has_system,
2199 &cache_filename,
2200 &dalvik_cache_exists,
2201 &has_cache,
2202 &is_global_cache)) {
2203 *error_msg = StringPrintf("Unable to find image file for %s and %s",
2204 image_location.c_str(),
2205 GetInstructionSetString(image_isa));
2206 return std::string();
2207 }
2208
2209 DCHECK(has_system || has_cache);
Andreas Gampe86823542019-02-25 09:38:49 -08002210 const std::string& filename = (order == ImageSpaceLoadingOrder::kSystemFirst)
2211 ? (has_system ? system_filename : cache_filename)
2212 : (has_cache ? cache_filename : system_filename);
Vladimir Marko0ace5632018-12-14 11:11:47 +00002213 std::unique_ptr<ImageHeader> header = ReadSpecificImageHeader(filename.c_str(), error_msg);
2214 if (header == nullptr) {
2215 return std::string();
2216 }
2217 if (header->GetComponentCount() == 0u || header->GetComponentCount() > boot_class_path.size()) {
2218 *error_msg = StringPrintf("Unexpected component count in %s, received %u, "
2219 "expected non-zero and <= %zu",
2220 filename.c_str(),
2221 header->GetComponentCount(),
2222 boot_class_path.size());
2223 return std::string();
2224 }
2225
2226 std::string boot_image_checksum =
2227 StringPrintf("i;%d/%08x", header->GetComponentCount(), header->GetImageChecksum());
2228 ArrayRef<const std::string> boot_class_path_tail =
2229 ArrayRef<const std::string>(boot_class_path).SubArray(header->GetComponentCount());
2230 for (const std::string& bcp_filename : boot_class_path_tail) {
2231 std::vector<std::unique_ptr<const DexFile>> dex_files;
2232 const ArtDexFileLoader dex_file_loader;
2233 if (!dex_file_loader.Open(bcp_filename.c_str(),
2234 bcp_filename, // The location does not matter here.
2235 /*verify=*/ false,
2236 /*verify_checksum=*/ false,
2237 error_msg,
2238 &dex_files)) {
2239 return std::string();
2240 }
2241 DCHECK(!dex_files.empty());
2242 StringAppendF(&boot_image_checksum, ":d");
2243 for (const std::unique_ptr<const DexFile>& dex_file : dex_files) {
2244 StringAppendF(&boot_image_checksum, "/%08x", dex_file->GetLocationChecksum());
2245 }
2246 }
2247 return boot_image_checksum;
2248}
2249
2250std::string ImageSpace::GetBootClassPathChecksums(
2251 const std::vector<ImageSpace*>& image_spaces,
2252 const std::vector<const DexFile*>& boot_class_path) {
2253 DCHECK(!image_spaces.empty());
2254 const ImageHeader& primary_header = image_spaces.front()->GetImageHeader();
2255 uint32_t component_count = primary_header.GetComponentCount();
2256 DCHECK_EQ(component_count, image_spaces.size());
2257 std::string boot_image_checksum =
2258 StringPrintf("i;%d/%08x", component_count, primary_header.GetImageChecksum());
2259 size_t pos = 0u;
2260 for (const ImageSpace* space : image_spaces) {
2261 size_t num_dex_files = space->oat_file_non_owned_->GetOatDexFiles().size();
2262 if (kIsDebugBuild) {
2263 CHECK_NE(num_dex_files, 0u);
2264 CHECK_LE(space->oat_file_non_owned_->GetOatDexFiles().size(), boot_class_path.size() - pos);
2265 for (size_t i = 0; i != num_dex_files; ++i) {
2266 CHECK_EQ(space->oat_file_non_owned_->GetOatDexFiles()[i]->GetDexFileLocation(),
2267 boot_class_path[pos + i]->GetLocation());
2268 }
2269 }
2270 pos += num_dex_files;
2271 }
2272 ArrayRef<const DexFile* const> boot_class_path_tail =
2273 ArrayRef<const DexFile* const>(boot_class_path).SubArray(pos);
2274 DCHECK(boot_class_path_tail.empty() ||
2275 !DexFileLoader::IsMultiDexLocation(boot_class_path_tail.front()->GetLocation().c_str()));
2276 for (const DexFile* dex_file : boot_class_path_tail) {
2277 if (!DexFileLoader::IsMultiDexLocation(dex_file->GetLocation().c_str())) {
2278 StringAppendF(&boot_image_checksum, ":d");
2279 }
2280 StringAppendF(&boot_image_checksum, "/%08x", dex_file->GetLocationChecksum());
2281 }
2282 return boot_image_checksum;
2283}
2284
Vladimir Marko91f10322018-12-07 18:04:10 +00002285std::vector<std::string> ImageSpace::ExpandMultiImageLocations(
2286 const std::vector<std::string>& dex_locations,
2287 const std::string& image_location) {
Vladimir Marko0ace5632018-12-14 11:11:47 +00002288 return ExpandMultiImageLocations(ArrayRef<const std::string>(dex_locations), image_location);
2289}
2290
2291std::vector<std::string> ImageSpace::ExpandMultiImageLocations(
2292 ArrayRef<const std::string> dex_locations,
2293 const std::string& image_location) {
Vladimir Marko91f10322018-12-07 18:04:10 +00002294 DCHECK(!dex_locations.empty());
Andreas Gampe8994a042015-12-30 19:03:17 +00002295
Vladimir Marko91f10322018-12-07 18:04:10 +00002296 // Find the path.
2297 size_t last_slash = image_location.rfind('/');
2298 CHECK_NE(last_slash, std::string::npos);
Andreas Gampe8994a042015-12-30 19:03:17 +00002299
Vladimir Marko91f10322018-12-07 18:04:10 +00002300 // We also need to honor path components that were encoded through '@'. Otherwise the loading
2301 // code won't be able to find the images.
2302 if (image_location.find('@', last_slash) != std::string::npos) {
2303 last_slash = image_location.rfind('@');
Andreas Gampe8994a042015-12-30 19:03:17 +00002304 }
Andreas Gampe8994a042015-12-30 19:03:17 +00002305
Vladimir Marko91f10322018-12-07 18:04:10 +00002306 // Find the dot separating the primary image name from the extension.
2307 size_t last_dot = image_location.rfind('.');
2308 // Extract the extension and base (the path and primary image name).
2309 std::string extension;
2310 std::string base = image_location;
2311 if (last_dot != std::string::npos && last_dot > last_slash) {
2312 extension = image_location.substr(last_dot); // Including the dot.
2313 base.resize(last_dot);
Andreas Gampe8994a042015-12-30 19:03:17 +00002314 }
Vladimir Marko91f10322018-12-07 18:04:10 +00002315 // For non-empty primary image name, add '-' to the `base`.
2316 if (last_slash + 1u != base.size()) {
2317 base += '-';
2318 }
2319
2320 std::vector<std::string> locations;
2321 locations.reserve(dex_locations.size());
2322 locations.push_back(image_location);
2323
2324 // Now create the other names. Use a counted loop to skip the first one.
2325 for (size_t i = 1u; i < dex_locations.size(); ++i) {
2326 // Replace path with `base` (i.e. image path and prefix) and replace the original
2327 // extension (if any) with `extension`.
2328 std::string name = dex_locations[i];
2329 size_t last_dex_slash = name.rfind('/');
2330 if (last_dex_slash != std::string::npos) {
2331 name = name.substr(last_dex_slash + 1);
2332 }
2333 size_t last_dex_dot = name.rfind('.');
2334 if (last_dex_dot != std::string::npos) {
2335 name.resize(last_dex_dot);
2336 }
2337 locations.push_back(base + name + extension);
2338 }
2339 return locations;
Andreas Gampe8994a042015-12-30 19:03:17 +00002340}
2341
Mathieu Chartierd5f3f322016-03-21 14:05:56 -07002342void ImageSpace::DumpSections(std::ostream& os) const {
2343 const uint8_t* base = Begin();
2344 const ImageHeader& header = GetImageHeader();
2345 for (size_t i = 0; i < ImageHeader::kSectionCount; ++i) {
2346 auto section_type = static_cast<ImageHeader::ImageSections>(i);
2347 const ImageSection& section = header.GetImageSection(section_type);
2348 os << section_type << " " << reinterpret_cast<const void*>(base + section.Offset())
2349 << "-" << reinterpret_cast<const void*>(base + section.End()) << "\n";
2350 }
2351}
2352
Mathieu Chartier6e7a72c2019-03-07 21:40:10 -08002353void ImageSpace::DisablePreResolvedStrings() {
2354 // Clear dex cache pointers.
2355 ObjPtr<mirror::ObjectArray<mirror::DexCache>> dex_caches =
2356 GetImageHeader().GetImageRoot(ImageHeader::kDexCaches)->AsObjectArray<mirror::DexCache>();
2357 for (size_t len = dex_caches->GetLength(), i = 0; i < len; ++i) {
2358 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
2359 dex_cache->ClearPreResolvedStrings();
2360 }
2361}
2362
2363void ImageSpace::ReleaseMetadata() {
2364 const ImageSection& metadata = GetImageHeader().GetMetadataSection();
2365 VLOG(image) << "Releasing " << metadata.Size() << " image metadata bytes";
2366 // In the case where new app images may have been added around the checkpoint, ensure that we
2367 // don't madvise the cache for these.
2368 ObjPtr<mirror::ObjectArray<mirror::DexCache>> dex_caches =
2369 GetImageHeader().GetImageRoot(ImageHeader::kDexCaches)->AsObjectArray<mirror::DexCache>();
2370 bool have_startup_cache = false;
2371 for (size_t len = dex_caches->GetLength(), i = 0; i < len; ++i) {
2372 ObjPtr<mirror::DexCache> dex_cache = dex_caches->Get(i);
2373 if (dex_cache->NumPreResolvedStrings() != 0u) {
2374 have_startup_cache = true;
2375 }
2376 }
2377 // Only safe to do for images that have their preresolved strings caches disabled. This is because
2378 // uncompressed images madvise to the original unrelocated image contents.
2379 if (!have_startup_cache) {
2380 // Avoid using ZeroAndReleasePages since the zero fill might not be word atomic.
2381 uint8_t* const page_begin = AlignUp(Begin() + metadata.Offset(), kPageSize);
2382 uint8_t* const page_end = AlignDown(Begin() + metadata.End(), kPageSize);
2383 if (page_begin < page_end) {
2384 CHECK_NE(madvise(page_begin, page_end - page_begin, MADV_DONTNEED), -1) << "madvise failed";
2385 }
2386 }
2387}
2388
Ian Rogers1d54e732013-05-02 21:10:01 -07002389} // namespace space
2390} // namespace gc
2391} // namespace art