blob: 4a2dbf5209e7ce53810e16c845410a4ceebfa9b4 [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,
262 std::string* error_msg) {
Alex Lighta59dd802014-07-02 16:28:08 -0700263 std::string system_filename;
264 bool has_system = false;
265 std::string cache_filename;
266 bool has_cache = false;
267 bool dalvik_cache_exists = false;
Andreas Gampe3c13a792014-09-18 20:56:04 -0700268 bool is_global_cache = false;
Vladimir Marko4df2d802018-09-27 16:42:44 +0000269 if (FindImageFilename(image_location,
270 image_isa,
271 &system_filename,
272 &has_system,
273 &cache_filename,
274 &dalvik_cache_exists,
275 &has_cache,
276 &is_global_cache)) {
277 if (has_system) {
278 return ReadSpecificImageHeader(system_filename.c_str(), error_msg);
279 } else if (has_cache) {
280 return ReadSpecificImageHeader(cache_filename.c_str(), error_msg);
Narayan Kamath52f84882014-05-02 10:10:39 +0100281 }
Narayan Kamath52f84882014-05-02 10:10:39 +0100282 }
283
Brian Carlstrom31d8f522014-09-29 11:22:54 -0700284 *error_msg = StringPrintf("Unable to find image file for %s", image_location);
Narayan Kamath52f84882014-05-02 10:10:39 +0100285 return nullptr;
286}
287
Robert Sesekbfa1f8d2016-08-15 15:21:09 -0400288static bool CanWriteToDalvikCache(const InstructionSet isa) {
289 const std::string dalvik_cache = GetDalvikCache(GetInstructionSetString(isa));
290 if (access(dalvik_cache.c_str(), O_RDWR) == 0) {
291 return true;
292 } else if (errno != EACCES) {
293 PLOG(WARNING) << "CanWriteToDalvikCache returned error other than EACCES";
294 }
295 return false;
296}
297
298static bool ImageCreationAllowed(bool is_global_cache,
299 const InstructionSet isa,
300 std::string* error_msg) {
Andreas Gampe3c13a792014-09-18 20:56:04 -0700301 // Anyone can write into a "local" cache.
302 if (!is_global_cache) {
303 return true;
304 }
305
Robert Sesekbfa1f8d2016-08-15 15:21:09 -0400306 // Only the zygote running as root is allowed to create the global boot image.
307 // If the zygote is running as non-root (and cannot write to the dalvik-cache),
308 // then image creation is not allowed..
Andreas Gampe3c13a792014-09-18 20:56:04 -0700309 if (Runtime::Current()->IsZygote()) {
Robert Sesekbfa1f8d2016-08-15 15:21:09 -0400310 return CanWriteToDalvikCache(isa);
Andreas Gampe3c13a792014-09-18 20:56:04 -0700311 }
312
313 *error_msg = "Only the zygote can create the global boot image.";
314 return false;
315}
316
Mathieu Chartier31e89252013-08-28 11:29:12 -0700317void ImageSpace::VerifyImageAllocations() {
Ian Rogers13735952014-10-08 12:43:28 -0700318 uint8_t* current = Begin() + RoundUp(sizeof(ImageHeader), kObjectAlignment);
Mathieu Chartier31e89252013-08-28 11:29:12 -0700319 while (current < End()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700320 CHECK_ALIGNED(current, kObjectAlignment);
321 auto* obj = reinterpret_cast<mirror::Object*>(current);
Mathieu Chartier31e89252013-08-28 11:29:12 -0700322 CHECK(obj->GetClass() != nullptr) << "Image object at address " << obj << " has null class";
David Sehr709b0702016-10-13 09:12:37 -0700323 CHECK(live_bitmap_->Test(obj)) << obj->PrettyTypeOf();
Hiroshi Yamauchi12b58b22016-11-01 11:55:29 -0700324 if (kUseBakerReadBarrier) {
325 obj->AssertReadBarrierState();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800326 }
Mathieu Chartier31e89252013-08-28 11:29:12 -0700327 current += RoundUp(obj->SizeOf(), kObjectAlignment);
328 }
329}
330
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800331// Helper class for relocating from one range of memory to another.
332class RelocationRange {
333 public:
334 RelocationRange() = default;
335 RelocationRange(const RelocationRange&) = default;
336 RelocationRange(uintptr_t source, uintptr_t dest, uintptr_t length)
337 : source_(source),
338 dest_(dest),
339 length_(length) {}
340
Mathieu Chartier91edc622016-02-16 17:16:01 -0800341 bool InSource(uintptr_t address) const {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800342 return address - source_ < length_;
343 }
344
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -0800345 bool InDest(const void* dest) const {
346 return InDest(reinterpret_cast<uintptr_t>(dest));
347 }
348
Mathieu Chartier91edc622016-02-16 17:16:01 -0800349 bool InDest(uintptr_t address) const {
350 return address - dest_ < length_;
351 }
352
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800353 // Translate a source address to the destination space.
354 uintptr_t ToDest(uintptr_t address) const {
Mathieu Chartier91edc622016-02-16 17:16:01 -0800355 DCHECK(InSource(address));
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800356 return address + Delta();
357 }
358
359 // Returns the delta between the dest from the source.
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800360 uintptr_t Delta() const {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800361 return dest_ - source_;
362 }
363
364 uintptr_t Source() const {
365 return source_;
366 }
367
368 uintptr_t Dest() const {
369 return dest_;
370 }
371
372 uintptr_t Length() const {
373 return length_;
374 }
375
376 private:
377 const uintptr_t source_;
378 const uintptr_t dest_;
379 const uintptr_t length_;
380};
381
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800382std::ostream& operator<<(std::ostream& os, const RelocationRange& reloc) {
383 return os << "(" << reinterpret_cast<const void*>(reloc.Source()) << "-"
384 << reinterpret_cast<const void*>(reloc.Source() + reloc.Length()) << ")->("
385 << reinterpret_cast<const void*>(reloc.Dest()) << "-"
386 << reinterpret_cast<const void*>(reloc.Dest() + reloc.Length()) << ")";
387}
388
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -0800389template <PointerSize kPointerSize, typename HeapVisitor, typename NativeVisitor>
Mathieu Chartierd3f037b2018-12-06 23:50:56 -0800390class ImageSpace::PatchObjectVisitor final {
391 public:
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -0800392 explicit PatchObjectVisitor(HeapVisitor heap_visitor, NativeVisitor native_visitor)
393 : heap_visitor_(heap_visitor), native_visitor_(native_visitor) {}
Mathieu Chartierd3f037b2018-12-06 23:50:56 -0800394
395 void VisitClass(mirror::Class* klass) REQUIRES_SHARED(Locks::mutator_lock_) {
396 // A mirror::Class object consists of
397 // - instance fields inherited from j.l.Object,
398 // - instance fields inherited from j.l.Class,
399 // - embedded tables (vtable, interface method table),
400 // - static fields of the class itself.
401 // The reference fields are at the start of each field section (this is how the
402 // ClassLinker orders fields; except when that would create a gap between superclass
403 // fields and the first reference of the subclass due to alignment, it can be filled
404 // with smaller fields - but that's not the case for j.l.Object and j.l.Class).
405
406 DCHECK_ALIGNED(klass, kObjectAlignment);
407 static_assert(IsAligned<kHeapReferenceSize>(kObjectAlignment), "Object alignment check.");
408 // First, patch the `klass->klass_`, known to be a reference to the j.l.Class.class.
409 // This should be the only reference field in j.l.Object and we assert that below.
410 PatchReferenceField</*kMayBeNull=*/ false>(klass, mirror::Object::ClassOffset());
411 // Then patch the reference instance fields described by j.l.Class.class.
412 // Use the sizeof(Object) to determine where these reference fields start;
413 // this is the same as `class_class->GetFirstReferenceInstanceFieldOffset()`
414 // after patching but the j.l.Class may not have been patched yet.
415 mirror::Class* class_class = klass->GetClass<kVerifyNone, kWithoutReadBarrier>();
416 size_t num_reference_instance_fields = class_class->NumReferenceInstanceFields<kVerifyNone>();
417 DCHECK_NE(num_reference_instance_fields, 0u);
418 static_assert(IsAligned<kHeapReferenceSize>(sizeof(mirror::Object)), "Size alignment check.");
419 MemberOffset instance_field_offset(sizeof(mirror::Object));
420 for (size_t i = 0; i != num_reference_instance_fields; ++i) {
421 PatchReferenceField(klass, instance_field_offset);
422 static_assert(sizeof(mirror::HeapReference<mirror::Object>) == kHeapReferenceSize,
423 "Heap reference sizes equality check.");
424 instance_field_offset =
425 MemberOffset(instance_field_offset.Uint32Value() + kHeapReferenceSize);
426 }
427 // Now that we have patched the `super_class_`, if this is the j.l.Class.class,
428 // we can get a reference to j.l.Object.class and assert that it has only one
429 // reference instance field (the `klass_` patched above).
430 if (kIsDebugBuild && klass == class_class) {
431 ObjPtr<mirror::Class> object_class =
432 klass->GetSuperClass<kVerifyNone, kWithoutReadBarrier>();
433 CHECK_EQ(object_class->NumReferenceInstanceFields<kVerifyNone>(), 1u);
434 }
435 // Then patch static fields.
436 size_t num_reference_static_fields = klass->NumReferenceStaticFields<kVerifyNone>();
437 if (num_reference_static_fields != 0u) {
438 MemberOffset static_field_offset =
439 klass->GetFirstReferenceStaticFieldOffset<kVerifyNone>(kPointerSize);
440 for (size_t i = 0; i != num_reference_static_fields; ++i) {
441 PatchReferenceField(klass, static_field_offset);
442 static_assert(sizeof(mirror::HeapReference<mirror::Object>) == kHeapReferenceSize,
443 "Heap reference sizes equality check.");
444 static_field_offset =
445 MemberOffset(static_field_offset.Uint32Value() + kHeapReferenceSize);
446 }
447 }
448 // Then patch native pointers.
449 klass->FixupNativePointers<kVerifyNone>(klass, kPointerSize, *this);
450 }
451
452 template <typename T>
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -0800453 T* operator()(T* ptr, void** dest_addr ATTRIBUTE_UNUSED) const {
454 return (ptr != nullptr) ? native_visitor_(ptr) : nullptr;
Mathieu Chartierd3f037b2018-12-06 23:50:56 -0800455 }
456
457 void VisitPointerArray(mirror::PointerArray* pointer_array)
458 REQUIRES_SHARED(Locks::mutator_lock_) {
459 // Fully patch the pointer array, including the `klass_` field.
460 PatchReferenceField</*kMayBeNull=*/ false>(pointer_array, mirror::Object::ClassOffset());
461
462 int32_t length = pointer_array->GetLength<kVerifyNone>();
463 for (int32_t i = 0; i != length; ++i) {
464 ArtMethod** method_entry = reinterpret_cast<ArtMethod**>(
465 pointer_array->ElementAddress<kVerifyNone>(i, kPointerSize));
466 PatchNativePointer</*kMayBeNull=*/ false>(method_entry);
467 }
468 }
469
470 void VisitObject(mirror::Object* object) REQUIRES_SHARED(Locks::mutator_lock_) {
471 // Visit all reference fields.
472 object->VisitReferences</*kVisitNativeRoots=*/ false,
473 kVerifyNone,
474 kWithoutReadBarrier>(*this, *this);
475 // This function should not be called for classes.
476 DCHECK(!object->IsClass<kVerifyNone>());
477 }
478
479 // Visitor for VisitReferences().
480 ALWAYS_INLINE void operator()(mirror::Object* object, MemberOffset field_offset, bool is_static)
481 const REQUIRES_SHARED(Locks::mutator_lock_) {
482 DCHECK(!is_static);
483 PatchReferenceField(object, field_offset);
484 }
485 // Visitor for VisitReferences(), java.lang.ref.Reference case.
486 ALWAYS_INLINE void operator()(ObjPtr<mirror::Class> klass, mirror::Reference* ref) const
487 REQUIRES_SHARED(Locks::mutator_lock_) {
488 DCHECK(klass->IsTypeOfReferenceClass());
489 this->operator()(ref, mirror::Reference::ReferentOffset(), /*is_static=*/ false);
490 }
491 // Ignore class native roots; not called from VisitReferences() for kVisitNativeRoots == false.
492 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED)
493 const {}
494 void VisitRoot(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const {}
495
496 void VisitDexCacheArrays(mirror::DexCache* dex_cache) REQUIRES_SHARED(Locks::mutator_lock_) {
497 FixupDexCacheArray<mirror::StringDexCacheType>(dex_cache,
498 mirror::DexCache::StringsOffset(),
499 dex_cache->NumStrings<kVerifyNone>());
500 FixupDexCacheArray<mirror::TypeDexCacheType>(dex_cache,
501 mirror::DexCache::ResolvedTypesOffset(),
502 dex_cache->NumResolvedTypes<kVerifyNone>());
503 FixupDexCacheArray<mirror::MethodDexCacheType>(dex_cache,
504 mirror::DexCache::ResolvedMethodsOffset(),
505 dex_cache->NumResolvedMethods<kVerifyNone>());
506 FixupDexCacheArray<mirror::FieldDexCacheType>(dex_cache,
507 mirror::DexCache::ResolvedFieldsOffset(),
508 dex_cache->NumResolvedFields<kVerifyNone>());
509 FixupDexCacheArray<mirror::MethodTypeDexCacheType>(
510 dex_cache,
511 mirror::DexCache::ResolvedMethodTypesOffset(),
512 dex_cache->NumResolvedMethodTypes<kVerifyNone>());
513 FixupDexCacheArray<GcRoot<mirror::CallSite>>(
514 dex_cache,
515 mirror::DexCache::ResolvedCallSitesOffset(),
516 dex_cache->NumResolvedCallSites<kVerifyNone>());
517 FixupDexCacheArray<GcRoot<mirror::String>>(
518 dex_cache,
519 mirror::DexCache::PreResolvedStringsOffset(),
520 dex_cache->NumPreResolvedStrings<kVerifyNone>());
521 }
522
523 template <bool kMayBeNull = true, typename T>
524 ALWAYS_INLINE void PatchGcRoot(/*inout*/GcRoot<T>* root) const
525 REQUIRES_SHARED(Locks::mutator_lock_) {
526 static_assert(sizeof(GcRoot<mirror::Class*>) == sizeof(uint32_t), "GcRoot size check");
527 T* old_value = root->template Read<kWithoutReadBarrier>();
528 DCHECK(kMayBeNull || old_value != nullptr);
529 if (!kMayBeNull || old_value != nullptr) {
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -0800530 *root = GcRoot<T>(heap_visitor_(old_value));
Mathieu Chartierd3f037b2018-12-06 23:50:56 -0800531 }
532 }
533
534 template <bool kMayBeNull = true, typename T>
535 ALWAYS_INLINE void PatchNativePointer(/*inout*/T** entry) const {
536 if (kPointerSize == PointerSize::k64) {
537 uint64_t* raw_entry = reinterpret_cast<uint64_t*>(entry);
538 T* old_value = reinterpret_cast64<T*>(*raw_entry);
539 DCHECK(kMayBeNull || old_value != nullptr);
540 if (!kMayBeNull || old_value != nullptr) {
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -0800541 T* new_value = native_visitor_(old_value);
Mathieu Chartierd3f037b2018-12-06 23:50:56 -0800542 *raw_entry = reinterpret_cast64<uint64_t>(new_value);
543 }
544 } else {
545 uint32_t* raw_entry = reinterpret_cast<uint32_t*>(entry);
546 T* old_value = reinterpret_cast32<T*>(*raw_entry);
547 DCHECK(kMayBeNull || old_value != nullptr);
548 if (!kMayBeNull || old_value != nullptr) {
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -0800549 T* new_value = native_visitor_(old_value);
Mathieu Chartierd3f037b2018-12-06 23:50:56 -0800550 *raw_entry = reinterpret_cast32<uint32_t>(new_value);
551 }
552 }
553 }
554
555 template <bool kMayBeNull = true>
556 ALWAYS_INLINE void PatchReferenceField(mirror::Object* object, MemberOffset offset) const
557 REQUIRES_SHARED(Locks::mutator_lock_) {
558 mirror::Object* old_value =
559 object->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(offset);
560 DCHECK(kMayBeNull || old_value != nullptr);
561 if (!kMayBeNull || old_value != nullptr) {
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -0800562 mirror::Object* new_value = heap_visitor_(old_value);
Mathieu Chartierd3f037b2018-12-06 23:50:56 -0800563 object->SetFieldObjectWithoutWriteBarrier</*kTransactionActive=*/ false,
564 /*kCheckTransaction=*/ true,
565 kVerifyNone>(offset, new_value);
566 }
567 }
568
569 template <typename T>
570 void FixupDexCacheArrayEntry(std::atomic<mirror::DexCachePair<T>>* array, uint32_t index)
571 REQUIRES_SHARED(Locks::mutator_lock_) {
572 static_assert(sizeof(std::atomic<mirror::DexCachePair<T>>) == sizeof(mirror::DexCachePair<T>),
573 "Size check for removing std::atomic<>.");
574 PatchGcRoot(&(reinterpret_cast<mirror::DexCachePair<T>*>(array)[index].object));
575 }
576
577 template <typename T>
578 void FixupDexCacheArrayEntry(std::atomic<mirror::NativeDexCachePair<T>>* array, uint32_t index)
579 REQUIRES_SHARED(Locks::mutator_lock_) {
580 static_assert(sizeof(std::atomic<mirror::NativeDexCachePair<T>>) ==
581 sizeof(mirror::NativeDexCachePair<T>),
582 "Size check for removing std::atomic<>.");
583 mirror::NativeDexCachePair<T> pair =
584 mirror::DexCache::GetNativePairPtrSize(array, index, kPointerSize);
585 if (pair.object != nullptr) {
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -0800586 pair.object = native_visitor_(pair.object);
Mathieu Chartierd3f037b2018-12-06 23:50:56 -0800587 mirror::DexCache::SetNativePairPtrSize(array, index, pair, kPointerSize);
588 }
589 }
590
591 void FixupDexCacheArrayEntry(GcRoot<mirror::CallSite>* array, uint32_t index)
592 REQUIRES_SHARED(Locks::mutator_lock_) {
593 PatchGcRoot(&array[index]);
594 }
595
596 void FixupDexCacheArrayEntry(GcRoot<mirror::String>* array, uint32_t index)
597 REQUIRES_SHARED(Locks::mutator_lock_) {
598 PatchGcRoot(&array[index]);
599 }
600
601 template <typename EntryType>
602 void FixupDexCacheArray(mirror::DexCache* dex_cache,
603 MemberOffset array_offset,
604 uint32_t size) REQUIRES_SHARED(Locks::mutator_lock_) {
605 EntryType* old_array =
606 reinterpret_cast64<EntryType*>(dex_cache->GetField64<kVerifyNone>(array_offset));
607 DCHECK_EQ(old_array != nullptr, size != 0u);
608 if (old_array != nullptr) {
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -0800609 EntryType* new_array = native_visitor_(old_array);
Mathieu Chartierd3f037b2018-12-06 23:50:56 -0800610 dex_cache->SetField64<kVerifyNone>(array_offset, reinterpret_cast64<uint64_t>(new_array));
611 for (uint32_t i = 0; i != size; ++i) {
612 FixupDexCacheArrayEntry(new_array, i);
613 }
614 }
615 }
616
617 private:
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -0800618 // Heap objects visitor.
619 HeapVisitor heap_visitor_;
620
621 // Native objects visitor.
622 NativeVisitor native_visitor_;
Mathieu Chartierd3f037b2018-12-06 23:50:56 -0800623};
624
625template <typename ObjectVisitor>
626class ImageSpace::PatchArtFieldVisitor final : public ArtFieldVisitor {
627 public:
628 explicit PatchArtFieldVisitor(const ObjectVisitor& visitor) : visitor_(visitor) {}
629
630 void Visit(ArtField* field) override REQUIRES_SHARED(Locks::mutator_lock_) {
631 visitor_.template PatchGcRoot</*kMayBeNull=*/ false>(&field->DeclaringClassRoot());
632 }
633
634 private:
635 const ObjectVisitor visitor_;
636};
637
638template <PointerSize kPointerSize, typename ObjectVisitor, typename CodeVisitor>
639class ImageSpace::PatchArtMethodVisitor final : public ArtMethodVisitor {
640 public:
641 explicit PatchArtMethodVisitor(const ObjectVisitor& object_visitor,
642 const CodeVisitor& code_visitor)
643 : object_visitor_(object_visitor),
644 code_visitor_(code_visitor) {}
645
646 void Visit(ArtMethod* method) override REQUIRES_SHARED(Locks::mutator_lock_) {
647 object_visitor_.PatchGcRoot(&method->DeclaringClassRoot());
648 void** data_address = PointerAddress(method, ArtMethod::DataOffset(kPointerSize));
649 object_visitor_.PatchNativePointer(data_address);
650 void** entrypoint_address =
651 PointerAddress(method, ArtMethod::EntryPointFromQuickCompiledCodeOffset(kPointerSize));
652 code_visitor_.PatchNativePointer(entrypoint_address);
653 }
654
655 private:
656 void** PointerAddress(ArtMethod* method, MemberOffset offset) {
657 return reinterpret_cast<void**>(reinterpret_cast<uint8_t*>(method) + offset.Uint32Value());
658 }
659
660 const ObjectVisitor object_visitor_;
661 const CodeVisitor code_visitor_;
662};
663
Mathieu Chartier25602dc2018-12-11 11:31:57 -0800664template <typename ReferenceVisitor>
665class ImageSpace::ClassTableVisitor final {
666 public:
667 explicit ClassTableVisitor(const ReferenceVisitor& reference_visitor)
668 : reference_visitor_(reference_visitor) {}
669
670 void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
671 REQUIRES_SHARED(Locks::mutator_lock_) {
672 DCHECK(root->AsMirrorPtr() != nullptr);
673 root->Assign(reference_visitor_(root->AsMirrorPtr()));
674 }
675
676 private:
677 ReferenceVisitor reference_visitor_;
678};
679
Andreas Gampea463b6a2016-08-12 21:53:32 -0700680// Helper class encapsulating loading, so we can access private ImageSpace members (this is a
Vladimir Markoc09cd052018-08-23 16:36:36 +0100681// nested class), but not declare functions in the header.
Vladimir Marko82e1e272018-08-20 13:38:06 +0000682class ImageSpace::Loader {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800683 public:
Vladimir Marko4df2d802018-09-27 16:42:44 +0000684 static std::unique_ptr<ImageSpace> InitAppImage(const char* image_filename,
685 const char* image_location,
Vladimir Marko4df2d802018-09-27 16:42:44 +0000686 const OatFile* oat_file,
687 /*inout*/MemMap* image_reservation,
Vladimir Marko4df2d802018-09-27 16:42:44 +0000688 /*out*/std::string* error_msg)
689 REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100690 TimingLogger logger(__PRETTY_FUNCTION__, /*precise=*/ true, VLOG_IS_ON(image));
Mathieu Chartier3ea43222018-12-08 20:44:50 -0800691
Vladimir Marko4df2d802018-09-27 16:42:44 +0000692 std::unique_ptr<ImageSpace> space = Init(image_filename,
693 image_location,
Vladimir Marko4df2d802018-09-27 16:42:44 +0000694 oat_file,
695 &logger,
696 image_reservation,
Vladimir Marko4df2d802018-09-27 16:42:44 +0000697 error_msg);
698 if (space != nullptr) {
Vladimir Marko7391c8c2018-11-21 17:58:44 +0000699 uint32_t expected_reservation_size =
700 RoundUp(space->GetImageHeader().GetImageSize(), kPageSize);
701 if (!CheckImageReservationSize(*space, expected_reservation_size, error_msg) ||
702 !CheckImageComponentCount(*space, /*expected_component_count=*/ 1u, error_msg)) {
703 return nullptr;
704 }
705
Vladimir Marko4df2d802018-09-27 16:42:44 +0000706 TimingLogger::ScopedTiming timing("RelocateImage", &logger);
707 ImageHeader* image_header = reinterpret_cast<ImageHeader*>(space->GetMemMap()->Begin());
Mathieu Chartier25602dc2018-12-11 11:31:57 -0800708 const PointerSize pointer_size = image_header->GetPointerSize();
709 bool result;
710 if (pointer_size == PointerSize::k64) {
711 result = RelocateInPlace<PointerSize::k64>(*image_header,
712 space->GetMemMap()->Begin(),
713 space->GetLiveBitmap(),
714 oat_file,
715 error_msg);
716 } else {
717 result = RelocateInPlace<PointerSize::k32>(*image_header,
718 space->GetMemMap()->Begin(),
719 space->GetLiveBitmap(),
720 oat_file,
721 error_msg);
722 }
723 if (!result) {
Vladimir Marko4df2d802018-09-27 16:42:44 +0000724 return nullptr;
725 }
726 Runtime* runtime = Runtime::Current();
727 CHECK_EQ(runtime->GetResolutionMethod(),
728 image_header->GetImageMethod(ImageHeader::kResolutionMethod));
729 CHECK_EQ(runtime->GetImtConflictMethod(),
730 image_header->GetImageMethod(ImageHeader::kImtConflictMethod));
731 CHECK_EQ(runtime->GetImtUnimplementedMethod(),
732 image_header->GetImageMethod(ImageHeader::kImtUnimplementedMethod));
733 CHECK_EQ(runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveAllCalleeSaves),
734 image_header->GetImageMethod(ImageHeader::kSaveAllCalleeSavesMethod));
735 CHECK_EQ(runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveRefsOnly),
736 image_header->GetImageMethod(ImageHeader::kSaveRefsOnlyMethod));
737 CHECK_EQ(runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveRefsAndArgs),
738 image_header->GetImageMethod(ImageHeader::kSaveRefsAndArgsMethod));
739 CHECK_EQ(runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveEverything),
740 image_header->GetImageMethod(ImageHeader::kSaveEverythingMethod));
741 CHECK_EQ(runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveEverythingForClinit),
742 image_header->GetImageMethod(ImageHeader::kSaveEverythingMethodForClinit));
743 CHECK_EQ(runtime->GetCalleeSaveMethod(CalleeSaveType::kSaveEverythingForSuspendCheck),
744 image_header->GetImageMethod(ImageHeader::kSaveEverythingMethodForSuspendCheck));
745
746 VLOG(image) << "ImageSpace::Loader::InitAppImage exiting " << *space.get();
Mathieu Chartier3f1fec62018-10-17 09:14:05 -0700747 }
748 if (VLOG_IS_ON(image)) {
749 logger.Dump(LOG_STREAM(INFO));
Vladimir Marko4df2d802018-09-27 16:42:44 +0000750 }
751 return space;
752 }
753
Andreas Gampea463b6a2016-08-12 21:53:32 -0700754 static std::unique_ptr<ImageSpace> Init(const char* image_filename,
755 const char* image_location,
Andreas Gampea463b6a2016-08-12 21:53:32 -0700756 const OatFile* oat_file,
Vladimir Marko4df2d802018-09-27 16:42:44 +0000757 TimingLogger* logger,
Vladimir Markoc09cd052018-08-23 16:36:36 +0100758 /*inout*/MemMap* image_reservation,
Vladimir Markoc09cd052018-08-23 16:36:36 +0100759 /*out*/std::string* error_msg)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700760 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampea463b6a2016-08-12 21:53:32 -0700761 CHECK(image_filename != nullptr);
762 CHECK(image_location != nullptr);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800763
Andreas Gampea463b6a2016-08-12 21:53:32 -0700764 VLOG(image) << "ImageSpace::Init entering image_filename=" << image_filename;
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800765
Andreas Gampea463b6a2016-08-12 21:53:32 -0700766 std::unique_ptr<File> file;
Mathieu Chartier92ec5942016-04-11 12:03:48 -0700767 {
Vladimir Marko4df2d802018-09-27 16:42:44 +0000768 TimingLogger::ScopedTiming timing("OpenImageFile", logger);
Andreas Gampea463b6a2016-08-12 21:53:32 -0700769 file.reset(OS::OpenFileForReading(image_filename));
770 if (file == nullptr) {
771 *error_msg = StringPrintf("Failed to open '%s'", image_filename);
772 return nullptr;
Mathieu Chartier92ec5942016-04-11 12:03:48 -0700773 }
Andreas Gampea463b6a2016-08-12 21:53:32 -0700774 }
775 ImageHeader temp_image_header;
776 ImageHeader* image_header = &temp_image_header;
777 {
Vladimir Marko4df2d802018-09-27 16:42:44 +0000778 TimingLogger::ScopedTiming timing("ReadImageHeader", logger);
Andreas Gampea463b6a2016-08-12 21:53:32 -0700779 bool success = file->ReadFully(image_header, sizeof(*image_header));
780 if (!success || !image_header->IsValid()) {
781 *error_msg = StringPrintf("Invalid image header in '%s'", image_filename);
782 return nullptr;
783 }
784 }
785 // Check that the file is larger or equal to the header size + data size.
786 const uint64_t image_file_size = static_cast<uint64_t>(file->GetLength());
787 if (image_file_size < sizeof(ImageHeader) + image_header->GetDataSize()) {
Mathieu Chartier1a842962018-11-13 15:09:51 -0800788 *error_msg = StringPrintf(
789 "Image file truncated: %" PRIu64 " vs. %" PRIu64 ".",
790 image_file_size,
791 static_cast<uint64_t>(sizeof(ImageHeader) + image_header->GetDataSize()));
Andreas Gampea463b6a2016-08-12 21:53:32 -0700792 return nullptr;
793 }
794
795 if (oat_file != nullptr) {
Vladimir Marko312f10e2018-11-21 12:35:24 +0000796 // If we have an oat file (i.e. for app image), check the oat file checksum.
797 // Otherwise, we open the oat file after the image and check the checksum there.
Andreas Gampea463b6a2016-08-12 21:53:32 -0700798 const uint32_t oat_checksum = oat_file->GetOatHeader().GetChecksum();
799 const uint32_t image_oat_checksum = image_header->GetOatChecksum();
800 if (oat_checksum != image_oat_checksum) {
801 *error_msg = StringPrintf("Oat checksum 0x%x does not match the image one 0x%x in image %s",
802 oat_checksum,
803 image_oat_checksum,
804 image_filename);
805 return nullptr;
Mathieu Chartier92ec5942016-04-11 12:03:48 -0700806 }
807 }
808
Andreas Gampea463b6a2016-08-12 21:53:32 -0700809 if (VLOG_IS_ON(startup)) {
810 LOG(INFO) << "Dumping image sections";
811 for (size_t i = 0; i < ImageHeader::kSectionCount; ++i) {
812 const auto section_idx = static_cast<ImageHeader::ImageSections>(i);
813 auto& section = image_header->GetImageSection(section_idx);
814 LOG(INFO) << section_idx << " start="
815 << reinterpret_cast<void*>(image_header->GetImageBegin() + section.Offset()) << " "
816 << section;
Mathieu Chartier92ec5942016-04-11 12:03:48 -0700817 }
Andreas Gampea463b6a2016-08-12 21:53:32 -0700818 }
819
Vladimir Markocd87c3e2017-09-05 13:11:57 +0100820 const auto& bitmap_section = image_header->GetImageBitmapSection();
Andreas Gampea463b6a2016-08-12 21:53:32 -0700821 // The location we want to map from is the first aligned page after the end of the stored
822 // (possibly compressed) data.
823 const size_t image_bitmap_offset = RoundUp(sizeof(ImageHeader) + image_header->GetDataSize(),
824 kPageSize);
825 const size_t end_of_bitmap = image_bitmap_offset + bitmap_section.Size();
Vladimir Markod68ab242018-10-18 16:07:10 +0100826 if (end_of_bitmap != image_file_size) {
Andreas Gampea463b6a2016-08-12 21:53:32 -0700827 *error_msg = StringPrintf(
Vladimir Markod68ab242018-10-18 16:07:10 +0100828 "Image file size does not equal end of bitmap: size=%" PRIu64 " vs. %zu.",
Vladimir Marko6121aa62018-07-06 10:04:35 +0100829 image_file_size,
Vladimir Markod68ab242018-10-18 16:07:10 +0100830 end_of_bitmap);
Andreas Gampea463b6a2016-08-12 21:53:32 -0700831 return nullptr;
832 }
833
Andreas Gampea463b6a2016-08-12 21:53:32 -0700834 // GetImageBegin is the preferred address to map the image. If we manage to map the
835 // image at the image begin, the amount of fixup work required is minimized.
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -0800836 // 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 -0800837 // avoid reading proc maps for a mapping failure and slowing everything down.
Vladimir Markoc09cd052018-08-23 16:36:36 +0100838 // For the boot image, we have already reserved the memory and we load the image
839 // into the `image_reservation`.
Vladimir Marko312f10e2018-11-21 12:35:24 +0000840 MemMap map = LoadImageFile(
Vladimir Markoc09cd052018-08-23 16:36:36 +0100841 image_filename,
842 image_location,
843 *image_header,
Vladimir Markoc09cd052018-08-23 16:36:36 +0100844 file->Fd(),
845 logger,
846 image_reservation,
Vladimir Marko4df2d802018-09-27 16:42:44 +0000847 error_msg);
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100848 if (!map.IsValid()) {
Andreas Gampea463b6a2016-08-12 21:53:32 -0700849 DCHECK(!error_msg->empty());
850 return nullptr;
851 }
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100852 DCHECK_EQ(0, memcmp(image_header, map.Begin(), sizeof(ImageHeader)));
Andreas Gampea463b6a2016-08-12 21:53:32 -0700853
Vladimir Markoc09cd052018-08-23 16:36:36 +0100854 MemMap image_bitmap_map = MemMap::MapFile(bitmap_section.Size(),
Vladimir Marko4df2d802018-09-27 16:42:44 +0000855 PROT_READ,
856 MAP_PRIVATE,
Vladimir Markoc09cd052018-08-23 16:36:36 +0100857 file->Fd(),
858 image_bitmap_offset,
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100859 /*low_4gb=*/ false,
Vladimir Markoc09cd052018-08-23 16:36:36 +0100860 image_filename,
861 error_msg);
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100862 if (!image_bitmap_map.IsValid()) {
Andreas Gampea463b6a2016-08-12 21:53:32 -0700863 *error_msg = StringPrintf("Failed to map image bitmap: %s", error_msg->c_str());
864 return nullptr;
865 }
866 // Loaded the map, use the image header from the file now in case we patch it with
867 // RelocateInPlace.
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100868 image_header = reinterpret_cast<ImageHeader*>(map.Begin());
Hans Boehmfb8b4e22018-09-05 16:45:42 -0700869 const uint32_t bitmap_index = ImageSpace::bitmap_index_.fetch_add(1);
Andreas Gampea463b6a2016-08-12 21:53:32 -0700870 std::string bitmap_name(StringPrintf("imagespace %s live-bitmap %u",
871 image_filename,
872 bitmap_index));
873 // Bitmap only needs to cover until the end of the mirror objects section.
Vladimir Markocd87c3e2017-09-05 13:11:57 +0100874 const ImageSection& image_objects = image_header->GetObjectsSection();
Andreas Gampea463b6a2016-08-12 21:53:32 -0700875 // We only want the mirror object, not the ArtFields and ArtMethods.
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100876 uint8_t* const image_end = map.Begin() + image_objects.End();
Andreas Gampea463b6a2016-08-12 21:53:32 -0700877 std::unique_ptr<accounting::ContinuousSpaceBitmap> bitmap;
878 {
Vladimir Marko4df2d802018-09-27 16:42:44 +0000879 TimingLogger::ScopedTiming timing("CreateImageBitmap", logger);
Andreas Gampea463b6a2016-08-12 21:53:32 -0700880 bitmap.reset(
881 accounting::ContinuousSpaceBitmap::CreateFromMemMap(
882 bitmap_name,
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100883 std::move(image_bitmap_map),
884 reinterpret_cast<uint8_t*>(map.Begin()),
Mathieu Chartier612ff542017-05-01 09:59:24 -0700885 // Make sure the bitmap is aligned to card size instead of just bitmap word size.
886 RoundUp(image_objects.End(), gc::accounting::CardTable::kCardSize)));
Andreas Gampea463b6a2016-08-12 21:53:32 -0700887 if (bitmap == nullptr) {
888 *error_msg = StringPrintf("Could not create bitmap '%s'", bitmap_name.c_str());
889 return nullptr;
890 }
891 }
Andreas Gampea463b6a2016-08-12 21:53:32 -0700892 // We only want the mirror object, not the ArtFields and ArtMethods.
893 std::unique_ptr<ImageSpace> space(new ImageSpace(image_filename,
894 image_location,
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100895 std::move(map),
Vladimir Markoc09cd052018-08-23 16:36:36 +0100896 std::move(bitmap),
Andreas Gampea463b6a2016-08-12 21:53:32 -0700897 image_end));
Vladimir Marko312f10e2018-11-21 12:35:24 +0000898 space->oat_file_non_owned_ = oat_file;
Andreas Gampea463b6a2016-08-12 21:53:32 -0700899 return space;
900 }
901
Vladimir Marko7391c8c2018-11-21 17:58:44 +0000902 static bool CheckImageComponentCount(const ImageSpace& space,
903 uint32_t expected_component_count,
904 /*out*/std::string* error_msg) {
905 const ImageHeader& header = space.GetImageHeader();
906 if (header.GetComponentCount() != expected_component_count) {
907 *error_msg = StringPrintf("Unexpected component count in %s, received %u, expected %u",
908 space.GetImageFilename().c_str(),
909 header.GetComponentCount(),
910 expected_component_count);
911 return false;
912 }
913 return true;
914 }
915
916 static bool CheckImageReservationSize(const ImageSpace& space,
917 uint32_t expected_reservation_size,
918 /*out*/std::string* error_msg) {
919 const ImageHeader& header = space.GetImageHeader();
920 if (header.GetImageReservationSize() != expected_reservation_size) {
921 *error_msg = StringPrintf("Unexpected reservation size in %s, received %u, expected %u",
922 space.GetImageFilename().c_str(),
923 header.GetImageReservationSize(),
924 expected_reservation_size);
925 return false;
926 }
927 return true;
928 }
929
Andreas Gampea463b6a2016-08-12 21:53:32 -0700930 private:
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100931 static MemMap LoadImageFile(const char* image_filename,
932 const char* image_location,
933 const ImageHeader& image_header,
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100934 int fd,
Vladimir Marko4df2d802018-09-27 16:42:44 +0000935 TimingLogger* logger,
Vladimir Markoc09cd052018-08-23 16:36:36 +0100936 /*inout*/MemMap* image_reservation,
937 /*out*/std::string* error_msg) {
Vladimir Marko4df2d802018-09-27 16:42:44 +0000938 TimingLogger::ScopedTiming timing("MapImageFile", logger);
Mathieu Chartier1a842962018-11-13 15:09:51 -0800939 std::string temp_error_msg;
940 const bool is_compressed = image_header.HasCompressedBlock();
941 if (!is_compressed) {
Vladimir Marko11306592018-10-26 14:22:59 +0100942 uint8_t* address = (image_reservation != nullptr) ? image_reservation->Begin() : nullptr;
Andreas Gampea463b6a2016-08-12 21:53:32 -0700943 return MemMap::MapFileAtAddress(address,
944 image_header.GetImageSize(),
945 PROT_READ | PROT_WRITE,
946 MAP_PRIVATE,
947 fd,
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100948 /*start=*/ 0,
949 /*low_4gb=*/ true,
Andreas Gampea463b6a2016-08-12 21:53:32 -0700950 image_filename,
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100951 /*reuse=*/ false,
Vladimir Markoc09cd052018-08-23 16:36:36 +0100952 image_reservation,
Andreas Gampea463b6a2016-08-12 21:53:32 -0700953 error_msg);
954 }
955
Andreas Gampea463b6a2016-08-12 21:53:32 -0700956 // Reserve output and decompress into it.
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100957 MemMap map = MemMap::MapAnonymous(image_location,
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100958 image_header.GetImageSize(),
959 PROT_READ | PROT_WRITE,
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100960 /*low_4gb=*/ true,
Vladimir Markoc09cd052018-08-23 16:36:36 +0100961 image_reservation,
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100962 error_msg);
963 if (map.IsValid()) {
Andreas Gampea463b6a2016-08-12 21:53:32 -0700964 const size_t stored_size = image_header.GetDataSize();
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100965 MemMap temp_map = MemMap::MapFile(sizeof(ImageHeader) + stored_size,
966 PROT_READ,
967 MAP_PRIVATE,
968 fd,
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100969 /*start=*/ 0,
970 /*low_4gb=*/ false,
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100971 image_filename,
972 error_msg);
973 if (!temp_map.IsValid()) {
Mathieu Chartier66b1d572017-02-10 18:41:39 -0800974 DCHECK(error_msg == nullptr || !error_msg->empty());
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100975 return MemMap::Invalid();
Andreas Gampea463b6a2016-08-12 21:53:32 -0700976 }
Vladimir Markoc34bebf2018-08-16 16:12:49 +0100977 memcpy(map.Begin(), &image_header, sizeof(ImageHeader));
Mathieu Chartierc6068c72018-11-13 16:00:58 -0800978
Mathieu Chartierada33d72018-12-17 13:17:30 -0800979 Runtime::ScopedThreadPoolUsage stpu;
980 ThreadPool* const pool = stpu.GetThreadPool();
Andreas Gampea463b6a2016-08-12 21:53:32 -0700981 const uint64_t start = NanoTime();
Mathieu Chartierc6068c72018-11-13 16:00:58 -0800982 Thread* const self = Thread::Current();
Mathieu Chartierada33d72018-12-17 13:17:30 -0800983 static constexpr size_t kMinBlocks = 2u;
984 const bool use_parallel = pool != nullptr && image_header.GetBlockCount() >= kMinBlocks;
Mathieu Chartier1a842962018-11-13 15:09:51 -0800985 for (const ImageHeader::Block& block : image_header.GetBlocks(temp_map.Begin())) {
Mathieu Chartierc6068c72018-11-13 16:00:58 -0800986 auto function = [&](Thread*) {
987 const uint64_t start2 = NanoTime();
988 ScopedTrace trace("LZ4 decompress block");
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -0800989 bool result = block.Decompress(/*out_ptr=*/map.Begin(),
990 /*in_ptr=*/temp_map.Begin(),
991 error_msg);
992 if (!result && error_msg != nullptr) {
993 *error_msg = "Failed to decompress image block " + *error_msg;
Mathieu Chartier1a842962018-11-13 15:09:51 -0800994 }
Mathieu Chartierc6068c72018-11-13 16:00:58 -0800995 VLOG(image) << "Decompress block " << block.GetDataSize() << " -> "
996 << block.GetImageSize() << " in " << PrettyDuration(NanoTime() - start2);
997 };
998 if (use_parallel) {
999 pool->AddTask(self, new FunctionTask(std::move(function)));
1000 } else {
1001 function(self);
Mathieu Chartier1a842962018-11-13 15:09:51 -08001002 }
1003 }
Mathieu Chartierc6068c72018-11-13 16:00:58 -08001004 if (use_parallel) {
1005 ScopedTrace trace("Waiting for workers");
1006 pool->Wait(self, true, false);
1007 }
Mathieu Chartier0d4d2912017-02-10 17:22:41 -08001008 const uint64_t time = NanoTime() - start;
1009 // Add one 1 ns to prevent possible divide by 0.
1010 VLOG(image) << "Decompressing image took " << PrettyDuration(time) << " ("
Vladimir Markoc34bebf2018-08-16 16:12:49 +01001011 << PrettySize(static_cast<uint64_t>(map.Size()) * MsToNs(1000) / (time + 1))
Mathieu Chartier0d4d2912017-02-10 17:22:41 -08001012 << "/s)";
Andreas Gampea463b6a2016-08-12 21:53:32 -07001013 }
1014
Vladimir Markoc34bebf2018-08-16 16:12:49 +01001015 return map;
Andreas Gampea463b6a2016-08-12 21:53:32 -07001016 }
1017
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -08001018 class EmptyRange {
Andreas Gampea463b6a2016-08-12 21:53:32 -07001019 public:
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -08001020 ALWAYS_INLINE bool InSource(uintptr_t) const { return false; }
1021 ALWAYS_INLINE bool InDest(uintptr_t) const { return false; }
1022 ALWAYS_INLINE uintptr_t ToDest(uintptr_t) const { UNREACHABLE(); }
1023 };
1024
1025 template <typename Range0, typename Range1 = EmptyRange, typename Range2 = EmptyRange>
1026 class ForwardAddress {
1027 public:
1028 ForwardAddress(const Range0& range0 = Range0(),
1029 const Range1& range1 = Range1(),
1030 const Range2& range2 = Range2())
1031 : range0_(range0), range1_(range1), range2_(range2) {}
Andreas Gampea463b6a2016-08-12 21:53:32 -07001032
1033 // Return the relocated address of a heap object.
Mathieu Chartier9a3da9a2018-12-21 12:56:55 -08001034 // Null checks must be performed in the caller (for performance reasons).
Andreas Gampea463b6a2016-08-12 21:53:32 -07001035 template <typename T>
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -08001036 ALWAYS_INLINE T* operator()(T* src) const {
Mathieu Chartier9a3da9a2018-12-21 12:56:55 -08001037 DCHECK(src != nullptr);
Andreas Gampea463b6a2016-08-12 21:53:32 -07001038 const uintptr_t uint_src = reinterpret_cast<uintptr_t>(src);
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -08001039 if (range2_.InSource(uint_src)) {
1040 return reinterpret_cast<T*>(range2_.ToDest(uint_src));
Andreas Gampea463b6a2016-08-12 21:53:32 -07001041 }
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -08001042 if (range1_.InSource(uint_src)) {
1043 return reinterpret_cast<T*>(range1_.ToDest(uint_src));
Andreas Gampea463b6a2016-08-12 21:53:32 -07001044 }
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -08001045 CHECK(range0_.InSource(uint_src))
1046 << reinterpret_cast<const void*>(src) << " not in "
1047 << reinterpret_cast<const void*>(range0_.Source()) << "-"
1048 << reinterpret_cast<const void*>(range0_.Source() + range0_.Length());
1049 return reinterpret_cast<T*>(range0_.ToDest(uint_src));
Andreas Gampea463b6a2016-08-12 21:53:32 -07001050 }
1051
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -08001052 private:
1053 const Range0 range0_;
1054 const Range1 range1_;
1055 const Range2 range2_;
Andreas Gampea463b6a2016-08-12 21:53:32 -07001056 };
1057
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -08001058 template <typename Forward>
1059 class FixupRootVisitor {
Andreas Gampea463b6a2016-08-12 21:53:32 -07001060 public:
1061 template<typename... Args>
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -08001062 explicit FixupRootVisitor(Args... args) : forward_(args...) {}
Andreas Gampea463b6a2016-08-12 21:53:32 -07001063
1064 ALWAYS_INLINE void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001065 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampea463b6a2016-08-12 21:53:32 -07001066 if (!root->IsNull()) {
1067 VisitRoot(root);
1068 }
1069 }
1070
1071 ALWAYS_INLINE void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001072 REQUIRES_SHARED(Locks::mutator_lock_) {
Andreas Gampea463b6a2016-08-12 21:53:32 -07001073 mirror::Object* ref = root->AsMirrorPtr();
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -08001074 mirror::Object* new_ref = forward_(ref);
Andreas Gampea463b6a2016-08-12 21:53:32 -07001075 if (ref != new_ref) {
1076 root->Assign(new_ref);
1077 }
1078 }
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -08001079
1080 private:
1081 Forward forward_;
Andreas Gampea463b6a2016-08-12 21:53:32 -07001082 };
1083
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -08001084 template <typename Forward>
1085 class FixupObjectVisitor {
Andreas Gampea463b6a2016-08-12 21:53:32 -07001086 public:
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -08001087 explicit FixupObjectVisitor(gc::accounting::ContinuousSpaceBitmap* visited,
1088 const Forward& forward)
1089 : visited_(visited), forward_(forward) {}
Andreas Gampea463b6a2016-08-12 21:53:32 -07001090
1091 // Fix up separately since we also need to fix up method entrypoints.
1092 ALWAYS_INLINE void VisitRootIfNonNull(
1093 mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const {}
1094
1095 ALWAYS_INLINE void VisitRoot(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED)
1096 const {}
1097
Mathieu Chartier31e88222016-10-14 18:43:19 -07001098 ALWAYS_INLINE void operator()(ObjPtr<mirror::Object> obj,
Andreas Gampea463b6a2016-08-12 21:53:32 -07001099 MemberOffset offset,
1100 bool is_static ATTRIBUTE_UNUSED) const
1101 NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier25602dc2018-12-11 11:31:57 -08001102 // Space is not yet added to the heap, don't do a read barrier.
1103 mirror::Object* ref = obj->GetFieldObject<mirror::Object, kVerifyNone, kWithoutReadBarrier>(
1104 offset);
Mathieu Chartier9a3da9a2018-12-21 12:56:55 -08001105 if (ref != nullptr) {
1106 // Use SetFieldObjectWithoutWriteBarrier to avoid card marking since we are writing to the
1107 // image.
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -08001108 obj->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(offset, forward_(ref));
Mathieu Chartier9a3da9a2018-12-21 12:56:55 -08001109 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07001110 }
1111
1112 // java.lang.ref.Reference visitor.
Mathieu Chartier31e88222016-10-14 18:43:19 -07001113 void operator()(ObjPtr<mirror::Class> klass ATTRIBUTE_UNUSED,
1114 ObjPtr<mirror::Reference> ref) const
Andreas Gampebdf7f1c2016-08-30 16:38:47 -07001115 REQUIRES_SHARED(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Andreas Gampea463b6a2016-08-12 21:53:32 -07001116 mirror::Object* obj = ref->GetReferent<kWithoutReadBarrier>();
Mathieu Chartier9a3da9a2018-12-21 12:56:55 -08001117 if (obj != nullptr) {
1118 ref->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
1119 mirror::Reference::ReferentOffset(),
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -08001120 forward_(obj));
Mathieu Chartier9a3da9a2018-12-21 12:56:55 -08001121 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07001122 }
1123
Mathieu Chartier8c19d242017-03-06 12:35:10 -08001124 void operator()(mirror::Object* obj) const
1125 NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartier25602dc2018-12-11 11:31:57 -08001126 if (!visited_->Set(obj)) {
1127 // Not already visited.
1128 obj->VisitReferences</*visit native roots*/false, kVerifyNone, kWithoutReadBarrier>(
1129 *this,
1130 *this);
1131 CHECK(!obj->IsClass());
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001132 }
1133 }
Mathieu Chartier91edc622016-02-16 17:16:01 -08001134
Andreas Gampea463b6a2016-08-12 21:53:32 -07001135 private:
Andreas Gampea463b6a2016-08-12 21:53:32 -07001136 gc::accounting::ContinuousSpaceBitmap* const visited_;
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -08001137 Forward forward_;
Andreas Gampea463b6a2016-08-12 21:53:32 -07001138 };
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001139
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -08001140 template <typename ForwardObject, typename ForwardNative, typename ForwardCode>
1141 class FixupArtMethodVisitor : public ArtMethodVisitor {
Andreas Gampea463b6a2016-08-12 21:53:32 -07001142 public:
1143 template<typename... Args>
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -08001144 explicit FixupArtMethodVisitor(PointerSize pointer_size,
1145 const ForwardObject& forward_object,
1146 const ForwardNative& forward_native,
1147 const ForwardCode& forward_code)
1148 : pointer_size_(pointer_size),
1149 forward_object_(forward_object),
1150 forward_native_(forward_native),
1151 forward_code_(forward_code) {}
Andreas Gampea463b6a2016-08-12 21:53:32 -07001152
Andreas Gampefa6a1b02018-09-07 08:11:55 -07001153 void Visit(ArtMethod* method) override NO_THREAD_SAFETY_ANALYSIS {
Andreas Gampea463b6a2016-08-12 21:53:32 -07001154 // TODO: Separate visitor for runtime vs normal methods.
1155 if (UNLIKELY(method->IsRuntimeMethod())) {
1156 ImtConflictTable* table = method->GetImtConflictTable(pointer_size_);
1157 if (table != nullptr) {
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -08001158 ImtConflictTable* new_table = forward_native_(table);
Andreas Gampea463b6a2016-08-12 21:53:32 -07001159 if (table != new_table) {
1160 method->SetImtConflictTable(new_table, pointer_size_);
1161 }
1162 }
1163 const void* old_code = method->GetEntryPointFromQuickCompiledCodePtrSize(pointer_size_);
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -08001164 const void* new_code = forward_code_(old_code);
Andreas Gampea463b6a2016-08-12 21:53:32 -07001165 if (old_code != new_code) {
1166 method->SetEntryPointFromQuickCompiledCodePtrSize(new_code, pointer_size_);
1167 }
1168 } else {
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -08001169 method->UpdateObjectsForImageRelocation(forward_object_);
1170 method->UpdateEntrypoints(forward_code_, pointer_size_);
Andreas Gampea463b6a2016-08-12 21:53:32 -07001171 }
1172 }
1173
1174 private:
Andreas Gampea463b6a2016-08-12 21:53:32 -07001175 const PointerSize pointer_size_;
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -08001176 const ForwardObject forward_object_;
1177 const ForwardNative forward_native_;
1178 const ForwardCode forward_code_;
Andreas Gampea463b6a2016-08-12 21:53:32 -07001179 };
1180
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -08001181 template <typename Forward>
1182 class FixupArtFieldVisitor : public ArtFieldVisitor {
Andreas Gampea463b6a2016-08-12 21:53:32 -07001183 public:
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -08001184 explicit FixupArtFieldVisitor(Forward forward) : forward_(forward) {}
Andreas Gampea463b6a2016-08-12 21:53:32 -07001185
Andreas Gampefa6a1b02018-09-07 08:11:55 -07001186 void Visit(ArtField* field) override NO_THREAD_SAFETY_ANALYSIS {
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -08001187 field->UpdateObjects(forward_);
Andreas Gampea463b6a2016-08-12 21:53:32 -07001188 }
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -08001189
1190 private:
1191 Forward forward_;
Andreas Gampea463b6a2016-08-12 21:53:32 -07001192 };
1193
1194 // Relocate an image space mapped at target_base which possibly used to be at a different base
Vladimir Marko4df2d802018-09-27 16:42:44 +00001195 // address. In place means modifying a single ImageSpace in place rather than relocating from
1196 // one ImageSpace to another.
Mathieu Chartier25602dc2018-12-11 11:31:57 -08001197 template <PointerSize kPointerSize>
Andreas Gampea463b6a2016-08-12 21:53:32 -07001198 static bool RelocateInPlace(ImageHeader& image_header,
1199 uint8_t* target_base,
1200 accounting::ContinuousSpaceBitmap* bitmap,
1201 const OatFile* app_oat_file,
1202 std::string* error_msg) {
1203 DCHECK(error_msg != nullptr);
Andreas Gampea463b6a2016-08-12 21:53:32 -07001204 // Set up sections.
1205 uint32_t boot_image_begin = 0;
1206 uint32_t boot_image_end = 0;
1207 uint32_t boot_oat_begin = 0;
1208 uint32_t boot_oat_end = 0;
Andreas Gampea463b6a2016-08-12 21:53:32 -07001209 gc::Heap* const heap = Runtime::Current()->GetHeap();
1210 heap->GetBootImagesSize(&boot_image_begin, &boot_image_end, &boot_oat_begin, &boot_oat_end);
1211 if (boot_image_begin == boot_image_end) {
1212 *error_msg = "Can not relocate app image without boot image space";
1213 return false;
1214 }
1215 if (boot_oat_begin == boot_oat_end) {
1216 *error_msg = "Can not relocate app image without boot oat file";
1217 return false;
1218 }
Vladimir Marko0c78ef72018-11-21 14:09:35 +00001219 const uint32_t boot_image_size = boot_oat_end - boot_image_begin;
Andreas Gampea463b6a2016-08-12 21:53:32 -07001220 const uint32_t image_header_boot_image_size = image_header.GetBootImageSize();
Andreas Gampea463b6a2016-08-12 21:53:32 -07001221 if (boot_image_size != image_header_boot_image_size) {
1222 *error_msg = StringPrintf("Boot image size %" PRIu64 " does not match expected size %"
1223 PRIu64,
1224 static_cast<uint64_t>(boot_image_size),
1225 static_cast<uint64_t>(image_header_boot_image_size));
1226 return false;
1227 }
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -08001228 const ImageSection& objects_section = image_header.GetObjectsSection();
1229 // Where the app image objects are mapped to.
1230 uint8_t* objects_location = target_base + objects_section.Offset();
Andreas Gampea463b6a2016-08-12 21:53:32 -07001231 TimingLogger logger(__FUNCTION__, true, false);
1232 RelocationRange boot_image(image_header.GetBootImageBegin(),
1233 boot_image_begin,
1234 boot_image_size);
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -08001235 // Metadata is everything after the objects section, use exclusion to be safe.
1236 RelocationRange app_image_metadata(
1237 reinterpret_cast<uintptr_t>(image_header.GetImageBegin()) + objects_section.End(),
1238 reinterpret_cast<uintptr_t>(target_base) + objects_section.End(),
1239 image_header.GetImageSize() - objects_section.End());
1240 // App image heap objects, may be mapped in the heap.
1241 RelocationRange app_image_objects(
1242 reinterpret_cast<uintptr_t>(image_header.GetImageBegin()) + objects_section.Offset(),
1243 reinterpret_cast<uintptr_t>(objects_location),
1244 objects_section.Size());
Andreas Gampea463b6a2016-08-12 21:53:32 -07001245 // Use the oat data section since this is where the OatFile::Begin is.
1246 RelocationRange app_oat(reinterpret_cast<uintptr_t>(image_header.GetOatDataBegin()),
1247 // Not necessarily in low 4GB.
1248 reinterpret_cast<uintptr_t>(app_oat_file->Begin()),
1249 image_header.GetOatDataEnd() - image_header.GetOatDataBegin());
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -08001250 VLOG(image) << "App image metadata " << app_image_metadata;
1251 VLOG(image) << "App image objects " << app_image_objects;
Andreas Gampea463b6a2016-08-12 21:53:32 -07001252 VLOG(image) << "App oat " << app_oat;
1253 VLOG(image) << "Boot image " << boot_image;
Vladimir Marko0c78ef72018-11-21 14:09:35 +00001254 // True if we need to fixup any heap pointers.
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -08001255 const bool fixup_image = boot_image.Delta() != 0 || app_image_metadata.Delta() != 0 ||
1256 app_image_objects.Delta() != 0;
Vladimir Marko0c78ef72018-11-21 14:09:35 +00001257 if (!fixup_image) {
Andreas Gampea463b6a2016-08-12 21:53:32 -07001258 // Nothing to fix up.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001259 return true;
1260 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07001261 ScopedDebugDisallowReadBarriers sddrb(Thread::Current());
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -08001262
1263 using ForwardObject = ForwardAddress<RelocationRange, RelocationRange>;
1264 ForwardObject forward_object(boot_image, app_image_objects);
1265 ForwardObject forward_metadata(boot_image, app_image_metadata);
1266 using ForwardCode = ForwardAddress<RelocationRange, RelocationRange>;
1267 ForwardCode forward_code(boot_image, app_oat);
1268 PatchObjectVisitor<kPointerSize, ForwardObject, ForwardCode> patch_object_visitor(
1269 forward_object,
1270 forward_metadata);
Andreas Gampea463b6a2016-08-12 21:53:32 -07001271 if (fixup_image) {
1272 // Two pass approach, fix up all classes first, then fix up non class-objects.
1273 // The visited bitmap is used to ensure that pointer arrays are not forwarded twice.
1274 std::unique_ptr<gc::accounting::ContinuousSpaceBitmap> visited_bitmap(
1275 gc::accounting::ContinuousSpaceBitmap::Create("Relocate bitmap",
1276 target_base,
1277 image_header.GetImageSize()));
Mathieu Chartier25602dc2018-12-11 11:31:57 -08001278 {
1279 TimingLogger::ScopedTiming timing("Fixup classes", &logger);
1280 const auto& class_table_section = image_header.GetClassTableSection();
1281 if (class_table_section.Size() > 0u) {
1282 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -08001283 ClassTableVisitor class_table_visitor(forward_object);
Mathieu Chartier25602dc2018-12-11 11:31:57 -08001284 size_t read_count = 0u;
1285 const uint8_t* data = target_base + class_table_section.Offset();
1286 // We avoid making a copy of the data since we want modifications to be propagated to the
1287 // memory map.
1288 ClassTable::ClassSet temp_set(data, /*make_copy_of_data=*/ false, &read_count);
1289 for (ClassTable::TableSlot& slot : temp_set) {
1290 slot.VisitRoot(class_table_visitor);
1291 mirror::Class* klass = slot.Read<kWithoutReadBarrier>();
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -08001292 if (!app_image_objects.InDest(klass)) {
Mathieu Chartier25602dc2018-12-11 11:31:57 -08001293 continue;
1294 }
1295 const bool already_marked = visited_bitmap->Set(klass);
1296 CHECK(!already_marked) << "App image class already visited";
1297 patch_object_visitor.VisitClass(klass);
1298 // Then patch the non-embedded vtable and iftable.
1299 mirror::PointerArray* vtable = klass->GetVTable<kVerifyNone, kWithoutReadBarrier>();
1300 if (vtable != nullptr &&
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -08001301 app_image_objects.InDest(vtable) &&
Mathieu Chartier25602dc2018-12-11 11:31:57 -08001302 !visited_bitmap->Set(vtable)) {
1303 patch_object_visitor.VisitPointerArray(vtable);
1304 }
1305 auto* iftable = klass->GetIfTable<kVerifyNone, kWithoutReadBarrier>();
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -08001306 if (iftable != nullptr && app_image_objects.InDest(iftable)) {
Mathieu Chartier25602dc2018-12-11 11:31:57 -08001307 // Avoid processing the fields of iftable since we will process them later anyways
1308 // below.
1309 int32_t ifcount = klass->GetIfTableCount<kVerifyNone>();
1310 for (int32_t i = 0; i != ifcount; ++i) {
1311 mirror::PointerArray* unpatched_ifarray =
1312 iftable->GetMethodArrayOrNull<kVerifyNone, kWithoutReadBarrier>(i);
1313 if (unpatched_ifarray != nullptr) {
1314 // The iftable has not been patched, so we need to explicitly adjust the pointer.
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -08001315 mirror::PointerArray* ifarray = forward_object(unpatched_ifarray);
1316 if (app_image_objects.InDest(ifarray) && !visited_bitmap->Set(ifarray)) {
Mathieu Chartier25602dc2018-12-11 11:31:57 -08001317 patch_object_visitor.VisitPointerArray(ifarray);
1318 }
1319 }
1320 }
1321 }
1322 }
1323 }
1324 }
1325
1326 // Fixup objects may read fields in the boot image, use the mutator lock here for sanity.
1327 // Though its probably not required.
Mathieu Chartier2ffc74b2019-01-03 19:25:41 -08001328 TimingLogger::ScopedTiming timing("Fixup objects", &logger);
Andreas Gampea463b6a2016-08-12 21:53:32 -07001329 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartier25602dc2018-12-11 11:31:57 -08001330 // Need to update the image to be at the target base.
Mathieu Chartier25602dc2018-12-11 11:31:57 -08001331 uintptr_t objects_begin = reinterpret_cast<uintptr_t>(target_base + objects_section.Offset());
1332 uintptr_t objects_end = reinterpret_cast<uintptr_t>(target_base + objects_section.End());
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -08001333 FixupObjectVisitor<ForwardObject> fixup_object_visitor(visited_bitmap.get(), forward_object);
Andreas Gampea463b6a2016-08-12 21:53:32 -07001334 bitmap->VisitMarkedRange(objects_begin, objects_end, fixup_object_visitor);
1335 // Fixup image roots.
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -08001336 CHECK(app_image_objects.InSource(reinterpret_cast<uintptr_t>(
Vladimir Markoc13fbd82018-06-04 16:16:28 +01001337 image_header.GetImageRoots<kWithoutReadBarrier>().Ptr())));
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -08001338 image_header.RelocateImageObjects(app_image_objects.Delta());
Andreas Gampea463b6a2016-08-12 21:53:32 -07001339 CHECK_EQ(image_header.GetImageBegin(), target_base);
1340 // Fix up dex cache DexFile pointers.
1341 auto* dex_caches = image_header.GetImageRoot<kWithoutReadBarrier>(ImageHeader::kDexCaches)->
Vladimir Marko98db89c2018-09-07 11:45:46 +01001342 AsObjectArray<mirror::DexCache, kVerifyNone>();
Andreas Gampea463b6a2016-08-12 21:53:32 -07001343 for (int32_t i = 0, count = dex_caches->GetLength(); i < count; ++i) {
1344 mirror::DexCache* dex_cache = dex_caches->Get<kVerifyNone, kWithoutReadBarrier>(i);
Mathieu Chartier25602dc2018-12-11 11:31:57 -08001345 CHECK(dex_cache != nullptr);
1346 patch_object_visitor.VisitDexCacheArrays(dex_cache);
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001347 }
1348 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001349 {
1350 // Only touches objects in the app image, no need for mutator lock.
Andreas Gampea463b6a2016-08-12 21:53:32 -07001351 TimingLogger::ScopedTiming timing("Fixup methods", &logger);
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -08001352 FixupArtMethodVisitor method_visitor(kPointerSize,
1353 forward_object,
1354 forward_metadata,
1355 forward_code);
Mathieu Chartier25602dc2018-12-11 11:31:57 -08001356 image_header.VisitPackedArtMethods(&method_visitor, target_base, kPointerSize);
Mathieu Chartiere42888f2016-04-14 10:49:19 -07001357 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07001358 if (fixup_image) {
1359 {
1360 // Only touches objects in the app image, no need for mutator lock.
1361 TimingLogger::ScopedTiming timing("Fixup fields", &logger);
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -08001362 FixupArtFieldVisitor field_visitor(forward_object);
Andreas Gampea463b6a2016-08-12 21:53:32 -07001363 image_header.VisitPackedArtFields(&field_visitor, target_base);
1364 }
1365 {
1366 TimingLogger::ScopedTiming timing("Fixup imt", &logger);
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -08001367 image_header.VisitPackedImTables(forward_metadata, target_base, kPointerSize);
Andreas Gampea463b6a2016-08-12 21:53:32 -07001368 }
1369 {
1370 TimingLogger::ScopedTiming timing("Fixup conflict tables", &logger);
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -08001371 image_header.VisitPackedImtConflictTables(forward_metadata, target_base, kPointerSize);
Andreas Gampea463b6a2016-08-12 21:53:32 -07001372 }
1373 // In the app image case, the image methods are actually in the boot image.
1374 image_header.RelocateImageMethods(boot_image.Delta());
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001375 // Fix up the intern table.
1376 const auto& intern_table_section = image_header.GetInternedStringsSection();
1377 if (intern_table_section.Size() > 0u) {
1378 TimingLogger::ScopedTiming timing("Fixup intern table", &logger);
1379 ScopedObjectAccess soa(Thread::Current());
1380 // Fixup the pointers in the newly written intern table to contain image addresses.
1381 InternTable temp_intern_table;
1382 // Note that we require that ReadFromMemory does not make an internal copy of the elements
1383 // so that the VisitRoots() will update the memory directly rather than the copies.
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001384 temp_intern_table.AddTableFromMemory(target_base + intern_table_section.Offset(),
1385 [&](InternTable::UnorderedSet& strings)
1386 REQUIRES_SHARED(Locks::mutator_lock_) {
1387 for (GcRoot<mirror::String>& root : strings) {
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -08001388 root = GcRoot<mirror::String>(forward_object(root.Read<kWithoutReadBarrier>()));
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001389 }
Mathieu Chartier8cc418e2018-10-31 10:54:30 -07001390 }, /*is_boot_image=*/ false);
Mathieu Chartier74ccee62018-10-10 10:30:29 -07001391 }
Artem Udovichenkoa62cb9b2016-06-30 09:18:25 +00001392 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07001393 if (VLOG_IS_ON(image)) {
Andreas Gampe3fec9ac2016-09-13 10:47:28 -07001394 logger.Dump(LOG_STREAM(INFO));
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001395 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07001396 return true;
Andreas Gampe7fa55782016-06-15 17:45:01 -07001397 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07001398};
Hiroshi Yamauchibd0fb612014-05-20 13:46:00 -07001399
Vladimir Marko82e1e272018-08-20 13:38:06 +00001400class ImageSpace::BootImageLoader {
1401 public:
Vladimir Marko91f10322018-12-07 18:04:10 +00001402 BootImageLoader(const std::vector<std::string>& boot_class_path,
1403 const std::vector<std::string>& boot_class_path_locations,
1404 const std::string& image_location,
1405 InstructionSet image_isa)
1406 : boot_class_path_(boot_class_path),
1407 boot_class_path_locations_(boot_class_path_locations),
1408 image_location_(image_location),
Vladimir Marko82e1e272018-08-20 13:38:06 +00001409 image_isa_(image_isa),
1410 is_zygote_(Runtime::Current()->IsZygote()),
1411 has_system_(false),
1412 has_cache_(false),
1413 is_global_cache_(true),
Vladimir Markoe3070022018-08-22 09:36:19 +00001414 dalvik_cache_exists_(false),
Vladimir Marko82e1e272018-08-20 13:38:06 +00001415 dalvik_cache_(),
1416 cache_filename_() {
1417 }
1418
1419 bool IsZygote() const { return is_zygote_; }
1420
1421 void FindImageFiles() {
1422 std::string system_filename;
Vladimir Marko82e1e272018-08-20 13:38:06 +00001423 bool found_image = FindImageFilenameImpl(image_location_.c_str(),
1424 image_isa_,
1425 &has_system_,
1426 &system_filename,
Vladimir Markoe3070022018-08-22 09:36:19 +00001427 &dalvik_cache_exists_,
Vladimir Marko82e1e272018-08-20 13:38:06 +00001428 &dalvik_cache_,
1429 &is_global_cache_,
1430 &has_cache_,
1431 &cache_filename_);
Vladimir Markoe3070022018-08-22 09:36:19 +00001432 DCHECK(!dalvik_cache_exists_ || !dalvik_cache_.empty());
Vladimir Marko82e1e272018-08-20 13:38:06 +00001433 DCHECK_EQ(found_image, has_system_ || has_cache_);
1434 }
1435
1436 bool HasSystem() const { return has_system_; }
1437 bool HasCache() const { return has_cache_; }
1438
Vladimir Markoe3070022018-08-22 09:36:19 +00001439 bool DalvikCacheExists() const { return dalvik_cache_exists_; }
Vladimir Marko82e1e272018-08-20 13:38:06 +00001440 bool IsGlobalCache() const { return is_global_cache_; }
1441
1442 const std::string& GetDalvikCache() const {
Vladimir Marko82e1e272018-08-20 13:38:06 +00001443 return dalvik_cache_;
1444 }
1445
1446 const std::string& GetCacheFilename() const {
Vladimir Marko82e1e272018-08-20 13:38:06 +00001447 return cache_filename_;
1448 }
1449
Vladimir Markod44d7032018-08-30 13:02:31 +01001450 bool LoadFromSystem(size_t extra_reservation_size,
1451 /*out*/std::vector<std::unique_ptr<space::ImageSpace>>* boot_image_spaces,
1452 /*out*/MemMap* extra_reservation,
1453 /*out*/std::string* error_msg) REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001454 TimingLogger logger(__PRETTY_FUNCTION__, /*precise=*/ true, VLOG_IS_ON(image));
Vladimir Marko82e1e272018-08-20 13:38:06 +00001455 std::string filename = GetSystemImageFilename(image_location_.c_str(), image_isa_);
Vladimir Markoc09cd052018-08-23 16:36:36 +01001456
Vladimir Marko7391c8c2018-11-21 17:58:44 +00001457 if (!LoadFromFile(filename,
1458 /*validate_oat_file=*/ false,
1459 extra_reservation_size,
1460 &logger,
1461 boot_image_spaces,
1462 extra_reservation,
1463 error_msg)) {
Vladimir Markoc09cd052018-08-23 16:36:36 +01001464 return false;
1465 }
1466
Vladimir Marko4df2d802018-09-27 16:42:44 +00001467 if (VLOG_IS_ON(image)) {
Vladimir Marko312f10e2018-11-21 12:35:24 +00001468 LOG(INFO) << "ImageSpace::BootImageLoader::LoadFromSystem exiting "
1469 << boot_image_spaces->front();
Vladimir Marko4df2d802018-09-27 16:42:44 +00001470 logger.Dump(LOG_STREAM(INFO));
1471 }
Vladimir Marko82e1e272018-08-20 13:38:06 +00001472 return true;
1473 }
1474
1475 bool LoadFromDalvikCache(
Vladimir Marko82e1e272018-08-20 13:38:06 +00001476 bool validate_oat_file,
Vladimir Markod44d7032018-08-30 13:02:31 +01001477 size_t extra_reservation_size,
1478 /*out*/std::vector<std::unique_ptr<space::ImageSpace>>* boot_image_spaces,
1479 /*out*/MemMap* extra_reservation,
1480 /*out*/std::string* error_msg) REQUIRES_SHARED(Locks::mutator_lock_) {
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001481 TimingLogger logger(__PRETTY_FUNCTION__, /*precise=*/ true, VLOG_IS_ON(image));
Vladimir Marko82e1e272018-08-20 13:38:06 +00001482 DCHECK(DalvikCacheExists());
Vladimir Markoc09cd052018-08-23 16:36:36 +01001483
Vladimir Marko7391c8c2018-11-21 17:58:44 +00001484 if (!LoadFromFile(cache_filename_,
1485 validate_oat_file,
1486 extra_reservation_size,
1487 &logger,
1488 boot_image_spaces,
1489 extra_reservation,
1490 error_msg)) {
Vladimir Markoc09cd052018-08-23 16:36:36 +01001491 return false;
1492 }
1493
Vladimir Marko4df2d802018-09-27 16:42:44 +00001494 if (VLOG_IS_ON(image)) {
Vladimir Marko312f10e2018-11-21 12:35:24 +00001495 LOG(INFO) << "ImageSpace::BootImageLoader::LoadFromDalvikCache exiting "
1496 << boot_image_spaces->front();
Vladimir Marko4df2d802018-09-27 16:42:44 +00001497 logger.Dump(LOG_STREAM(INFO));
1498 }
Vladimir Marko82e1e272018-08-20 13:38:06 +00001499 return true;
1500 }
1501
1502 private:
Vladimir Marko7391c8c2018-11-21 17:58:44 +00001503 bool LoadFromFile(
1504 const std::string& filename,
1505 bool validate_oat_file,
1506 size_t extra_reservation_size,
1507 TimingLogger* logger,
1508 /*out*/std::vector<std::unique_ptr<space::ImageSpace>>* boot_image_spaces,
1509 /*out*/MemMap* extra_reservation,
1510 /*out*/std::string* error_msg) REQUIRES_SHARED(Locks::mutator_lock_) {
1511 ImageHeader system_hdr;
1512 if (!ReadSpecificImageHeader(filename.c_str(), &system_hdr)) {
1513 *error_msg = StringPrintf("Cannot read header of %s", filename.c_str());
1514 return false;
1515 }
Vladimir Marko0ace5632018-12-14 11:11:47 +00001516 if (system_hdr.GetComponentCount() == 0u ||
1517 system_hdr.GetComponentCount() > boot_class_path_.size()) {
1518 *error_msg = StringPrintf("Unexpected component count in %s, received %u, "
1519 "expected non-zero and <= %zu",
Vladimir Marko7391c8c2018-11-21 17:58:44 +00001520 filename.c_str(),
1521 system_hdr.GetComponentCount(),
1522 boot_class_path_.size());
1523 return false;
1524 }
1525 MemMap image_reservation;
1526 MemMap local_extra_reservation;
1527 if (!ReserveBootImageMemory(system_hdr.GetImageReservationSize(),
1528 reinterpret_cast32<uint32_t>(system_hdr.GetImageBegin()),
1529 extra_reservation_size,
1530 &image_reservation,
1531 &local_extra_reservation,
1532 error_msg)) {
1533 return false;
1534 }
1535
Vladimir Marko0ace5632018-12-14 11:11:47 +00001536 ArrayRef<const std::string> provided_locations(boot_class_path_locations_.data(),
1537 system_hdr.GetComponentCount());
Vladimir Marko7391c8c2018-11-21 17:58:44 +00001538 std::vector<std::string> locations =
Vladimir Marko0ace5632018-12-14 11:11:47 +00001539 ExpandMultiImageLocations(provided_locations, image_location_);
Vladimir Marko7391c8c2018-11-21 17:58:44 +00001540 std::vector<std::string> filenames =
Vladimir Marko0ace5632018-12-14 11:11:47 +00001541 ExpandMultiImageLocations(provided_locations, filename);
Vladimir Marko7391c8c2018-11-21 17:58:44 +00001542 DCHECK_EQ(locations.size(), filenames.size());
1543 std::vector<std::unique_ptr<ImageSpace>> spaces;
1544 spaces.reserve(locations.size());
1545 for (std::size_t i = 0u, size = locations.size(); i != size; ++i) {
1546 spaces.push_back(Load(locations[i], filenames[i], logger, &image_reservation, error_msg));
1547 const ImageSpace* space = spaces.back().get();
1548 if (space == nullptr) {
1549 return false;
1550 }
1551 uint32_t expected_component_count = (i == 0u) ? system_hdr.GetComponentCount() : 0u;
1552 uint32_t expected_reservation_size = (i == 0u) ? system_hdr.GetImageReservationSize() : 0u;
1553 if (!Loader::CheckImageReservationSize(*space, expected_reservation_size, error_msg) ||
1554 !Loader::CheckImageComponentCount(*space, expected_component_count, error_msg)) {
1555 return false;
1556 }
1557 }
1558 for (size_t i = 0u, size = spaces.size(); i != size; ++i) {
1559 std::string expected_boot_class_path =
Vladimir Marko0ace5632018-12-14 11:11:47 +00001560 (i == 0u) ? android::base::Join(provided_locations, ':') : std::string();
Vladimir Marko7391c8c2018-11-21 17:58:44 +00001561 if (!OpenOatFile(spaces[i].get(),
1562 boot_class_path_[i],
1563 expected_boot_class_path,
1564 validate_oat_file,
1565 logger,
1566 &image_reservation,
1567 error_msg)) {
1568 return false;
1569 }
1570 }
1571 if (!CheckReservationExhausted(image_reservation, error_msg)) {
1572 return false;
1573 }
1574
1575 MaybeRelocateSpaces(spaces, logger);
1576 InitRuntimeMethods(spaces);
1577 boot_image_spaces->swap(spaces);
1578 *extra_reservation = std::move(local_extra_reservation);
1579 return true;
1580 }
1581
Mathieu Chartierd3f037b2018-12-06 23:50:56 -08001582 private:
1583 class RelocateVisitor {
1584 public:
1585 explicit RelocateVisitor(uint32_t diff) : diff_(diff) {}
Vladimir Marko4df2d802018-09-27 16:42:44 +00001586
Mathieu Chartierd3f037b2018-12-06 23:50:56 -08001587 template <typename T>
1588 ALWAYS_INLINE T* operator()(T* src) const {
1589 DCHECK(src != nullptr);
1590 return reinterpret_cast32<T*>(reinterpret_cast32<uint32_t>(src) + diff_);
Vladimir Marko4df2d802018-09-27 16:42:44 +00001591 }
Vladimir Marko4df2d802018-09-27 16:42:44 +00001592
Mathieu Chartierd3f037b2018-12-06 23:50:56 -08001593 private:
1594 const uint32_t diff_;
1595 };
Vladimir Marko4df2d802018-09-27 16:42:44 +00001596
Vladimir Marko4df2d802018-09-27 16:42:44 +00001597 template <PointerSize kPointerSize>
1598 static void DoRelocateSpaces(const std::vector<std::unique_ptr<ImageSpace>>& spaces,
1599 uint32_t diff) REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier2ffc74b2019-01-03 19:25:41 -08001600 std::unique_ptr<gc::accounting::ContinuousSpaceBitmap> patched_objects(
1601 gc::accounting::ContinuousSpaceBitmap::Create(
1602 "Marked objects",
1603 spaces.front()->Begin(),
1604 spaces.back()->End() - spaces.front()->Begin()));
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -08001605 using PatchRelocateVisitor = PatchObjectVisitor<kPointerSize, RelocateVisitor, RelocateVisitor>;
Mathieu Chartierd3f037b2018-12-06 23:50:56 -08001606 RelocateVisitor relocate_visitor(diff);
Mathieu Chartierf0a96eb2019-01-11 11:06:43 -08001607 PatchRelocateVisitor patch_object_visitor(relocate_visitor, relocate_visitor);
Vladimir Marko4df2d802018-09-27 16:42:44 +00001608
1609 mirror::Class* dcheck_class_class = nullptr; // Used only for a DCHECK().
Vladimir Markoafe14eb2018-10-01 12:11:14 +01001610 for (size_t s = 0u, size = spaces.size(); s != size; ++s) {
Vladimir Marko4df2d802018-09-27 16:42:44 +00001611 const ImageSpace* space = spaces[s].get();
1612
1613 // First patch the image header. The `diff` is OK for patching 32-bit fields but
1614 // the 64-bit method fields in the ImageHeader may need a negative `delta`.
1615 reinterpret_cast<ImageHeader*>(space->Begin())->RelocateImage(
1616 (reinterpret_cast32<uint32_t>(space->Begin()) < diff)
1617 ? -static_cast<int64_t>(-diff) : static_cast<int64_t>(diff));
1618
1619 // Patch fields and methods.
1620 const ImageHeader& image_header = space->GetImageHeader();
Mathieu Chartierd3f037b2018-12-06 23:50:56 -08001621 PatchArtFieldVisitor<PatchRelocateVisitor> field_visitor(patch_object_visitor);
Vladimir Marko4df2d802018-09-27 16:42:44 +00001622 image_header.VisitPackedArtFields(&field_visitor, space->Begin());
Mathieu Chartierd3f037b2018-12-06 23:50:56 -08001623 PatchArtMethodVisitor<kPointerSize, PatchRelocateVisitor, PatchRelocateVisitor>
1624 method_visitor(patch_object_visitor, patch_object_visitor);
Vladimir Marko4df2d802018-09-27 16:42:44 +00001625 image_header.VisitPackedArtMethods(&method_visitor, space->Begin(), kPointerSize);
Mathieu Chartierd3f037b2018-12-06 23:50:56 -08001626 auto method_table_visitor = [&](ArtMethod* method) {
Vladimir Marko4df2d802018-09-27 16:42:44 +00001627 DCHECK(method != nullptr);
Mathieu Chartierd3f037b2018-12-06 23:50:56 -08001628 return relocate_visitor(method);
Vladimir Marko4df2d802018-09-27 16:42:44 +00001629 };
1630 image_header.VisitPackedImTables(method_table_visitor, space->Begin(), kPointerSize);
1631 image_header.VisitPackedImtConflictTables(method_table_visitor, space->Begin(), kPointerSize);
1632
1633 // Patch the intern table.
1634 if (image_header.GetInternedStringsSection().Size() != 0u) {
1635 const uint8_t* data = space->Begin() + image_header.GetInternedStringsSection().Offset();
1636 size_t read_count;
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001637 InternTable::UnorderedSet temp_set(data, /*make_copy_of_data=*/ false, &read_count);
Vladimir Marko4df2d802018-09-27 16:42:44 +00001638 for (GcRoot<mirror::String>& slot : temp_set) {
Mathieu Chartierd3f037b2018-12-06 23:50:56 -08001639 patch_object_visitor.template PatchGcRoot</*kMayBeNull=*/ false>(&slot);
Vladimir Marko4df2d802018-09-27 16:42:44 +00001640 }
1641 }
1642
1643 // Patch the class table and classes, so that we can traverse class hierarchy to
1644 // determine the types of other objects when we visit them later.
1645 if (image_header.GetClassTableSection().Size() != 0u) {
1646 uint8_t* data = space->Begin() + image_header.GetClassTableSection().Offset();
1647 size_t read_count;
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001648 ClassTable::ClassSet temp_set(data, /*make_copy_of_data=*/ false, &read_count);
Vladimir Marko4df2d802018-09-27 16:42:44 +00001649 DCHECK(!temp_set.empty());
Mathieu Chartierd3f037b2018-12-06 23:50:56 -08001650 ClassTableVisitor class_table_visitor(relocate_visitor);
Vladimir Marko4df2d802018-09-27 16:42:44 +00001651 for (ClassTable::TableSlot& slot : temp_set) {
1652 slot.VisitRoot(class_table_visitor);
1653 mirror::Class* klass = slot.Read<kWithoutReadBarrier>();
1654 DCHECK(klass != nullptr);
Mathieu Chartier2ffc74b2019-01-03 19:25:41 -08001655 patched_objects->Set(klass);
Vladimir Marko4df2d802018-09-27 16:42:44 +00001656 patch_object_visitor.VisitClass(klass);
1657 if (kIsDebugBuild) {
1658 mirror::Class* class_class = klass->GetClass<kVerifyNone, kWithoutReadBarrier>();
1659 if (dcheck_class_class == nullptr) {
1660 dcheck_class_class = class_class;
1661 } else {
1662 CHECK_EQ(class_class, dcheck_class_class);
1663 }
1664 }
1665 // Then patch the non-embedded vtable and iftable.
1666 mirror::PointerArray* vtable = klass->GetVTable<kVerifyNone, kWithoutReadBarrier>();
Mathieu Chartier2ffc74b2019-01-03 19:25:41 -08001667 if (vtable != nullptr && !patched_objects->Set(vtable)) {
Vladimir Marko4df2d802018-09-27 16:42:44 +00001668 patch_object_visitor.VisitPointerArray(vtable);
1669 }
1670 auto* iftable = klass->GetIfTable<kVerifyNone, kWithoutReadBarrier>();
1671 if (iftable != nullptr) {
Vladimir Markodbcb48f2018-11-12 11:47:04 +00001672 int32_t ifcount = klass->GetIfTableCount<kVerifyNone>();
Vladimir Marko4df2d802018-09-27 16:42:44 +00001673 for (int32_t i = 0; i != ifcount; ++i) {
1674 mirror::PointerArray* unpatched_ifarray =
1675 iftable->GetMethodArrayOrNull<kVerifyNone, kWithoutReadBarrier>(i);
1676 if (unpatched_ifarray != nullptr) {
1677 // The iftable has not been patched, so we need to explicitly adjust the pointer.
Mathieu Chartierd3f037b2018-12-06 23:50:56 -08001678 mirror::PointerArray* ifarray = relocate_visitor(unpatched_ifarray);
Mathieu Chartier2ffc74b2019-01-03 19:25:41 -08001679 if (!patched_objects->Set(ifarray)) {
Vladimir Marko4df2d802018-09-27 16:42:44 +00001680 patch_object_visitor.VisitPointerArray(ifarray);
1681 }
1682 }
1683 }
1684 }
1685 }
1686 }
1687 }
1688
1689 // Patch class roots now, so that we can recognize mirror::Method and mirror::Constructor.
1690 ObjPtr<mirror::Class> method_class;
1691 ObjPtr<mirror::Class> constructor_class;
1692 {
1693 const ImageSpace* space = spaces.front().get();
1694 const ImageHeader& image_header = space->GetImageHeader();
1695
1696 ObjPtr<mirror::ObjectArray<mirror::Object>> image_roots =
1697 image_header.GetImageRoots<kWithoutReadBarrier>();
Mathieu Chartier2ffc74b2019-01-03 19:25:41 -08001698 patched_objects->Set(image_roots.Ptr());
Vladimir Marko4df2d802018-09-27 16:42:44 +00001699 patch_object_visitor.VisitObject(image_roots.Ptr());
1700
1701 ObjPtr<mirror::ObjectArray<mirror::Class>> class_roots =
1702 ObjPtr<mirror::ObjectArray<mirror::Class>>::DownCast(MakeObjPtr(
1703 image_header.GetImageRoot<kWithoutReadBarrier>(ImageHeader::kClassRoots)));
Mathieu Chartier2ffc74b2019-01-03 19:25:41 -08001704 patched_objects->Set(class_roots.Ptr());
Vladimir Marko4df2d802018-09-27 16:42:44 +00001705 patch_object_visitor.VisitObject(class_roots.Ptr());
1706
1707 method_class = GetClassRoot<mirror::Method, kWithoutReadBarrier>(class_roots);
1708 constructor_class = GetClassRoot<mirror::Constructor, kWithoutReadBarrier>(class_roots);
1709 }
1710
Vladimir Markoafe14eb2018-10-01 12:11:14 +01001711 for (size_t s = 0u, size = spaces.size(); s != size; ++s) {
Vladimir Marko4df2d802018-09-27 16:42:44 +00001712 const ImageSpace* space = spaces[s].get();
1713 const ImageHeader& image_header = space->GetImageHeader();
1714
1715 static_assert(IsAligned<kObjectAlignment>(sizeof(ImageHeader)), "Header alignment check");
1716 uint32_t objects_end = image_header.GetObjectsSection().Size();
1717 DCHECK_ALIGNED(objects_end, kObjectAlignment);
1718 for (uint32_t pos = sizeof(ImageHeader); pos != objects_end; ) {
1719 mirror::Object* object = reinterpret_cast<mirror::Object*>(space->Begin() + pos);
Mathieu Chartier2ffc74b2019-01-03 19:25:41 -08001720 if (!patched_objects->Test(object)) {
1721 // This is the last pass over objects, so we do not need to Set().
Vladimir Marko4df2d802018-09-27 16:42:44 +00001722 patch_object_visitor.VisitObject(object);
1723 mirror::Class* klass = object->GetClass<kVerifyNone, kWithoutReadBarrier>();
1724 if (klass->IsDexCacheClass<kVerifyNone>()) {
1725 // Patch dex cache array pointers and elements.
1726 mirror::DexCache* dex_cache = object->AsDexCache<kVerifyNone, kWithoutReadBarrier>();
1727 patch_object_visitor.VisitDexCacheArrays(dex_cache);
1728 } else if (klass == method_class || klass == constructor_class) {
1729 // Patch the ArtMethod* in the mirror::Executable subobject.
1730 ObjPtr<mirror::Executable> as_executable =
1731 ObjPtr<mirror::Executable>::DownCast(MakeObjPtr(object));
1732 ArtMethod* unpatched_method = as_executable->GetArtMethod<kVerifyNone>();
Mathieu Chartierd3f037b2018-12-06 23:50:56 -08001733 ArtMethod* patched_method = relocate_visitor(unpatched_method);
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001734 as_executable->SetArtMethod</*kTransactionActive=*/ false,
1735 /*kCheckTransaction=*/ true,
Vladimir Marko4df2d802018-09-27 16:42:44 +00001736 kVerifyNone>(patched_method);
1737 }
1738 }
1739 pos += RoundUp(object->SizeOf<kVerifyNone>(), kObjectAlignment);
1740 }
1741 }
1742 }
1743
1744 static void MaybeRelocateSpaces(const std::vector<std::unique_ptr<ImageSpace>>& spaces,
1745 TimingLogger* logger)
1746 REQUIRES_SHARED(Locks::mutator_lock_) {
1747 TimingLogger::ScopedTiming timing("MaybeRelocateSpaces", logger);
1748 ImageSpace* first_space = spaces.front().get();
1749 const ImageHeader& first_space_header = first_space->GetImageHeader();
1750 uint32_t diff =
1751 static_cast<uint32_t>(first_space->Begin() - first_space_header.GetImageBegin());
1752 if (!Runtime::Current()->ShouldRelocate()) {
1753 DCHECK_EQ(diff, 0u);
1754 return;
1755 }
1756
1757 PointerSize pointer_size = first_space_header.GetPointerSize();
1758 if (pointer_size == PointerSize::k64) {
1759 DoRelocateSpaces<PointerSize::k64>(spaces, diff);
1760 } else {
1761 DoRelocateSpaces<PointerSize::k32>(spaces, diff);
1762 }
1763 }
1764
1765 static void InitRuntimeMethods(const std::vector<std::unique_ptr<ImageSpace>>& spaces)
1766 REQUIRES_SHARED(Locks::mutator_lock_) {
1767 Runtime* runtime = Runtime::Current();
1768 DCHECK(!runtime->HasResolutionMethod());
1769 DCHECK(!spaces.empty());
1770 ImageSpace* space = spaces[0].get();
1771 const ImageHeader& image_header = space->GetImageHeader();
Vladimir Marko4df2d802018-09-27 16:42:44 +00001772 runtime->SetResolutionMethod(image_header.GetImageMethod(ImageHeader::kResolutionMethod));
1773 runtime->SetImtConflictMethod(image_header.GetImageMethod(ImageHeader::kImtConflictMethod));
1774 runtime->SetImtUnimplementedMethod(
1775 image_header.GetImageMethod(ImageHeader::kImtUnimplementedMethod));
1776 runtime->SetCalleeSaveMethod(
1777 image_header.GetImageMethod(ImageHeader::kSaveAllCalleeSavesMethod),
1778 CalleeSaveType::kSaveAllCalleeSaves);
1779 runtime->SetCalleeSaveMethod(
1780 image_header.GetImageMethod(ImageHeader::kSaveRefsOnlyMethod),
1781 CalleeSaveType::kSaveRefsOnly);
1782 runtime->SetCalleeSaveMethod(
1783 image_header.GetImageMethod(ImageHeader::kSaveRefsAndArgsMethod),
1784 CalleeSaveType::kSaveRefsAndArgs);
1785 runtime->SetCalleeSaveMethod(
1786 image_header.GetImageMethod(ImageHeader::kSaveEverythingMethod),
1787 CalleeSaveType::kSaveEverything);
1788 runtime->SetCalleeSaveMethod(
1789 image_header.GetImageMethod(ImageHeader::kSaveEverythingMethodForClinit),
1790 CalleeSaveType::kSaveEverythingForClinit);
1791 runtime->SetCalleeSaveMethod(
1792 image_header.GetImageMethod(ImageHeader::kSaveEverythingMethodForSuspendCheck),
1793 CalleeSaveType::kSaveEverythingForSuspendCheck);
1794 }
1795
Vladimir Markoc09cd052018-08-23 16:36:36 +01001796 std::unique_ptr<ImageSpace> Load(const std::string& image_location,
1797 const std::string& image_filename,
Vladimir Marko4df2d802018-09-27 16:42:44 +00001798 TimingLogger* logger,
Vladimir Markoc09cd052018-08-23 16:36:36 +01001799 /*inout*/MemMap* image_reservation,
Vladimir Markoc09cd052018-08-23 16:36:36 +01001800 /*out*/std::string* error_msg)
1801 REQUIRES_SHARED(Locks::mutator_lock_) {
1802 // Should this be a RDWR lock? This is only a defensive measure, as at
1803 // this point the image should exist.
1804 // However, only the zygote can write into the global dalvik-cache, so
1805 // restrict to zygote processes, or any process that isn't using
1806 // /data/dalvik-cache (which we assume to be allowed to write there).
1807 const bool rw_lock = is_zygote_ || !is_global_cache_;
1808
1809 // Note that we must not use the file descriptor associated with
1810 // ScopedFlock::GetFile to Init the image file. We want the file
1811 // descriptor (and the associated exclusive lock) to be released when
1812 // we leave Create.
1813 ScopedFlock image = LockedFile::Open(image_filename.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001814 /*flags=*/ rw_lock ? (O_CREAT | O_RDWR) : O_RDONLY,
1815 /*block=*/ true,
Vladimir Markoc09cd052018-08-23 16:36:36 +01001816 error_msg);
1817
1818 VLOG(startup) << "Using image file " << image_filename.c_str() << " for image location "
1819 << image_location;
1820 // If we are in /system we can assume the image is good. We can also
1821 // assume this if we are using a relocated image (i.e. image checksum
1822 // matches) since this is only different by the offset. We need this to
1823 // make sure that host tests continue to work.
1824 // Since we are the boot image, pass null since we load the oat file from the boot image oat
1825 // file name.
1826 return Loader::Init(image_filename.c_str(),
1827 image_location.c_str(),
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001828 /*oat_file=*/ nullptr,
Vladimir Marko4df2d802018-09-27 16:42:44 +00001829 logger,
Vladimir Markoc09cd052018-08-23 16:36:36 +01001830 image_reservation,
Vladimir Markoc09cd052018-08-23 16:36:36 +01001831 error_msg);
1832 }
1833
Vladimir Marko312f10e2018-11-21 12:35:24 +00001834 bool OpenOatFile(ImageSpace* space,
Vladimir Marko91f10322018-12-07 18:04:10 +00001835 const std::string& dex_filename,
1836 const std::string& expected_boot_class_path,
Vladimir Marko312f10e2018-11-21 12:35:24 +00001837 bool validate_oat_file,
1838 TimingLogger* logger,
1839 /*inout*/MemMap* image_reservation,
1840 /*out*/std::string* error_msg) {
1841 // VerifyImageAllocations() will be called later in Runtime::Init()
1842 // as some class roots like ArtMethod::java_lang_reflect_ArtMethod_
1843 // and ArtField::java_lang_reflect_ArtField_, which are used from
1844 // Object::SizeOf() which VerifyImageAllocations() calls, are not
1845 // set yet at this point.
1846 DCHECK(image_reservation != nullptr);
1847 std::unique_ptr<OatFile> oat_file;
1848 {
1849 TimingLogger::ScopedTiming timing("OpenOatFile", logger);
1850 std::string oat_filename =
1851 ImageHeader::GetOatLocationFromImageLocation(space->GetImageFilename());
Vladimir Marko91f10322018-12-07 18:04:10 +00001852 std::string oat_location =
1853 ImageHeader::GetOatLocationFromImageLocation(space->GetImageLocation());
Vladimir Marko312f10e2018-11-21 12:35:24 +00001854
1855 oat_file.reset(OatFile::Open(/*zip_fd=*/ -1,
1856 oat_filename,
Vladimir Marko91f10322018-12-07 18:04:10 +00001857 oat_location,
Vladimir Marko312f10e2018-11-21 12:35:24 +00001858 !Runtime::Current()->IsAotCompiler(),
1859 /*low_4gb=*/ false,
Vladimir Marko91f10322018-12-07 18:04:10 +00001860 /*abs_dex_location=*/ dex_filename.c_str(),
Vladimir Marko312f10e2018-11-21 12:35:24 +00001861 image_reservation,
1862 error_msg));
1863 if (oat_file == nullptr) {
1864 *error_msg = StringPrintf("Failed to open oat file '%s' referenced from image %s: %s",
1865 oat_filename.c_str(),
1866 space->GetName(),
1867 error_msg->c_str());
1868 return false;
1869 }
1870 const ImageHeader& image_header = space->GetImageHeader();
1871 uint32_t oat_checksum = oat_file->GetOatHeader().GetChecksum();
1872 uint32_t image_oat_checksum = image_header.GetOatChecksum();
1873 if (oat_checksum != image_oat_checksum) {
1874 *error_msg = StringPrintf("Failed to match oat file checksum 0x%x to expected oat checksum"
1875 " 0x%x in image %s",
1876 oat_checksum,
1877 image_oat_checksum,
1878 space->GetName());
1879 return false;
1880 }
Vladimir Marko91f10322018-12-07 18:04:10 +00001881 const char* oat_boot_class_path =
1882 oat_file->GetOatHeader().GetStoreValueByKey(OatHeader::kBootClassPathKey);
1883 oat_boot_class_path = (oat_boot_class_path != nullptr) ? oat_boot_class_path : "";
1884 if (expected_boot_class_path != oat_boot_class_path) {
1885 *error_msg = StringPrintf("Failed to match oat boot class path %s to expected "
1886 "boot class path %s in image %s",
1887 oat_boot_class_path,
1888 expected_boot_class_path.c_str(),
1889 space->GetName());
1890 return false;
1891 }
Vladimir Marko312f10e2018-11-21 12:35:24 +00001892 ptrdiff_t relocation_diff = space->Begin() - image_header.GetImageBegin();
1893 CHECK(image_header.GetOatDataBegin() != nullptr);
1894 uint8_t* oat_data_begin = image_header.GetOatDataBegin() + relocation_diff;
1895 if (oat_file->Begin() != oat_data_begin) {
1896 *error_msg = StringPrintf("Oat file '%s' referenced from image %s has unexpected begin"
1897 " %p v. %p",
1898 oat_filename.c_str(),
1899 space->GetName(),
1900 oat_file->Begin(),
1901 oat_data_begin);
1902 return false;
1903 }
1904 }
1905 if (validate_oat_file) {
1906 TimingLogger::ScopedTiming timing("ValidateOatFile", logger);
1907 if (!ImageSpace::ValidateOatFile(*oat_file, error_msg)) {
1908 DCHECK(!error_msg->empty());
1909 return false;
1910 }
1911 }
1912 space->oat_file_ = std::move(oat_file);
1913 space->oat_file_non_owned_ = space->oat_file_.get();
1914 return true;
1915 }
1916
Vladimir Marko312f10e2018-11-21 12:35:24 +00001917 bool ReserveBootImageMemory(uint32_t reservation_size,
1918 uint32_t image_start,
Vladimir Markod44d7032018-08-30 13:02:31 +01001919 size_t extra_reservation_size,
Vladimir Markoc09cd052018-08-23 16:36:36 +01001920 /*out*/MemMap* image_reservation,
Vladimir Markod44d7032018-08-30 13:02:31 +01001921 /*out*/MemMap* extra_reservation,
Vladimir Markoc09cd052018-08-23 16:36:36 +01001922 /*out*/std::string* error_msg) {
Vladimir Marko7391c8c2018-11-21 17:58:44 +00001923 DCHECK_ALIGNED(reservation_size, kPageSize);
1924 DCHECK_ALIGNED(image_start, kPageSize);
Vladimir Markoc09cd052018-08-23 16:36:36 +01001925 DCHECK(!image_reservation->IsValid());
Vladimir Marko312f10e2018-11-21 12:35:24 +00001926 DCHECK_LT(extra_reservation_size, std::numeric_limits<uint32_t>::max() - reservation_size);
1927 size_t total_size = reservation_size + extra_reservation_size;
Vladimir Marko4df2d802018-09-27 16:42:44 +00001928 bool relocate = Runtime::Current()->ShouldRelocate();
Vladimir Markoae581ed2018-10-08 09:29:05 +01001929 // If relocating, choose a random address for ALSR.
1930 uint32_t addr = relocate ? ART_BASE_ADDRESS + ChooseRelocationOffsetDelta() : image_start;
Vladimir Markoc09cd052018-08-23 16:36:36 +01001931 *image_reservation =
1932 MemMap::MapAnonymous("Boot image reservation",
Vladimir Markoae581ed2018-10-08 09:29:05 +01001933 reinterpret_cast32<uint8_t*>(addr),
1934 total_size,
Vladimir Markoc09cd052018-08-23 16:36:36 +01001935 PROT_NONE,
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001936 /*low_4gb=*/ true,
1937 /*reuse=*/ false,
1938 /*reservation=*/ nullptr,
Vladimir Markoc09cd052018-08-23 16:36:36 +01001939 error_msg);
1940 if (!image_reservation->IsValid()) {
1941 return false;
1942 }
Vladimir Markod44d7032018-08-30 13:02:31 +01001943 DCHECK(!extra_reservation->IsValid());
1944 if (extra_reservation_size != 0u) {
1945 DCHECK_ALIGNED(extra_reservation_size, kPageSize);
1946 DCHECK_LT(extra_reservation_size, image_reservation->Size());
1947 uint8_t* split = image_reservation->End() - extra_reservation_size;
1948 *extra_reservation = image_reservation->RemapAtEnd(split,
1949 "Boot image extra reservation",
1950 PROT_NONE,
1951 error_msg);
1952 if (!extra_reservation->IsValid()) {
1953 return false;
1954 }
1955 }
Vladimir Markoc09cd052018-08-23 16:36:36 +01001956
1957 return true;
1958 }
1959
Vladimir Marko312f10e2018-11-21 12:35:24 +00001960 bool CheckReservationExhausted(const MemMap& image_reservation, /*out*/std::string* error_msg) {
Vladimir Markoc09cd052018-08-23 16:36:36 +01001961 if (image_reservation.IsValid()) {
1962 *error_msg = StringPrintf("Excessive image reservation after loading boot image: %p-%p",
1963 image_reservation.Begin(),
1964 image_reservation.End());
1965 return false;
1966 }
Vladimir Markoc09cd052018-08-23 16:36:36 +01001967 return true;
1968 }
1969
Vladimir Marko91f10322018-12-07 18:04:10 +00001970 const std::vector<std::string>& boot_class_path_;
1971 const std::vector<std::string>& boot_class_path_locations_;
Vladimir Marko82e1e272018-08-20 13:38:06 +00001972 const std::string& image_location_;
1973 InstructionSet image_isa_;
1974 bool is_zygote_;
1975 bool has_system_;
1976 bool has_cache_;
1977 bool is_global_cache_;
Vladimir Markoe3070022018-08-22 09:36:19 +00001978 bool dalvik_cache_exists_;
Vladimir Marko82e1e272018-08-20 13:38:06 +00001979 std::string dalvik_cache_;
1980 std::string cache_filename_;
1981};
1982
Andreas Gampea463b6a2016-08-12 21:53:32 -07001983static constexpr uint64_t kLowSpaceValue = 50 * MB;
1984static constexpr uint64_t kTmpFsSentinelValue = 384 * MB;
1985
1986// Read the free space of the cache partition and make a decision whether to keep the generated
1987// image. This is to try to mitigate situations where the system might run out of space later.
1988static bool CheckSpace(const std::string& cache_filename, std::string* error_msg) {
1989 // Using statvfs vs statvfs64 because of b/18207376, and it is enough for all practical purposes.
1990 struct statvfs buf;
1991
1992 int res = TEMP_FAILURE_RETRY(statvfs(cache_filename.c_str(), &buf));
1993 if (res != 0) {
1994 // Could not stat. Conservatively tell the system to delete the image.
1995 *error_msg = "Could not stat the filesystem, assuming low-memory situation.";
1996 return false;
Nicolas Geoffray1bc977c2016-01-23 14:15:49 +00001997 }
Nicolas Geoffray1bc977c2016-01-23 14:15:49 +00001998
Andreas Gampea463b6a2016-08-12 21:53:32 -07001999 uint64_t fs_overall_size = buf.f_bsize * static_cast<uint64_t>(buf.f_blocks);
2000 // Zygote is privileged, but other things are not. Use bavail.
2001 uint64_t fs_free_size = buf.f_bsize * static_cast<uint64_t>(buf.f_bavail);
Brian Carlstrom56d947f2013-07-15 13:14:23 -07002002
Andreas Gampea463b6a2016-08-12 21:53:32 -07002003 // Take the overall size as an indicator for a tmpfs, which is being used for the decryption
2004 // environment. We do not want to fail quickening the boot image there, as it is beneficial
2005 // for time-to-UI.
2006 if (fs_overall_size > kTmpFsSentinelValue) {
2007 if (fs_free_size < kLowSpaceValue) {
2008 *error_msg = StringPrintf("Low-memory situation: only %4.2f megabytes available, need at "
2009 "least %" PRIu64 ".",
2010 static_cast<double>(fs_free_size) / MB,
2011 kLowSpaceValue / MB);
Brian Carlstrom56d947f2013-07-15 13:14:23 -07002012 return false;
2013 }
2014 }
2015 return true;
2016}
2017
Vladimir Marko82e1e272018-08-20 13:38:06 +00002018bool ImageSpace::LoadBootImage(
Vladimir Marko91f10322018-12-07 18:04:10 +00002019 const std::vector<std::string>& boot_class_path,
2020 const std::vector<std::string>& boot_class_path_locations,
Vladimir Marko82e1e272018-08-20 13:38:06 +00002021 const std::string& image_location,
2022 const InstructionSet image_isa,
Vladimir Markod44d7032018-08-30 13:02:31 +01002023 size_t extra_reservation_size,
2024 /*out*/std::vector<std::unique_ptr<space::ImageSpace>>* boot_image_spaces,
2025 /*out*/MemMap* extra_reservation) {
Andreas Gampea463b6a2016-08-12 21:53:32 -07002026 ScopedTrace trace(__FUNCTION__);
2027
Vladimir Marko82e1e272018-08-20 13:38:06 +00002028 DCHECK(boot_image_spaces != nullptr);
2029 DCHECK(boot_image_spaces->empty());
Vladimir Markod44d7032018-08-30 13:02:31 +01002030 DCHECK_ALIGNED(extra_reservation_size, kPageSize);
2031 DCHECK(extra_reservation != nullptr);
Vladimir Marko82e1e272018-08-20 13:38:06 +00002032 DCHECK_NE(image_isa, InstructionSet::kNone);
2033
2034 if (image_location.empty()) {
2035 return false;
2036 }
2037
Vladimir Marko91f10322018-12-07 18:04:10 +00002038 BootImageLoader loader(boot_class_path, boot_class_path_locations, image_location, image_isa);
Vladimir Marko82e1e272018-08-20 13:38:06 +00002039
Andreas Gampea463b6a2016-08-12 21:53:32 -07002040 // Step 0: Extra zygote work.
2041
2042 // Step 0.a: If we're the zygote, mark boot.
Vladimir Marko82e1e272018-08-20 13:38:06 +00002043 if (loader.IsZygote() && CanWriteToDalvikCache(image_isa)) {
Andreas Gampea463b6a2016-08-12 21:53:32 -07002044 MarkZygoteStart(image_isa, Runtime::Current()->GetZygoteMaxFailedBoots());
2045 }
2046
Vladimir Marko82e1e272018-08-20 13:38:06 +00002047 loader.FindImageFiles();
2048
Andreas Gampea463b6a2016-08-12 21:53:32 -07002049 // Step 0.b: If we're the zygote, check for free space, and prune the cache preemptively,
2050 // if necessary. While the runtime may be fine (it is pretty tolerant to
2051 // out-of-disk-space situations), other parts of the platform are not.
2052 //
2053 // The advantage of doing this proactively is that the later steps are simplified,
2054 // i.e., we do not need to code retries.
Andreas Gampe6e74abb2018-03-01 17:33:19 -08002055 bool dex2oat_enabled = Runtime::Current()->IsImageDex2OatEnabled();
2056
Vladimir Marko82e1e272018-08-20 13:38:06 +00002057 if (loader.IsZygote() && loader.DalvikCacheExists()) {
Andreas Gampe6e74abb2018-03-01 17:33:19 -08002058 // Extra checks for the zygote. These only apply when loading the first image, explained below.
Vladimir Marko82e1e272018-08-20 13:38:06 +00002059 const std::string& dalvik_cache = loader.GetDalvikCache();
Andreas Gampea463b6a2016-08-12 21:53:32 -07002060 DCHECK(!dalvik_cache.empty());
2061 std::string local_error_msg;
Andreas Gampe6e74abb2018-03-01 17:33:19 -08002062 bool check_space = CheckSpace(dalvik_cache, &local_error_msg);
Vladimir Marko4df2d802018-09-27 16:42:44 +00002063 if (!check_space) {
Andreas Gampea463b6a2016-08-12 21:53:32 -07002064 LOG(WARNING) << local_error_msg << " Preemptively pruning the dalvik cache.";
2065 PruneDalvikCache(image_isa);
2066
2067 // Re-evaluate the image.
Vladimir Marko82e1e272018-08-20 13:38:06 +00002068 loader.FindImageFiles();
Andreas Gampea463b6a2016-08-12 21:53:32 -07002069 }
Andreas Gampe6e74abb2018-03-01 17:33:19 -08002070 if (!check_space) {
2071 // Disable compilation/patching - we do not want to fill up the space again.
2072 dex2oat_enabled = false;
2073 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07002074 }
2075
2076 // Collect all the errors.
2077 std::vector<std::string> error_msgs;
2078
Vladimir Marko4df2d802018-09-27 16:42:44 +00002079 // Step 1: Check if we have an existing image in /system.
Andreas Gampea463b6a2016-08-12 21:53:32 -07002080
Vladimir Marko4df2d802018-09-27 16:42:44 +00002081 if (loader.HasSystem()) {
Andreas Gampea463b6a2016-08-12 21:53:32 -07002082 std::string local_error_msg;
Vladimir Markod44d7032018-08-30 13:02:31 +01002083 if (loader.LoadFromSystem(extra_reservation_size,
2084 boot_image_spaces,
2085 extra_reservation,
2086 &local_error_msg)) {
Vladimir Marko82e1e272018-08-20 13:38:06 +00002087 return true;
Andreas Gampea463b6a2016-08-12 21:53:32 -07002088 }
2089 error_msgs.push_back(local_error_msg);
2090 }
2091
Vladimir Marko4df2d802018-09-27 16:42:44 +00002092 // Step 2: Check if we have an existing image in the dalvik cache.
2093 if (loader.HasCache()) {
Andreas Gampea463b6a2016-08-12 21:53:32 -07002094 std::string local_error_msg;
Vladimir Markof4efa9e2018-10-17 14:12:45 +01002095 if (loader.LoadFromDalvikCache(/*validate_oat_file=*/ true,
Vladimir Marko4df2d802018-09-27 16:42:44 +00002096 extra_reservation_size,
2097 boot_image_spaces,
2098 extra_reservation,
2099 &local_error_msg)) {
2100 return true;
Andreas Gampea463b6a2016-08-12 21:53:32 -07002101 }
Vladimir Marko4df2d802018-09-27 16:42:44 +00002102 error_msgs.push_back(local_error_msg);
Andreas Gampea463b6a2016-08-12 21:53:32 -07002103 }
2104
Vladimir Marko82e1e272018-08-20 13:38:06 +00002105 // Step 3: We do not have an existing image in /system,
2106 // so generate an image into the dalvik cache.
Vladimir Markoe3070022018-08-22 09:36:19 +00002107 if (!loader.HasSystem() && loader.DalvikCacheExists()) {
Andreas Gampea463b6a2016-08-12 21:53:32 -07002108 std::string local_error_msg;
Andreas Gampe6e74abb2018-03-01 17:33:19 -08002109 if (!dex2oat_enabled) {
Andreas Gampea463b6a2016-08-12 21:53:32 -07002110 local_error_msg = "Image compilation disabled.";
Vladimir Marko82e1e272018-08-20 13:38:06 +00002111 } else if (ImageCreationAllowed(loader.IsGlobalCache(), image_isa, &local_error_msg)) {
2112 bool compilation_success =
2113 GenerateImage(loader.GetCacheFilename(), image_isa, &local_error_msg);
Andreas Gampea463b6a2016-08-12 21:53:32 -07002114 if (compilation_success) {
Vladimir Markof4efa9e2018-10-17 14:12:45 +01002115 if (loader.LoadFromDalvikCache(/*validate_oat_file=*/ false,
Vladimir Markod44d7032018-08-30 13:02:31 +01002116 extra_reservation_size,
Vladimir Marko82e1e272018-08-20 13:38:06 +00002117 boot_image_spaces,
Vladimir Markod44d7032018-08-30 13:02:31 +01002118 extra_reservation,
Vladimir Marko82e1e272018-08-20 13:38:06 +00002119 &local_error_msg)) {
2120 return true;
Andreas Gampea463b6a2016-08-12 21:53:32 -07002121 }
2122 }
2123 }
2124 error_msgs.push_back(StringPrintf("Cannot compile image to %s: %s",
Vladimir Marko82e1e272018-08-20 13:38:06 +00002125 loader.GetCacheFilename().c_str(),
Andreas Gampea463b6a2016-08-12 21:53:32 -07002126 local_error_msg.c_str()));
2127 }
2128
Vladimir Marko82e1e272018-08-20 13:38:06 +00002129 // We failed. Prune the cache the free up space, create a compound error message
2130 // and return false.
Andreas Gampea463b6a2016-08-12 21:53:32 -07002131 PruneDalvikCache(image_isa);
2132
2133 std::ostringstream oss;
2134 bool first = true;
Andreas Gampe4c481a42016-11-03 08:21:59 -07002135 for (const auto& msg : error_msgs) {
Andreas Gampea463b6a2016-08-12 21:53:32 -07002136 if (!first) {
2137 oss << "\n ";
2138 }
2139 oss << msg;
2140 }
Andreas Gampea463b6a2016-08-12 21:53:32 -07002141
Vladimir Marko82e1e272018-08-20 13:38:06 +00002142 LOG(ERROR) << "Could not create image space with image file '" << image_location << "'. "
2143 << "Attempting to fall back to imageless running. Error was: " << oss.str();
Andreas Gampea463b6a2016-08-12 21:53:32 -07002144
Vladimir Marko82e1e272018-08-20 13:38:06 +00002145 return false;
Andreas Gampe2bd84282016-12-05 12:37:36 -08002146}
2147
Igor Murashkin8275fba2017-05-02 15:58:02 -07002148ImageSpace::~ImageSpace() {
2149 Runtime* runtime = Runtime::Current();
2150 if (runtime == nullptr) {
2151 return;
2152 }
2153
2154 if (GetImageHeader().IsAppImage()) {
2155 // This image space did not modify resolution method then in Init.
2156 return;
2157 }
2158
2159 if (!runtime->HasResolutionMethod()) {
2160 // Another image space has already unloaded the below methods.
2161 return;
2162 }
2163
2164 runtime->ClearInstructionSet();
2165 runtime->ClearResolutionMethod();
2166 runtime->ClearImtConflictMethod();
2167 runtime->ClearImtUnimplementedMethod();
2168 runtime->ClearCalleeSaveMethods();
2169}
2170
Andreas Gampea463b6a2016-08-12 21:53:32 -07002171std::unique_ptr<ImageSpace> ImageSpace::CreateFromAppImage(const char* image,
2172 const OatFile* oat_file,
2173 std::string* error_msg) {
Vladimir Marko312f10e2018-11-21 12:35:24 +00002174 // Note: The oat file has already been validated.
Vladimir Marko4df2d802018-09-27 16:42:44 +00002175 return Loader::InitAppImage(image,
2176 image,
Vladimir Marko4df2d802018-09-27 16:42:44 +00002177 oat_file,
Vladimir Markof4efa9e2018-10-17 14:12:45 +01002178 /*image_reservation=*/ nullptr,
Vladimir Marko4df2d802018-09-27 16:42:44 +00002179 error_msg);
Andreas Gampea463b6a2016-08-12 21:53:32 -07002180}
2181
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07002182const OatFile* ImageSpace::GetOatFile() const {
Andreas Gampe88da3b02015-06-12 20:38:49 -07002183 return oat_file_non_owned_;
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07002184}
2185
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -07002186std::unique_ptr<const OatFile> ImageSpace::ReleaseOatFile() {
2187 CHECK(oat_file_ != nullptr);
2188 return std::move(oat_file_);
Ian Rogers1d54e732013-05-02 21:10:01 -07002189}
2190
Ian Rogers1d54e732013-05-02 21:10:01 -07002191void ImageSpace::Dump(std::ostream& os) const {
2192 os << GetType()
Mathieu Chartier590fee92013-09-13 13:46:47 -07002193 << " begin=" << reinterpret_cast<void*>(Begin())
Ian Rogers1d54e732013-05-02 21:10:01 -07002194 << ",end=" << reinterpret_cast<void*>(End())
2195 << ",size=" << PrettySize(Size())
2196 << ",name=\"" << GetName() << "\"]";
2197}
2198
Richard Uhler84f50ae2017-02-06 15:12:45 +00002199bool ImageSpace::ValidateOatFile(const OatFile& oat_file, std::string* error_msg) {
David Sehr013fd802018-01-11 22:55:24 -08002200 const ArtDexFileLoader dex_file_loader;
Andreas Gampeb40d3612018-06-26 15:49:42 -07002201 for (const OatDexFile* oat_dex_file : oat_file.GetOatDexFiles()) {
Richard Uhler84f50ae2017-02-06 15:12:45 +00002202 const std::string& dex_file_location = oat_dex_file->GetDexFileLocation();
2203
2204 // Skip multidex locations - These will be checked when we visit their
2205 // corresponding primary non-multidex location.
Mathieu Chartier79c87da2017-10-10 11:54:29 -07002206 if (DexFileLoader::IsMultiDexLocation(dex_file_location.c_str())) {
Richard Uhler84f50ae2017-02-06 15:12:45 +00002207 continue;
2208 }
2209
2210 std::vector<uint32_t> checksums;
David Sehr013fd802018-01-11 22:55:24 -08002211 if (!dex_file_loader.GetMultiDexChecksums(dex_file_location.c_str(), &checksums, error_msg)) {
Richard Uhler84f50ae2017-02-06 15:12:45 +00002212 *error_msg = StringPrintf("ValidateOatFile failed to get checksums of dex file '%s' "
2213 "referenced by oat file %s: %s",
2214 dex_file_location.c_str(),
2215 oat_file.GetLocation().c_str(),
2216 error_msg->c_str());
2217 return false;
2218 }
2219 CHECK(!checksums.empty());
2220 if (checksums[0] != oat_dex_file->GetDexFileLocationChecksum()) {
2221 *error_msg = StringPrintf("ValidateOatFile found checksum mismatch between oat file "
2222 "'%s' and dex file '%s' (0x%x != 0x%x)",
2223 oat_file.GetLocation().c_str(),
2224 dex_file_location.c_str(),
2225 oat_dex_file->GetDexFileLocationChecksum(),
2226 checksums[0]);
2227 return false;
2228 }
2229
2230 // Verify checksums for any related multidex entries.
2231 for (size_t i = 1; i < checksums.size(); i++) {
Mathieu Chartier79c87da2017-10-10 11:54:29 -07002232 std::string multi_dex_location = DexFileLoader::GetMultiDexLocation(
2233 i,
2234 dex_file_location.c_str());
Andreas Gampeb40d3612018-06-26 15:49:42 -07002235 const OatDexFile* multi_dex = oat_file.GetOatDexFile(multi_dex_location.c_str(),
2236 nullptr,
2237 error_msg);
Richard Uhler84f50ae2017-02-06 15:12:45 +00002238 if (multi_dex == nullptr) {
2239 *error_msg = StringPrintf("ValidateOatFile oat file '%s' is missing entry '%s'",
2240 oat_file.GetLocation().c_str(),
2241 multi_dex_location.c_str());
2242 return false;
2243 }
2244
2245 if (checksums[i] != multi_dex->GetDexFileLocationChecksum()) {
2246 *error_msg = StringPrintf("ValidateOatFile found checksum mismatch between oat file "
2247 "'%s' and dex file '%s' (0x%x != 0x%x)",
2248 oat_file.GetLocation().c_str(),
2249 multi_dex_location.c_str(),
2250 multi_dex->GetDexFileLocationChecksum(),
2251 checksums[i]);
2252 return false;
2253 }
2254 }
2255 }
2256 return true;
2257}
2258
Vladimir Marko0ace5632018-12-14 11:11:47 +00002259std::string ImageSpace::GetBootClassPathChecksums(const std::vector<std::string>& boot_class_path,
2260 const std::string& image_location,
2261 InstructionSet image_isa,
2262 /*out*/std::string* error_msg) {
2263 std::string system_filename;
2264 bool has_system = false;
2265 std::string cache_filename;
2266 bool has_cache = false;
2267 bool dalvik_cache_exists = false;
2268 bool is_global_cache = false;
2269 if (!FindImageFilename(image_location.c_str(),
2270 image_isa,
2271 &system_filename,
2272 &has_system,
2273 &cache_filename,
2274 &dalvik_cache_exists,
2275 &has_cache,
2276 &is_global_cache)) {
2277 *error_msg = StringPrintf("Unable to find image file for %s and %s",
2278 image_location.c_str(),
2279 GetInstructionSetString(image_isa));
2280 return std::string();
2281 }
2282
2283 DCHECK(has_system || has_cache);
2284 const std::string& filename = has_system ? system_filename : cache_filename;
2285 std::unique_ptr<ImageHeader> header = ReadSpecificImageHeader(filename.c_str(), error_msg);
2286 if (header == nullptr) {
2287 return std::string();
2288 }
2289 if (header->GetComponentCount() == 0u || header->GetComponentCount() > boot_class_path.size()) {
2290 *error_msg = StringPrintf("Unexpected component count in %s, received %u, "
2291 "expected non-zero and <= %zu",
2292 filename.c_str(),
2293 header->GetComponentCount(),
2294 boot_class_path.size());
2295 return std::string();
2296 }
2297
2298 std::string boot_image_checksum =
2299 StringPrintf("i;%d/%08x", header->GetComponentCount(), header->GetImageChecksum());
2300 ArrayRef<const std::string> boot_class_path_tail =
2301 ArrayRef<const std::string>(boot_class_path).SubArray(header->GetComponentCount());
2302 for (const std::string& bcp_filename : boot_class_path_tail) {
2303 std::vector<std::unique_ptr<const DexFile>> dex_files;
2304 const ArtDexFileLoader dex_file_loader;
2305 if (!dex_file_loader.Open(bcp_filename.c_str(),
2306 bcp_filename, // The location does not matter here.
2307 /*verify=*/ false,
2308 /*verify_checksum=*/ false,
2309 error_msg,
2310 &dex_files)) {
2311 return std::string();
2312 }
2313 DCHECK(!dex_files.empty());
2314 StringAppendF(&boot_image_checksum, ":d");
2315 for (const std::unique_ptr<const DexFile>& dex_file : dex_files) {
2316 StringAppendF(&boot_image_checksum, "/%08x", dex_file->GetLocationChecksum());
2317 }
2318 }
2319 return boot_image_checksum;
2320}
2321
2322std::string ImageSpace::GetBootClassPathChecksums(
2323 const std::vector<ImageSpace*>& image_spaces,
2324 const std::vector<const DexFile*>& boot_class_path) {
2325 DCHECK(!image_spaces.empty());
2326 const ImageHeader& primary_header = image_spaces.front()->GetImageHeader();
2327 uint32_t component_count = primary_header.GetComponentCount();
2328 DCHECK_EQ(component_count, image_spaces.size());
2329 std::string boot_image_checksum =
2330 StringPrintf("i;%d/%08x", component_count, primary_header.GetImageChecksum());
2331 size_t pos = 0u;
2332 for (const ImageSpace* space : image_spaces) {
2333 size_t num_dex_files = space->oat_file_non_owned_->GetOatDexFiles().size();
2334 if (kIsDebugBuild) {
2335 CHECK_NE(num_dex_files, 0u);
2336 CHECK_LE(space->oat_file_non_owned_->GetOatDexFiles().size(), boot_class_path.size() - pos);
2337 for (size_t i = 0; i != num_dex_files; ++i) {
2338 CHECK_EQ(space->oat_file_non_owned_->GetOatDexFiles()[i]->GetDexFileLocation(),
2339 boot_class_path[pos + i]->GetLocation());
2340 }
2341 }
2342 pos += num_dex_files;
2343 }
2344 ArrayRef<const DexFile* const> boot_class_path_tail =
2345 ArrayRef<const DexFile* const>(boot_class_path).SubArray(pos);
2346 DCHECK(boot_class_path_tail.empty() ||
2347 !DexFileLoader::IsMultiDexLocation(boot_class_path_tail.front()->GetLocation().c_str()));
2348 for (const DexFile* dex_file : boot_class_path_tail) {
2349 if (!DexFileLoader::IsMultiDexLocation(dex_file->GetLocation().c_str())) {
2350 StringAppendF(&boot_image_checksum, ":d");
2351 }
2352 StringAppendF(&boot_image_checksum, "/%08x", dex_file->GetLocationChecksum());
2353 }
2354 return boot_image_checksum;
2355}
2356
Vladimir Marko91f10322018-12-07 18:04:10 +00002357std::vector<std::string> ImageSpace::ExpandMultiImageLocations(
2358 const std::vector<std::string>& dex_locations,
2359 const std::string& image_location) {
Vladimir Marko0ace5632018-12-14 11:11:47 +00002360 return ExpandMultiImageLocations(ArrayRef<const std::string>(dex_locations), image_location);
2361}
2362
2363std::vector<std::string> ImageSpace::ExpandMultiImageLocations(
2364 ArrayRef<const std::string> dex_locations,
2365 const std::string& image_location) {
Vladimir Marko91f10322018-12-07 18:04:10 +00002366 DCHECK(!dex_locations.empty());
Andreas Gampe8994a042015-12-30 19:03:17 +00002367
Vladimir Marko91f10322018-12-07 18:04:10 +00002368 // Find the path.
2369 size_t last_slash = image_location.rfind('/');
2370 CHECK_NE(last_slash, std::string::npos);
Andreas Gampe8994a042015-12-30 19:03:17 +00002371
Vladimir Marko91f10322018-12-07 18:04:10 +00002372 // We also need to honor path components that were encoded through '@'. Otherwise the loading
2373 // code won't be able to find the images.
2374 if (image_location.find('@', last_slash) != std::string::npos) {
2375 last_slash = image_location.rfind('@');
Andreas Gampe8994a042015-12-30 19:03:17 +00002376 }
Andreas Gampe8994a042015-12-30 19:03:17 +00002377
Vladimir Marko91f10322018-12-07 18:04:10 +00002378 // Find the dot separating the primary image name from the extension.
2379 size_t last_dot = image_location.rfind('.');
2380 // Extract the extension and base (the path and primary image name).
2381 std::string extension;
2382 std::string base = image_location;
2383 if (last_dot != std::string::npos && last_dot > last_slash) {
2384 extension = image_location.substr(last_dot); // Including the dot.
2385 base.resize(last_dot);
Andreas Gampe8994a042015-12-30 19:03:17 +00002386 }
Vladimir Marko91f10322018-12-07 18:04:10 +00002387 // For non-empty primary image name, add '-' to the `base`.
2388 if (last_slash + 1u != base.size()) {
2389 base += '-';
2390 }
2391
2392 std::vector<std::string> locations;
2393 locations.reserve(dex_locations.size());
2394 locations.push_back(image_location);
2395
2396 // Now create the other names. Use a counted loop to skip the first one.
2397 for (size_t i = 1u; i < dex_locations.size(); ++i) {
2398 // Replace path with `base` (i.e. image path and prefix) and replace the original
2399 // extension (if any) with `extension`.
2400 std::string name = dex_locations[i];
2401 size_t last_dex_slash = name.rfind('/');
2402 if (last_dex_slash != std::string::npos) {
2403 name = name.substr(last_dex_slash + 1);
2404 }
2405 size_t last_dex_dot = name.rfind('.');
2406 if (last_dex_dot != std::string::npos) {
2407 name.resize(last_dex_dot);
2408 }
2409 locations.push_back(base + name + extension);
2410 }
2411 return locations;
Andreas Gampe8994a042015-12-30 19:03:17 +00002412}
2413
Mathieu Chartierd5f3f322016-03-21 14:05:56 -07002414void ImageSpace::DumpSections(std::ostream& os) const {
2415 const uint8_t* base = Begin();
2416 const ImageHeader& header = GetImageHeader();
2417 for (size_t i = 0; i < ImageHeader::kSectionCount; ++i) {
2418 auto section_type = static_cast<ImageHeader::ImageSections>(i);
2419 const ImageSection& section = header.GetImageSection(section_type);
2420 os << section_type << " " << reinterpret_cast<const void*>(base + section.Offset())
2421 << "-" << reinterpret_cast<const void*>(base + section.End()) << "\n";
2422 }
2423}
2424
Ian Rogers1d54e732013-05-02 21:10:01 -07002425} // namespace space
2426} // namespace gc
2427} // namespace art